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.NodeTemplateOperation;
58 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
59 import org.openecomp.sdc.be.model.operations.api.*;
60 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
61 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
62 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
63 import org.openecomp.sdc.be.resources.data.ESArtifactData;
64 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
65 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
66 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
67 import org.openecomp.sdc.be.servlets.RepresentationUtils;
68 import org.openecomp.sdc.be.tosca.CsarUtils;
69 import org.openecomp.sdc.be.tosca.ToscaError;
70 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
71 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
72 import org.openecomp.sdc.be.user.IUserBusinessLogic;
73 import org.openecomp.sdc.be.user.Role;
74 import org.openecomp.sdc.be.user.UserBusinessLogic;
75 import org.openecomp.sdc.be.utils.TypeUtils;
76 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
77 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
78 import org.openecomp.sdc.common.api.Constants;
79 import org.openecomp.sdc.common.datastructure.Wrapper;
80 import org.openecomp.sdc.common.log.wrappers.Logger;
81 import org.openecomp.sdc.common.util.GeneralUtility;
82 import org.openecomp.sdc.common.util.ValidationUtils;
83 import org.openecomp.sdc.common.util.YamlToObjectConverter;
84 import org.openecomp.sdc.exception.ResponseFormat;
86 import org.springframework.beans.factory.annotation.Autowired;
88 import org.yaml.snakeyaml.Yaml;
90 import javax.servlet.http.HttpServletRequest;
91 import javax.xml.XMLConstants;
92 import javax.xml.parsers.ParserConfigurationException;
93 import javax.xml.parsers.SAXParserFactory;
94 import java.io.ByteArrayInputStream;
95 import java.io.IOException;
96 import java.math.BigDecimal;
98 import java.util.Map.Entry;
99 import java.util.function.Predicate;
100 import java.util.function.Supplier;
101 import java.util.stream.Collectors;
103 @org.springframework.stereotype.Component("artifactBusinessLogic")
104 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
105 private static final String RESOURCE_INSTANCE = "resource instance";
106 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
107 private static final String ARTIFACT_DESCRIPTION = "artifact description";
108 private static final String ARTIFACT_LABEL = "artifact label";
109 private static final String ARTIFACT_URL = "artifact url";
110 private static final String ARTIFACT_NAME = "artifact name";
111 private static final String ARTIFACT_PAYLOAD = "artifact payload";
113 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
114 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
115 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
117 public static final String HEAT_ENV_NAME = "heatEnv";
118 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
119 public static final String HEAT_ENV_SUFFIX = "env";
120 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
122 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
123 public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
124 public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
125 public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
126 public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
127 public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
128 public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
129 public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
130 public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
131 public static final String NULL_PARAMETER = "One of the function parameteres is null";
132 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
133 public static final String ROLLBACK = "all changes rollback";
134 public static final String COMMIT = "all changes committed";
135 public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
136 public static final String UPDATE_ARTIFACT = "Update Artifact";
137 public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
138 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
140 @javax.annotation.Resource
141 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
142 @javax.annotation.Resource
143 private IUserAdminOperation userOperaton;
145 @javax.annotation.Resource
146 private IElementOperation elementOperation;
148 @javax.annotation.Resource
149 private ResourceBusinessLogic resourceBusinessLogic;
151 @javax.annotation.Resource
152 private ServiceBusinessLogic serviceBusinessLogic;
154 @javax.annotation.Resource
155 private UserBusinessLogic userAdminManager;
157 @javax.annotation.Resource
158 private IHeatParametersOperation heatParametersOperation;
161 private ArtifactCassandraDao artifactCassandraDao;
164 private ToscaExportHandler toscaExportUtils;
167 private CsarUtils csarUtils;
170 private LifecycleBusinessLogic lifecycleBusinessLogic;
173 private IUserBusinessLogic userBusinessLogic;
176 private NodeTemplateOperation nodeTemplateOperation;
179 private ArtifactsResolver artifactsResolver;
181 public enum ArtifactOperationEnum {
182 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
184 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
185 return operation == CREATE || operation == LINK;
189 public class ArtifactOperationInfo {
191 private ArtifactOperationEnum artifactOperationEnum;
192 private boolean isExternalApi;
193 private boolean ignoreLifecycleState;
195 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
196 this.artifactOperationEnum = artifactOperationEnum;
197 this.isExternalApi = isExternalApi;
198 this.ignoreLifecycleState = ignoreLifecycleState;
201 public boolean isExternalApi() {
202 return isExternalApi;
205 public boolean ignoreLifecycleState() {
206 return ignoreLifecycleState;
209 public ArtifactOperationEnum getArtifactOperationEnum() {
210 return artifactOperationEnum;
216 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
217 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
218 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
221 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
222 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
224 // step 1 - detect auditing type
225 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
226 // step 2 - check header
227 if (userId == null) {
228 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
229 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
230 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
231 return Either.right(responseFormat);
233 // step 3 - check user existence
234 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
235 if (userResult.isRight()) {
236 return Either.right(userResult.right().value());
239 // step 4 - check user's role
240 User user = userResult.left().value();
241 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
242 if (validateUserRole.isRight()) {
243 return Either.right(validateUserRole.right().value());
247 // 5. check service/resource existence
248 // 6. check service/resource check out
249 // 7. user is owner of checkout state
250 org.openecomp.sdc.be.model.Component component = null;
251 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
252 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
253 if (validateComponent.isRight()) {
254 return Either.right(validateComponent.right().value());
256 component = validateComponent.left().value();
257 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
258 if (validateWorkOnResource.isRight()) {
259 return Either.right(validateWorkOnResource.right().value());
263 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
264 shouldLock, inTransaction, true);
268 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
269 * For regular usage use <br>
270 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
274 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
275 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
276 Component parent = component;
277 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
279 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
280 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
282 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
283 if (errorWrapper.isEmpty()) {
285 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
288 result = Either.right(errorWrapper.getInnerElement());
293 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
294 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
295 ArtifactDefinition validatedArtifactInfo = artifactInfo;
296 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
297 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
298 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
299 if (validateArtifact.isRight()) {
300 ResponseFormat responseFormat = validateArtifact.right().value();
301 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
302 errorWrapper.setInnerElement(validateArtifact.right().value());
304 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
305 validatedArtifactInfo = validateArtifact.left().value();
306 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
309 return validatedArtifactInfo;
312 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
313 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
314 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
316 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
317 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
318 ComponentInstance componentInstance = component.getComponentInstances()
320 .filter(p -> p.getUniqueId().equals(componentId))
323 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
325 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
327 .filter(p -> p.getUniqueId()
328 .equals(validatedArtifact.getUniqueId()))
331 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
332 .getName(), user, componentId, shouldLock, inTransaction);
333 if (eitherGenerated.isRight()) {
334 errorWrapper.setInnerElement(eitherGenerated.right().value());
339 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
340 boolean needGenerate;
341 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
342 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
343 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
344 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
345 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
349 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
350 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
352 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
355 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
356 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
358 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
359 if (generated.isRight()) {
362 byte[] decodedPayload = artifactDefinition.getPayloadData();
363 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
364 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
365 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
366 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
367 shouldLock, inTransaction);
371 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
372 log.debug("tosca artifact generation");
373 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
374 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
376 if (generated.isRight()) {
377 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
380 return Either.right(generated.right().value());
382 byte[] value = generated.left().value();
383 artifactInfo.setPayload(value);
387 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
388 if (exportComponent.isRight()) {
389 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
391 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
392 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
393 return Either.right(responseFormat);
395 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
396 String payload = exportComponent.left().value().getMainYaml();
397 artifactInfo.setPayloadData(payload);
399 return Either.left(Either.left(artifactInfo));
402 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
403 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
404 switch (operation.getArtifactOperationEnum()) {
406 if (artifactGenerationRequired(parent, artifactInfo)) {
407 return generateNotSavedArtifact(parent, artifactInfo);
409 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
411 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
413 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
414 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
415 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
416 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
417 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
418 if (needUpdateGroup && result.isLeft()) {
419 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
420 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
421 .value(), parent, componentType, componentId);
422 if (error != ActionStatus.OK) {
423 result = Either.right(componentsUtils.getResponseFormat(error));
428 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
429 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
432 if (result == null) {
433 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
434 if (needUpdateGroup && result.isLeft()) {
435 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
437 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
438 .value(), parent, componentType);
439 if (error != ActionStatus.OK) {
440 result = Either.right(componentsUtils.getResponseFormat(error));
446 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
448 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
453 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
454 List<GroupDefinition> groups = parent.getGroups();
455 if (groups != null && !groups.isEmpty()) {
456 List<GroupDataDefinition> groupToUpdate = groups.stream()
457 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
458 .contains(artifactInfo
460 .collect(Collectors.toList());
461 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
462 groupToUpdate.forEach(g -> {
463 g.getArtifacts().remove(artifactInfo.getUniqueId());
464 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
465 g.getArtifacts().add(artAfterUpdate.getUniqueId());
466 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
468 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
469 if (status.isRight()) {
470 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
471 return componentsUtils.convertFromStorageResponse(status.right().value());
475 return ActionStatus.OK;
478 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
479 List<GroupDefinition> groups = parent.getGroups();
480 if (groups != null && !groups.isEmpty()) {
481 List<GroupDataDefinition> groupToUpdate = groups.stream()
482 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
483 .contains(artifactInfoHeat
485 .collect(Collectors.toList());
486 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
487 groupToUpdate.forEach(g -> {
488 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
489 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
490 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
491 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
492 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
493 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
495 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
496 if (status.isRight()) {
497 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
498 return componentsUtils.convertFromStorageResponse(status.right().value());
502 return ActionStatus.OK;
505 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
506 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
507 List<GroupInstance> groupInstances = null;
508 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
510 .filter(ci -> ci.getUniqueId().equals(parentId))
512 if (componentInstOp.isPresent()) {
513 groupInstances = componentInstOp.get().getGroupInstances();
515 if (CollectionUtils.isNotEmpty(groupInstances)) {
516 boolean isUpdated = false;
517 for (GroupInstance groupInstance : groupInstances) {
519 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
520 .contains(artifactInfo
522 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
523 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
526 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
527 .contains(artifactInfo
528 .getArtifactUUID())) {
529 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
530 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
534 updatedGroupInstances.add(groupInstance);
538 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
539 if (status.isRight()) {
540 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
541 return componentsUtils.convertFromStorageResponse(status.right().value());
543 return ActionStatus.OK;
546 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
547 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
548 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
549 result = generateToscaArtifact(parent, artifactInfo, false, false);
552 String heatArtifactId = artifactInfo.getGeneratedFromId();
553 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
554 if (heatRes.isRight()) {
555 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
557 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
560 return Either.right(responseFormat);
562 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
563 artifactInfo.setPayloadData(generatedPayload);
564 result = Either.left(Either.left(artifactInfo));
569 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
570 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
571 convertParentType(componentType);
572 String parentId = parent.getUniqueId();
573 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
574 .getGeneratedFromId());
575 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
577 if (origMd5 != null) {
578 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
579 if (validateMd5.isRight()) {
580 ResponseFormat responseFormat = validateMd5.right().value();
581 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
582 return Either.right(responseFormat);
585 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
587 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
588 if (payloadEither.isRight()) {
589 ResponseFormat responseFormat = payloadEither.right().value();
590 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
591 return Either.right(responseFormat);
595 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
596 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
597 return Either.right(responseFormat);
603 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
604 if (lockComponent.isRight()) {
605 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
606 .value(), componentType, null);
607 return Either.right(lockComponent.right().value());
610 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
612 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
618 if (resultOp == null || resultOp.isRight()) {
620 if (!inTransaction) {
626 if (!inTransaction) {
631 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
636 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
637 if (artifactGenerationRequired(component, csarArtifact)) {
638 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
640 if (generated.isRight()) {
641 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
644 return Either.right(generated.right().value());
646 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
649 return downloadArtifact(csarArtifact);
652 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
653 // perform all validation in common flow
654 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
655 null, parentId, containerComponentType);
656 if (result.isRight()) {
657 return Either.right(result.right().value());
659 ArtifactDefinition artifactDefinition;
660 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
661 if (insideValue.isLeft()) {
662 artifactDefinition = insideValue.left().value();
665 artifactDefinition = insideValue.right().value().getImplementationArtifact();
667 // for tosca artifacts and heat env on VF level generated on download without saving
668 if (artifactDefinition.getPayloadData() != null) {
669 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
672 return downloadArtifact(artifactDefinition);
675 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
677 // detect auditing type
678 Map<String, ArtifactDefinition> resMap = null;
679 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
684 if (userId == null) {
685 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
686 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
688 resultOp = Either.right(responseFormat);
692 // check user existence
696 validateUserExists(userId, "get artifacts", false);
698 // 5. check service/resource existence
699 // 6. check service/resource check out
700 // 7. user is owner of checkout state
701 org.openecomp.sdc.be.model.Component component = null;
702 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
703 ComponentParametersView componentFilter = new ComponentParametersView();
704 componentFilter.disableAll();
705 componentFilter.setIgnoreArtifacts(false);
706 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
707 componentFilter.setIgnoreComponentInstances(false);
710 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
711 .findByParamName(containerComponentType), componentFilter);
713 if (validateComponent.isRight()) {
714 resultOp = Either.right(validateComponent.right().value());
717 component = validateComponent.left().value();
718 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
719 if (lockComponent.isRight()) {
721 resultOp = Either.right(lockComponent.right().value());
726 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
728 if (groupType == null) {
729 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
730 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
732 resultOp = Either.right(responseFormat);
736 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
737 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
738 if (list != null && !list.isEmpty()) {
739 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
742 resMap = new HashMap<>();
744 resultOp = Either.left(resMap);
749 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
750 .getNodeType(), groupType, componentId);
751 if (artifactsMapStatus.isRight()) {
752 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
753 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
754 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
755 resultOp = Either.right(responseFormat);
758 resMap = new HashMap<>();
759 resultOp = Either.left(resMap);
763 resMap = artifactsMapStatus.left().value();
764 resultOp = Either.left(resMap);
771 if (resultOp == null || resultOp.isRight()) {
780 componentType = component.getComponentType();
781 NodeTypeEnum nodeType = componentType.getNodeType();
782 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
787 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
789 // check artifact existence
790 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
792 if (artifactResult.isRight()) {
793 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
794 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
795 log.debug("addArtifact - artifact {} not found", artifactId);
796 return Either.right(responseFormat);
800 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
803 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
805 return Either.right(responseFormat);
809 // check artifact belong to component
810 boolean found = false;
811 switch (componentType) {
814 found = checkArtifactInComponent(component, artifactId);
816 case RESOURCE_INSTANCE:
817 found = checkArtifactInResourceInstance(component, componentId, artifactId);
823 String componentName = componentType.name().toLowerCase();
824 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
825 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
826 return Either.right(responseFormat);
828 return Either.left(artifactResult.left().value());
831 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
832 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
834 String artifactId = null;
837 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
838 if (payloadEither.isRight()) {
839 return Either.right(payloadEither.right().value());
841 byte[] decodedPayload = payloadEither.left().value();
842 convertParentType(componentType);
845 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
846 if (lockComponent.isRight()) {
847 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
848 .value(), componentType, null);
849 return Either.right(lockComponent.right().value());
852 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
855 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
860 unlockComponent(resultOp, parent, inTransaction);
867 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
868 Component parent, boolean shouldLock, boolean inTransaction) {
871 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
872 if (lockComponent.isRight()) {
873 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
874 .value(), componentType, null);
875 return Either.right(lockComponent.right().value());
878 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
881 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
886 unlockComponent(resultOp, parent, inTransaction);
893 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
894 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
896 convertParentType(componentType);
900 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
902 if (lockComponent.isRight()) {
903 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
904 .value(), componentType, null);
905 return Either.right(lockComponent.right().value());
909 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
911 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
917 unlockComponent(resultOp, parent, inTransaction);
922 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
923 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
925 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
927 if (payloadEither.isRight()) {
928 return Either.right(payloadEither.right().value());
930 byte[] decodedPayload = payloadEither.left().value();
932 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
935 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
936 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
938 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
939 if (validateMd5.isRight()) {
940 ResponseFormat responseFormat = validateMd5.right().value();
941 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
942 return Either.right(responseFormat);
946 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
947 if (validateResult.isRight()) {
948 ResponseFormat responseFormat = validateResult.right().value();
949 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
950 return Either.right(validateResult.right().value());
953 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
954 if (payloadEither.isRight()) {
955 ResponseFormat responseFormat = payloadEither.right().value();
956 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
957 log.debug("Error during handle payload");
958 return Either.right(responseFormat);
961 // validate heat parameters. this part must be after the parameters are
962 // extracted in "handlePayload"
963 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
965 if (validateAndConvertHeatParamers.isRight()) {
966 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
967 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
968 log.debug("Error during handle payload");
969 return Either.right(responseFormat);
971 return payloadEither;
974 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
975 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
977 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
983 user.setUserId("UNKNOWN");
985 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
988 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
989 switch (componentTypeEnum) {
991 Resource resource = (Resource) component;
992 if (resource == null) {
993 // In that case, component ID should be instead of name
994 resource = new Resource();
995 resource.setName(componentId);
997 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
998 ResourceVersionInfo.newBuilder()
999 .artifactUuid(prevArtifactUuid)
1000 .build(), currentArtifactUuid, artifactDefinition);
1004 Service service = (Service) component;
1005 if (service == null) {
1006 // In that case, component ID should be instead of name
1007 service = new Service();
1008 service.setName(componentId);
1010 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1011 ResourceVersionInfo.newBuilder()
1012 .artifactUuid(prevArtifactUuid)
1014 ResourceVersionInfo.newBuilder()
1015 .artifactUuid(currentArtifactUuid)
1017 null, artifactDefinition, null);
1020 case RESOURCE_INSTANCE:
1021 if (resourceInstanceName == null) {
1022 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1024 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1025 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1026 ResourceVersionInfo.newBuilder()
1027 .artifactUuid(prevArtifactUuid)
1029 ResourceVersionInfo.newBuilder()
1030 .artifactUuid(currentArtifactUuid)
1032 null, artifactDefinition, null);
1039 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1040 ComponentInstance resourceInstance = component.getComponentInstances()
1042 .filter(p -> p.getUniqueId().equals(componentId))
1045 String resourceInstanceName = null;
1046 if (resourceInstance != null) {
1047 resourceInstanceName = resourceInstance.getName();
1049 return resourceInstanceName;
1052 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1053 StringBuilder sb = new StringBuilder();
1054 if (artifactDefinition != null) {
1055 sb.append(artifactDefinition.getArtifactGroupType().getType())
1058 .append(artifactDefinition.getArtifactLabel())
1061 .append(artifactDefinition.getArtifactType())
1063 .append(artifactDefinition.getArtifactName())
1065 .append(artifactDefinition.getTimeout())
1067 .append(artifactDefinition.getEsId());
1070 if (artifactDefinition.getArtifactVersion() != null) {
1072 sb.append(artifactDefinition.getArtifactVersion());
1078 if (artifactDefinition.getArtifactUUID() != null) {
1079 sb.append(artifactDefinition.getArtifactUUID());
1085 return sb.toString();
1088 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1090 if (origMd5 != null) {
1091 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1092 if (!encodeBase64Str.equals(origMd5)) {
1093 log.debug("The calculated md5 is different then the received one");
1094 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1098 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1099 log.debug("Missing md5 header during artifact create");
1100 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1103 if (payload != null && payload.length != 0) {
1104 log.debug("Cannot have payload while md5 header is missing");
1105 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1108 return Either.left(true);
1111 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1112 ComponentTypeEnum componentType, Component parentComponent) {
1114 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1115 if (artifactById.isRight()) {
1116 return Either.right(artifactById.right().value());
1118 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1120 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1121 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1122 if (validateInformationalArtifactRes.isRight()) {
1123 return Either.right(validateInformationalArtifactRes.right().value());
1125 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1126 if (validateAndSetArtifactname.isRight()) {
1127 return Either.right(validateAndSetArtifactname.right().value());
1129 if (operationName != null && interfaceName != null) {
1130 operationName = operationName.toLowerCase();
1131 interfaceName = interfaceName.toLowerCase();
1133 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1134 if (logicalNameStatus.isRight()) {
1135 return Either.right(logicalNameStatus.right().value());
1137 // This is a patch to block possibility of updating service api fields
1138 // through other artifacts flow
1140 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1141 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1142 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1145 checkCreateFields(user, artifactInfo, artifactGroupType);
1148 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1149 if (currentArtifactInfo != null) {
1150 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1153 // artifactGroupType is not allowed to be updated
1154 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1155 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1156 if (validateGroupType.isRight()) {
1157 return Either.right(validateGroupType.right().value());
1160 NodeTypeEnum parentType = convertParentType(componentType);
1162 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1164 if (isDeploymentArtifact(artifactInfo)) {
1165 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1166 if (deploymentValidationResult.isRight()) {
1167 return Either.right(deploymentValidationResult.right().value());
1171 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1174 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1175 if (descriptionResult.isRight()) {
1176 return Either.right(descriptionResult.right().value());
1179 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1180 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1181 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1182 if (validateServiceApiType.isRight()) {
1183 return Either.right(validateServiceApiType.right().value());
1185 // Change of type is not allowed and should be ignored
1187 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1189 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1190 if (validateUrl.isRight()) {
1191 return Either.right(validateUrl.right().value());
1194 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1195 if (validateUpdate.isRight()) {
1196 log.debug("serviceApi first update cnnot be without payload.");
1197 return Either.right(validateUpdate.right().value());
1201 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1202 if (validateArtifactType.isRight()) {
1203 return Either.right(validateArtifactType.right().value());
1205 if (artifactInfo.getApiUrl() != null) {
1206 artifactInfo.setApiUrl(null);
1207 log.error("Artifact URL cannot be set through this API - ignoring");
1210 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1211 artifactInfo.setServiceApi(false);
1212 log.error("Artifact service API flag cannot be changed - ignoring");
1216 return Either.left(artifactInfo);
1219 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1220 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1221 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1222 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1223 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1227 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1229 Either<ArtifactDefinition, ResponseFormat> result = null;
1230 ArtifactDefinition foundArtifact = null;
1231 if (StringUtils.isNotEmpty(artifactId)) {
1232 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1234 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1235 log.debug("Artifact {} already exist", artifactId);
1236 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1238 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1239 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1240 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1242 if (result == null) {
1243 result = Either.left(foundArtifact);
1248 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1249 ArtifactDefinition foundArtifact;
1250 if (parentComponent.getUniqueId().equals(parentId)) {
1251 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1254 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1255 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1257 return foundArtifact;
1260 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1261 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1262 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1263 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1264 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1265 if (artifactType == null) {
1266 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1267 .getArtifactType()));
1269 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1270 String artifactTypeName = artifactType.getType();
1271 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1272 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1274 .getResourceInformationalArtifacts();
1275 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1276 if (!validArtifactTypes.contains(artifactTypeName)) {
1277 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1280 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1281 .getValidForResourceTypes();
1282 if (!validResourceType.contains(parentResourceType.name())) {
1283 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1287 return validationResult;
1290 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1291 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1292 return NodeTypeEnum.Resource;
1294 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1295 return NodeTypeEnum.ResourceInstance;
1298 return NodeTypeEnum.Service;
1302 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1303 boolean shouldLock, boolean inTransaction) {
1305 NodeTypeEnum parentType = convertParentType(componentType);
1306 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1307 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1308 ArtifactDefinition foundArtifact = null;
1309 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1310 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1311 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1312 boolean isDuplicated = false;
1314 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1317 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1318 if (lockComponent.isRight()) {
1319 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1320 .value(), componentType, null);
1321 resultOp = Either.right(lockComponent.right().value());
1324 if (resultOp == null) {
1325 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1326 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1327 if (getContainerRes.isRight()) {
1328 log.debug("Failed to fetch the container component {}. ", parentId);
1329 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1331 .value()), artifactId);
1332 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1333 resultOp = Either.right(responseFormat);
1336 if (resultOp == null) {
1337 fetchedContainerComponent = getContainerRes.left().value();
1338 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1339 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1340 if (getArtifactRes.isRight()) {
1341 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1343 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1344 .value(), artifactId);
1345 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1346 resultOp = Either.right(responseFormat);
1349 foundArtifact = getArtifactRes.left().value().getLeft();
1350 esId = foundArtifact.getEsId();
1353 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1354 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1355 .getComponentType()));
1356 if (needCloneRes.isRight()) {
1357 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1358 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1360 .value()), foundArtifact.getArtifactDisplayName());
1361 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1362 resultOp = Either.right(responseFormat);
1365 boolean isNeedToDeleteArtifactFromDB = true;
1366 if (resultOp == null) {
1368 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1369 String instanceId = parentId;
1370 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1372 if (isOnlyResourceInstanceArtifact.isRight()) {
1373 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1374 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1375 .value(), foundArtifact
1376 .getArtifactDisplayName());
1377 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1378 return Either.right(responseFormat);
1380 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1383 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1386 if (updatedArtifactRes.isRight()) {
1387 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1388 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1390 .value()), foundArtifact.getArtifactDisplayName());
1391 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1392 resultOp = Either.right(responseFormat);
1395 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1399 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1400 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1401 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1402 if (cassandraStatus != CassandraOperationStatus.OK) {
1403 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1404 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1405 .getArtifactDisplayName());
1406 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1407 resultOp = Either.right(responseFormat);
1410 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1412 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1416 .getGroupInstances());
1417 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1418 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1419 if (status.isRight()) {
1420 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1421 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1423 .value()), foundArtifact.getArtifactDisplayName());
1424 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1425 resultOp = Either.right(responseFormat);
1429 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1430 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1431 if (status != StorageOperationStatus.OK) {
1432 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1433 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1434 .getArtifactDisplayName());
1435 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1436 resultOp = Either.right(responseFormat);
1439 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1440 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1442 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1443 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1444 if (status.isRight()) {
1445 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1446 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1448 .value()), foundArtifact.getArtifactDisplayName());
1449 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1450 resultOp = Either.right(responseFormat);
1454 if (resultOp == null) {
1455 resultOp = Either.left(Either.left(foundArtifact));
1456 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1462 unlockComponent(resultOp, parent, inTransaction);
1467 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1468 Either<Boolean, ActionStatus> result = Either.left(true);
1469 ComponentInstance foundInstance = null;
1470 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1472 .filter(i -> i.getUniqueId().equals(instanceId))
1474 if (!componentInstanceOpt.isPresent()) {
1475 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1478 foundInstance = componentInstanceOpt.get();
1479 String componentUid = foundInstance.getComponentUid();
1480 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1481 if (getContainerRes.isRight()) {
1482 log.debug("Failed to fetch the container component {}. ", componentUid);
1483 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1485 Component origComponent = getContainerRes.left().value();
1486 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1487 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1488 Optional<String> op = deploymentArtifacts.keySet()
1490 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1492 if (op.isPresent()) {
1493 return Either.left(false);
1496 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1497 if (artifacts != null && !artifacts.isEmpty()) {
1498 Optional<String> op = artifacts.keySet()
1500 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1502 if (op.isPresent()) {
1503 return Either.left(false);
1511 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1512 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1513 boolean isUpdated = false;
1514 if (groups != null) {
1515 for (GroupDefinition group : groups) {
1517 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1518 group.getArtifacts().remove(artifactId);
1521 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1522 .contains(foundArtifact.getArtifactUUID())) {
1523 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1527 updatedGroups.add(group);
1531 return updatedGroups;
1534 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1535 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1536 if (CollectionUtils.isNotEmpty(groupInstances)) {
1537 boolean isUpdated = false;
1538 for (GroupInstance groupInstance : groupInstances) {
1540 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1541 .contains(artifactId)) {
1542 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1545 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1546 .contains(foundArtifact
1547 .getArtifactUUID())) {
1548 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1552 updatedGroupInstances.add(groupInstance);
1556 return updatedGroupInstances;
1559 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1561 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1562 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1563 String componentId = component.getUniqueId();
1564 String instanceId = componentId.equals(parentId) ? null : parentId;
1566 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1567 resetMandatoryArtifactFields(foundArtifact);
1568 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1570 else if (cloneIsNeeded) {
1571 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1572 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1575 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1576 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1581 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1583 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1584 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1585 ComponentInstance foundInstance = null;
1586 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1587 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1589 .filter(i -> i.getUniqueId()
1592 if (!componentInstanceOpt.isPresent()) {
1593 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1596 foundInstance = componentInstanceOpt.get();
1597 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1601 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1603 if (result == null) {
1604 if (artifacts.containsKey(artifactId)) {
1605 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1608 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1614 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1615 Map<String, ArtifactDefinition> currArtifacts;
1616 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1617 currArtifacts = component.getDeploymentArtifacts()
1620 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1621 if (MapUtils.isNotEmpty(currArtifacts)) {
1622 artifacts.putAll(currArtifacts);
1625 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1626 currArtifacts = component.getArtifacts()
1629 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1630 if (MapUtils.isNotEmpty(currArtifacts)) {
1631 artifacts.putAll(currArtifacts);
1634 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1635 currArtifacts = component.getToscaArtifacts()
1638 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1639 if (MapUtils.isNotEmpty(currArtifacts)) {
1640 artifacts.putAll(currArtifacts);
1645 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1646 Map<String, ArtifactDefinition> currArtifacts;
1647 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1648 currArtifacts = instance.getDeploymentArtifacts()
1651 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1652 if (MapUtils.isNotEmpty(currArtifacts)) {
1653 artifacts.putAll(currArtifacts);
1656 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1657 currArtifacts = instance.getArtifacts()
1660 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1661 if (MapUtils.isNotEmpty(currArtifacts)) {
1662 artifacts.putAll(currArtifacts);
1667 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1668 if (fetchedArtifact != null) {
1669 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1670 fetchedArtifact.setEsId(null);
1671 fetchedArtifact.setArtifactName(null);
1672 fetchedArtifact.setDescription(null);
1673 fetchedArtifact.setApiUrl(null);
1674 fetchedArtifact.setArtifactChecksum(null);
1675 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1676 fetchedArtifact.setArtifactUUID(null);
1677 long time = System.currentTimeMillis();
1678 fetchedArtifact.setPayloadUpdateDate(time);
1679 fetchedArtifact.setHeatParameters(null);
1680 fetchedArtifact.setHeatParamsUpdateDate(null);
1684 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1685 StorageOperationStatus error = StorageOperationStatus.OK;
1686 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1687 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1688 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1693 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1695 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1697 if (artifactById.isRight()) {
1698 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1699 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1700 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1701 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1702 return Either.right(responseFormat);
1704 ArtifactDefinition artifactDefinition = artifactById.left().value();
1705 if (artifactDefinition == null) {
1706 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1707 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1708 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1709 return Either.right(responseFormat);
1712 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1713 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1714 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1715 return Either.left(insideEither);
1718 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1719 ComponentTypeEnum componentType) {
1721 String artifactLabel = artifactInfo.getArtifactLabel();
1722 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1724 BeEcompErrorManager.getInstance()
1725 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1726 log.debug("missing artifact logical name for component {}", componentId);
1727 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1729 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1731 if (operationName != null) {
1732 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1733 log.debug("artifact label cannot be set {}", artifactLabel);
1734 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1737 artifactLabel = operationName;
1740 String displayName = artifactInfo.getArtifactDisplayName();
1741 if (displayName == null || displayName.isEmpty()) {
1742 displayName = artifactLabel;
1744 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1745 artifactInfo.setArtifactDisplayName(displayName);
1747 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1748 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1749 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1751 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1753 if (artifactLabel.isEmpty()) {
1754 log.debug("missing normalized artifact logical name for component {}", componentId);
1755 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1758 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1759 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1760 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1761 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1763 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1764 log.debug("Non unique Artifact label : {}", artifactLabel);
1765 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1768 artifactInfo.setArtifactLabel(artifactLabel);
1770 return Either.left(ActionStatus.OK);
1773 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1774 boolean isUnique = true;
1775 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1776 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1777 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1780 artifacts = artifactToscaOperation.getArtifacts(componentId);
1783 if (artifacts.isLeft()) {
1784 for (String label : artifacts.left().value().keySet()) {
1785 if (label.equals(artifactLabel)) {
1791 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1792 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1793 .getAllInterfacesOfResource(componentId, true, true);
1794 if (allInterfacesOfResource.isLeft()) {
1795 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1796 for (Operation operation : interace.getOperationsMap().values()) {
1797 if (operation.getImplementation() != null && operation.getImplementation()
1799 .equals(artifactLabel)) {
1810 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1811 ComponentTypeEnum componentType) {
1812 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1813 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1814 String artifactName = artifactInfo.getArtifactName();
1815 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1816 if (artifacts.left().value().values().stream()
1817 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1818 //check whether it is the same artifact we hold (by label)
1819 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1823 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1824 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1829 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1830 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1831 .getAllInterfacesOfResource(componentId, true, true);
1833 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1834 return !allInterfacesOfResource.left().value()
1836 .stream().map(InterfaceDefinition :: getOperationsMap)
1837 .flatMap(map -> map.values().stream())
1838 .map(OperationDataDefinition::getImplementation)
1839 .filter(Objects::nonNull)
1840 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1841 && !artifactLabel.equals(add.getArtifactLabel()));
1846 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1847 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1848 .getAllInterfacesOfResource(componentId, true, true);
1850 if (allInterfacesOfResource.isLeft()){
1851 return !allInterfacesOfResource.left().value()
1853 .stream().map(InterfaceDefinition :: getOperationsMap)
1854 .flatMap(map -> map.values().stream())
1855 .map(OperationDataDefinition::getImplementation)
1856 .filter(Objects::nonNull)
1857 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1862 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1863 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1864 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1865 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1866 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1869 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1871 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1872 log.debug("failed to retrieve artifacts for {} ", componentId);
1873 return Either.right(artifactsResponse.right().value());
1875 return Either.left(artifactsResponse.left().value().entrySet()
1877 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1878 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1881 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1882 return artifacts.entrySet()
1884 .map(x -> x.getValue().getArtifactName())
1885 .collect(Collectors.toList());
1888 // ***************************************************************
1890 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1891 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1892 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1893 Either<ArtifactDefinition, Operation> insideEither = null;
1894 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1895 String instanceId = null;
1896 String instanceName = null;
1897 if (foundInstance != null) {
1898 instanceId = foundInstance.getUniqueId();
1899 instanceName = foundInstance.getName();
1901 boolean isLeft = false;
1902 String artifactUniqueId = null;
1903 StorageOperationStatus error = null;
1904 // information/deployment/api aritfacts
1905 log.trace("Try to create entry on graph");
1906 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1907 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1908 .getUniqueId(), nodeType, true, instanceId);
1910 isLeft = result.isLeft();
1912 artifactUniqueId = result.left().value().getUniqueId();
1913 result.left().value();
1915 insideEither = Either.left(result.left().value());
1916 resultOp = Either.left(insideEither);
1918 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1919 if (error != StorageOperationStatus.OK) {
1925 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1926 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1930 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1931 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1932 .getArtifactDisplayName());
1933 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1934 resultOp = Either.right(responseFormat);
1940 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1941 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1943 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1944 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1945 Either<ArtifactDefinition, Operation> insideEither = null;
1946 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1947 String instanceId = null;
1948 String instanceName = null;
1949 if (foundInstance != null) {
1950 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1951 log.debug("Failed to create artifact, already exists");
1952 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1953 .getArtifactLabel());
1954 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1956 resultOp = Either.right(responseFormat);
1960 instanceId = foundInstance.getUniqueId();
1961 instanceName = foundInstance.getName();
1963 if (artifactData == null) {
1964 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1965 log.debug("Failed to create artifact object for ES.");
1966 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1967 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1968 resultOp = Either.right(responseFormat);
1972 // set on graph object id of artifact in ES!
1973 artifactInfo.setEsId(artifactData.getId());
1975 boolean isLeft = false;
1976 String artifactUniqueId = null;
1977 StorageOperationStatus error = null;
1978 if (interfaceType != null && operationName != null) {
1979 // lifecycle artifact
1980 Operation operation = convertToOperation(artifactInfo, operationName);
1982 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1984 isLeft = result.isLeft();
1986 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1987 result.left().value().getImplementation();
1989 insideEither = Either.right(result.left().value());
1990 resultOp = Either.left(insideEither);
1993 error = result.right().value();
1997 // information/deployment/api aritfacts
1998 log.trace("Try to create entry on graph");
1999 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2000 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2001 .getUniqueId(), nodeType, true, instanceId);
2003 isLeft = result.isLeft();
2005 artifactUniqueId = result.left().value().getUniqueId();
2006 artifactData.setId(result.left().value().getEsId());
2007 insideEither = Either.left(result.left().value());
2008 resultOp = Either.left(insideEither);
2010 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2011 if (error != StorageOperationStatus.OK) {
2017 error = result.right().value();
2021 boolean res = saveArtifacts(artifactData, parentId);
2024 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2026 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2027 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2031 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2032 log.debug(FAILED_SAVE_ARTIFACT);
2033 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2034 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2036 resultOp = Either.right(responseFormat);
2041 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2042 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2043 .getArtifactDisplayName());
2044 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2045 resultOp = Either.right(responseFormat);
2051 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2052 ComponentInstance foundInstance = null;
2053 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2054 foundInstance = containerComponent.getComponentInstances()
2056 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2060 return foundInstance;
2063 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2065 Either<Boolean, ResponseFormat> result = Either.left(true);
2066 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2068 validateArtifactTypeExists(responseWrapper, artifactInfo);
2070 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2072 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2074 if (responseWrapper.isEmpty()) {
2075 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2078 // Common code for all types
2079 // not allowed to change artifactType
2080 if (responseWrapper.isEmpty() && !isCreate) {
2081 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2082 if (validateServiceApiType.isRight()) {
2083 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2086 if (responseWrapper.isEmpty()) {
2087 if (parentType.equals(NodeTypeEnum.Resource)) {
2088 Resource resource = (Resource) parentComponent;
2089 ResourceTypeEnum resourceType = resource.getResourceType();
2090 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2091 if (config == null) {
2092 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2093 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2094 .getArtifactType()));
2097 List<String> myList = config.getValidForResourceTypes();
2098 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2099 if (either.isRight()) {
2100 responseWrapper.setInnerElement(either.right().value());
2105 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2108 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2109 String artifactName = artifactInfo.getArtifactName();
2110 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2111 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2115 if (responseWrapper.isEmpty()) {
2116 switch (artifactType) {
2120 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2123 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2124 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2126 case DCAE_INVENTORY_TOSCA:
2127 case DCAE_INVENTORY_JSON:
2128 case DCAE_INVENTORY_POLICY:
2129 // Validation is done in handle payload.
2130 case DCAE_INVENTORY_DOC:
2131 case DCAE_INVENTORY_BLUEPRINT:
2132 case DCAE_INVENTORY_EVENT:
2133 // No specific validation
2135 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2141 if (!responseWrapper.isEmpty()) {
2142 result = Either.right(responseWrapper.getInnerElement());
2147 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2148 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2149 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2150 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2151 .getArtifactType());
2152 responseWrapper.setInnerElement(responseFormat);
2153 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2157 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2158 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2159 if (parentType.equals(NodeTypeEnum.Resource)) {
2160 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2162 .getResourceDeploymentArtifacts();
2164 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2165 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2167 .getResourceInstanceDeploymentArtifacts();
2170 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2172 .getServiceDeploymentArtifacts();
2174 return resourceDeploymentArtifacts;
2177 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2178 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2179 if (artifactType == null) {
2180 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2181 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2182 .getArtifactType());
2183 responseWrapper.setInnerElement(responseFormat);
2184 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2188 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2189 ArtifactTypeConfig retConfig = null;
2190 String fileType = artifactType.getType();
2191 if (parentType.equals(NodeTypeEnum.Resource)) {
2192 retConfig = ConfigurationManager.getConfigurationManager()
2194 .getResourceDeploymentArtifacts()
2197 else if (parentType.equals(NodeTypeEnum.Service)) {
2198 retConfig = ConfigurationManager.getConfigurationManager()
2200 .getServiceDeploymentArtifacts()
2203 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2204 retConfig = ConfigurationManager.getConfigurationManager()
2206 .getResourceInstanceDeploymentArtifacts()
2212 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2213 // extract heat parameters
2214 if (artifactInfo.getPayloadData() != null) {
2215 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2216 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2217 .getArtifactType());
2218 if (heatParameters.isRight() && (!heatParameters.right()
2220 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2221 log.info("failed to parse heat parameters ");
2222 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2223 .getArtifactType());
2224 return Either.right(responseFormat);
2226 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2227 artifactInfo.setListHeatParameters(heatParameters.left().value());
2230 return Either.left(true);
2235 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2236 String fileType = artifactType.getType();
2237 List<String> acceptedTypes = null;
2238 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2239 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2240 log.debug("parent type of artifact can be either resource or service");
2241 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2245 if (deploymentAcceptedTypes == null) {
2246 log.debug("parent type of artifact can be either resource or service");
2247 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2248 .getArtifactType()));
2252 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2255 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2258 String artifactName = artifactInfo.getArtifactName();
2259 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2260 // Pavel - File extension validation is case-insensitive - Ella,
2262 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2263 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2264 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2269 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2271 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2272 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2273 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2275 if (errorWrapper.isEmpty()) {
2276 validateValidYaml(errorWrapper, artifactInfo);
2279 if (errorWrapper.isEmpty()) {
2280 // Validate Heat Exist
2281 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2282 .getComponentType());
2285 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2286 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2289 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2290 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2294 Either<Boolean, ResponseFormat> eitherResponse;
2295 if (errorWrapper.isEmpty()) {
2296 eitherResponse = Either.left(true);
2299 eitherResponse = Either.right(errorWrapper.getInnerElement());
2301 return eitherResponse;
2304 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2305 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2306 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2307 if (fillArtifactPayload.isRight()) {
2308 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2309 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2313 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2317 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2318 Either<Boolean, ResponseFormat> result = Either.left(true);
2319 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2321 if (eitherArtifactData.isLeft()) {
2322 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2323 data = Base64.encodeBase64(data);
2324 payloadWrapper.setInnerElement(data);
2327 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2330 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2331 result = Either.right(responseFormat);
2337 @SuppressWarnings("unchecked")
2338 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2339 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2340 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2341 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2342 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2344 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2345 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2346 if (eitherHeatEnvProperties.isRight()) {
2347 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2348 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2349 errorWrapper.setInnerElement(responseFormat);
2350 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2352 else if (eitherHeatProperties.isRight()) {
2353 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2354 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2355 .getArtifactName(), heatArtifact.getArtifactName());
2356 errorWrapper.setInnerElement(responseFormat);
2357 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2358 .getArtifactName());
2361 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2362 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2363 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2364 if (!heatEnvPropertiesKeys.isEmpty()) {
2365 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2366 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2367 .getArtifactName(), heatArtifact.getArtifactName());
2368 errorWrapper.setInnerElement(responseFormat);
2373 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2374 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2375 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2377 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2378 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2379 .getArtifactType());
2380 errorWrapper.setInnerElement(responseFormat);
2381 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2385 private boolean isValidXml(byte[] xmlToParse) {
2386 boolean isXmlValid = true;
2388 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2389 setFeatures(reader);
2390 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2392 catch (ParserConfigurationException | IOException | SAXException e) {
2393 log.debug("Xml is invalid : {}", e.getMessage(), e);
2399 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2401 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2402 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2404 catch (SAXNotRecognizedException e) {
2405 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2409 private boolean isValidJson(byte[] jsonToParse) {
2410 String parsed = new String(jsonToParse);
2412 gson.fromJson(parsed, Object.class);
2414 catch (Exception e) {
2415 log.debug("Json is invalid : {}", e.getMessage(), e);
2421 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2422 boolean artifactNameFound = false;
2423 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2426 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2427 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2429 if (artifactNameFound) {
2430 String parentName = parentComponent.getName();
2431 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2432 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2433 .name(), parentName, artifactName);
2435 errorWrapper.setInnerElement(responseFormat);
2436 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2441 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2442 ComponentTypeEnum componentType) {
2443 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2444 if (res.isRight()) {
2445 ResponseFormat responseFormat;
2446 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2447 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2450 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2452 errorWrapper.setInnerElement(responseFormat);
2455 ArtifactDefinition heatArtifact = res.left().value();
2456 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2459 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2460 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2461 // timeout > 0 for HEAT artifacts
2462 Integer timeout = artifactInfo.getTimeout();
2463 if (timeout == null) {
2464 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2465 artifactInfo.setTimeout(defaultTimeout);
2466 // HEAT artifact but timeout is invalid
2468 else if (timeout < 1) {
2469 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2472 // US649856 - Allow several HEAT files on Resource
2473 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2474 return Either.left(true);
2477 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2478 String listToString = (typeList != null) ? typeList.toString() : "";
2479 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2480 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2481 .getArtifactName(), listToString, resourceType.getValue());
2482 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2483 String resourceTypeName = resourceType.name();
2484 if (typeList != null && typeList.contains(resourceTypeName)) {
2485 either = Either.left(true);
2490 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2491 if (artifactInfo.getHeatParameters() != null) {
2492 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2493 String parameterType = heatParam.getType();
2494 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2495 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2496 if (heatParameterType == null) {
2497 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2499 return Either.right(responseFormat);
2502 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2503 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2504 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2505 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2506 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2507 .getType(), heatParam.getName());
2508 return Either.right(responseFormat);
2512 return Either.left(artifactInfo);
2515 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2516 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2517 if (parentComponent.getDeploymentArtifacts() != null) {
2518 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2519 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2520 if (getRI.isRight()) {
2521 return deploymentArtifacts;
2523 ComponentInstance ri = getRI.left().value();
2524 if (ri.getDeploymentArtifacts() != null) {
2525 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2528 else if (parentComponent.getDeploymentArtifacts() != null) {
2529 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2532 return deploymentArtifacts;
2535 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2536 // on create if null add informational to current
2537 if (artifactInfo.getArtifactGroupType() == null) {
2538 artifactInfo.setArtifactGroupType(type);
2540 if (artifactInfo.getUniqueId() != null) {
2541 log.error("artifact uniqid cannot be set ignoring");
2543 artifactInfo.setUniqueId(null);
2545 if (artifactInfo.getArtifactRef() != null) {
2546 log.error("artifact ref cannot be set ignoring");
2548 artifactInfo.setArtifactRef(null);
2550 if (artifactInfo.getArtifactRepository() != null) {
2551 log.error("artifact repository cannot be set ignoring");
2553 artifactInfo.setArtifactRepository(null);
2555 if (artifactInfo.getUserIdCreator() != null) {
2556 log.error("creator uuid cannot be set ignoring");
2558 artifactInfo.setArtifactCreator(user.getUserId());
2560 if (artifactInfo.getUserIdLastUpdater() != null) {
2561 log.error("userId of last updater cannot be set ignoring");
2563 artifactInfo.setUserIdLastUpdater(user.getUserId());
2565 if (artifactInfo.getCreatorFullName() != null) {
2566 log.error("creator Full name cannot be set ignoring");
2568 String fullName = user.getFirstName() + " " + user.getLastName();
2569 artifactInfo.setUpdaterFullName(fullName);
2571 if (artifactInfo.getUpdaterFullName() != null) {
2572 log.error("updater Full name cannot be set ignoring");
2574 artifactInfo.setUpdaterFullName(fullName);
2576 if (artifactInfo.getCreationDate() != null) {
2577 log.error("Creation Date cannot be set ignoring");
2579 long time = System.currentTimeMillis();
2580 artifactInfo.setCreationDate(time);
2582 if (artifactInfo.getLastUpdateDate() != null) {
2583 log.error("Last Update Date cannot be set ignoring");
2585 artifactInfo.setLastUpdateDate(time);
2587 if (artifactInfo.getEsId() != null) {
2588 log.error("es id cannot be set ignoring");
2590 artifactInfo.setEsId(null);
2595 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2596 String id = artifactId;
2597 if (artifactId == null || artifactId.isEmpty()) {
2598 String uniqueId = null;
2599 if (interfaceName != null && operationName != null) {
2600 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2601 .getArtifactLabel());
2604 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2606 artifactInfo.setUniqueId(uniqueId);
2607 artifactInfo.setEsId(uniqueId);
2611 artifactInfo.setUniqueId(artifactId);
2612 artifactInfo.setEsId(artifactId);
2617 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2618 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2619 BeEcompErrorManager.getInstance()
2620 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2621 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2622 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2625 boolean artifactTypeExist = false;
2626 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2627 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2629 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2630 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2634 allArtifactTypes = elementOperation.getAllArtifactTypes();
2636 if (allArtifactTypes.isRight()) {
2637 BeEcompErrorManager.getInstance()
2638 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2642 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2644 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2647 for (ArtifactType type : allArtifactTypes.left().value()) {
2648 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2649 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2650 artifactTypeExist = true;
2655 if (!artifactTypeExist) {
2656 BeEcompErrorManager.getInstance()
2657 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2658 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2659 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2660 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2661 .getArtifactType()));
2664 return Either.left(ActionStatus.OK);
2667 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2669 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2670 List<ArtifactType> artifactTypes = new ArrayList<>();
2672 if (parentType.equals(NodeTypeEnum.Service)) {
2673 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2675 .getServiceDeploymentArtifacts();
2677 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2678 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2680 .getResourceInstanceDeploymentArtifacts();
2683 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2685 .getResourceDeploymentArtifacts();
2687 if (deploymentArtifacts != null) {
2688 for (String artifactType : deploymentArtifacts.keySet()) {
2689 ArtifactType artifactT = new ArtifactType();
2690 artifactT.setName(artifactType);
2691 artifactTypes.add(artifactT);
2693 return Either.left(artifactTypes);
2696 return Either.right(ActionStatus.GENERAL_ERROR);
2701 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2702 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2703 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2705 return Either.left(true);
2709 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2710 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2711 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2714 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2715 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2716 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2718 artifactInfo.setArtifactName(normalizeFileName);
2720 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2721 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2724 return Either.left(true);
2727 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2728 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2729 log.info("artifact type is missing operation ignored");
2730 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2733 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2734 log.info("artifact type cannot be changed operation ignored");
2735 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2737 return Either.left(true);
2740 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2741 if (artifactInfo.getArtifactGroupType() == null) {
2742 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2745 else if (!currentArtifact.getArtifactGroupType()
2747 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2748 log.info("artifact group type cannot be changed. operation failed");
2749 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2751 return Either.left(artifactInfo);
2754 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2756 // on update if null add informational to current
2757 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2758 currentArtifact.setArtifactGroupType(type);
2761 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2762 log.error("artifact uniqid cannot be set ignoring");
2764 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2766 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2767 .equals(artifactInfo.getArtifactRef())) {
2768 log.error("artifact ref cannot be set ignoring");
2770 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2772 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2773 .equals(artifactInfo.getArtifactRepository())) {
2774 log.error("artifact repository cannot be set ignoring");
2776 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2778 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2779 .equals(artifactInfo.getUserIdCreator())) {
2780 log.error("creator uuid cannot be set ignoring");
2782 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2784 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2785 .equals(artifactInfo.getArtifactCreator())) {
2786 log.error("artifact creator cannot be set ignoring");
2788 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2790 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2791 .equals(artifactInfo.getUserIdLastUpdater())) {
2792 log.error("userId of last updater cannot be set ignoring");
2794 artifactInfo.setUserIdLastUpdater(user.getUserId());
2796 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2797 .equals(artifactInfo.getCreatorFullName())) {
2798 log.error("creator Full name cannot be set ignoring");
2800 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2802 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2803 .equals(artifactInfo.getUpdaterFullName())) {
2804 log.error("updater Full name cannot be set ignoring");
2806 String fullName = user.getFirstName() + " " + user.getLastName();
2807 artifactInfo.setUpdaterFullName(fullName);
2809 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2810 .equals(artifactInfo.getCreationDate())) {
2811 log.error("Creation Date cannot be set ignoring");
2813 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2815 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2816 .equals(artifactInfo.getLastUpdateDate())) {
2817 log.error("Last Update Date cannot be set ignoring");
2819 long time = System.currentTimeMillis();
2820 artifactInfo.setLastUpdateDate(time);
2822 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2823 log.error("es id cannot be set ignoring");
2825 artifactInfo.setEsId(currentArtifact.getUniqueId());
2827 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2828 .equals(artifactInfo.getArtifactDisplayName())) {
2829 log.error(" Artifact Display Name cannot be set ignoring");
2831 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2833 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2834 .equals(artifactInfo.getServiceApi())) {
2835 log.debug("serviceApi cannot be set. ignoring.");
2837 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2839 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2840 .equals(artifactInfo.getArtifactGroupType())) {
2841 log.debug("artifact group cannot be set. ignoring.");
2843 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2845 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2847 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2848 .isEmpty() && !currentArtifact.getArtifactUUID()
2849 .equals(artifactInfo.getArtifactUUID())) {
2850 log.debug("artifact UUID cannot be set. ignoring.");
2852 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2854 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2855 .getHeatParameters()
2856 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2857 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2861 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2863 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2864 for (HeatParameterDefinition parameter : heatParameters) {
2865 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2867 if (currentParam != null) {
2869 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2870 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2871 parameter.setName(currentParam.getName());
2873 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2874 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2875 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2876 parameter.setDefaultValue(currentParam.getDefaultValue());
2878 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2879 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2880 parameter.setType(currentParam.getType());
2882 if (parameter.getDescription() != null && !parameter.getDescription()
2883 .equalsIgnoreCase(currentParam.getDescription())) {
2884 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2885 parameter.setDescription(currentParam.getDescription());
2888 // check and set current value
2889 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2890 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2891 parameter.setCurrentValue(currentParam.getDefaultValue());
2897 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2899 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2900 for (HeatParameterDefinition param : currentParameters) {
2901 currentParamsMap.put(param.getUniqueId(), param);
2903 return currentParamsMap;
2906 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2907 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2908 log.debug("Artifact url cannot be empty.");
2909 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2911 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2913 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2914 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2916 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2917 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2920 return Either.left(true);
2923 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2924 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2925 log.debug("Artifact description cannot be empty.");
2926 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2928 String description = artifactInfo.getDescription();
2929 description = ValidationUtils.removeNoneUtf8Chars(description);
2930 description = ValidationUtils.normaliseWhitespace(description);
2931 description = ValidationUtils.stripOctets(description);
2932 description = ValidationUtils.removeHtmlTagsOnly(description);
2933 if (!ValidationUtils.validateIsEnglish(description)) {
2934 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2936 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2937 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2938 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2940 artifactInfo.setDescription(description);
2941 return Either.left(true);
2944 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2945 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2946 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2947 String prevArtifactId = null;
2948 String currArtifactId = artifactId;
2950 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2951 Either<ArtifactDefinition, Operation> insideEither = null;
2953 log.trace("Try to update entry on graph");
2954 String artifactUniqueId = null;
2955 ArtifactDefinition artifactDefinition = artifactInfo;
2956 StorageOperationStatus error;
2959 if (interfaceType == null || operationUuid == null) {
2960 log.debug("Entity on graph is updated. Update artifact in ES");
2962 // Changing previous and current artifactId for auditing
2963 prevArtifactId = currArtifactId;
2964 currArtifactId = artifactDefinition.getUniqueId();
2967 if (decodedPayload == null) {
2968 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2969 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2971 if (artifactFromCassandra.isRight()) {
2972 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2973 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2975 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2976 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2977 resultOp = Either.right(responseFormat);
2980 // clone data to new artifact
2981 artifactData.setData(artifactFromCassandra.left().value().getData());
2982 artifactData.setId(artifactFromCassandra.left().value().getId());
2985 if (artifactDefinition.getEsId() == null) {
2986 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2987 artifactData.setId(artifactDefinition.getUniqueId());
2991 NodeTypeEnum convertParentType = convertParentType(componentType);
2992 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
2993 .getUniqueId(), artifactId, convertParentType, parentId);
2994 isLeft = result.isLeft();
2996 artifactUniqueId = result.left().value().getUniqueId();
2997 artifactDefinition = result.left().value();
2998 String artifactType = artifactInfo.getArtifactType();
2999 if (NodeTypeEnum.Resource == convertParentType
3000 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3001 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3002 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3003 && !artifactUniqueId.equals(artifactId)) {
3004 // need to update the generated id in heat env
3005 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3006 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3008 .filter(a -> a.getValue()
3009 .getGeneratedFromId() != null && a
3011 .getGeneratedFromId()
3012 .equals(artifactId))
3014 if (findFirst.isPresent()) {
3015 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3016 artifactEnvInfo.setArtifactChecksum(null);
3017 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3020 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3022 insideEither = Either.left(result.left().value());
3023 resultOp = Either.left(insideEither);
3024 if (error != StorageOperationStatus.OK) {
3029 error = result.right().value();
3033 // create new entry in ES
3035 if (artifactData.getData() != null) {
3036 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3037 artifactData.setId(artifactDefinition.getEsId());
3039 res = saveArtifacts(artifactData, parentId);
3045 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3046 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3047 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3049 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3050 log.debug(FAILED_SAVE_ARTIFACT);
3051 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3052 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3053 resultOp = Either.right(responseFormat);
3056 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3057 decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3058 currArtifactId, artifactDefinition);
3064 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3065 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3066 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3067 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3068 ArtifactDefinition artifactDefinition) {
3069 StorageOperationStatus error;
3070 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3071 if (decodedPayload == null) {
3072 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3073 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3075 if (artifactFromCassandra.isRight()) {
3076 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3077 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3079 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3080 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3081 resultOp = Either.right(responseFormat);
3084 // clone data to new artifact
3085 artifactData.setData(artifactFromCassandra.left().value().getData());
3086 artifactData.setId(artifactFromCassandra.left().value().getId());
3088 // todo if not exist(first time)
3092 if (artifactDefinition.getEsId() == null) {
3093 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3094 artifactData.setId(artifactDefinition.getUniqueId());
3097 NodeTypeEnum convertParentType = convertParentType(componentType);
3098 // Set additional fields for artifact
3099 artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
3100 artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
3102 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
3103 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
3104 if(updateArtifactOnResourceEither.isRight()){
3105 log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
3106 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
3107 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3109 if (artifactData.getData() != null) {
3110 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3111 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3112 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
3113 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3114 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3115 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3119 Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
3120 if(updateOprEither.isRight()){
3121 return Either.right(updateOprEither.right().value());
3124 return Either.left(Either.left(updateOprEither.left().value()));
3127 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3128 log.trace("Starting payload handling");
3129 byte[] payload = artifactInfo.getPayloadData();
3130 byte[] decodedPayload = null;
3132 if (payload != null && payload.length != 0) {
3133 // the generated artifacts were already decoded by the handler
3134 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3135 if (decodedPayload.length == 0) {
3136 log.debug("Failed to decode the payload.");
3137 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3138 return Either.right(responseFormat);
3141 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3142 artifactInfo.setArtifactChecksum(checkSum);
3143 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3145 // Specific payload validations of different types
3146 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3147 if (isDeploymentArtifact(artifactInfo)) {
3148 log.trace("Starting deployment artifacts payload validation");
3149 String artifactType = artifactInfo.getArtifactType();
3150 if (ArtifactTypeEnum.HEAT.getType()
3151 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3152 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3154 .equalsIgnoreCase(artifactType)
3155 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3156 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3157 if (isValidPayload.isLeft()) {
3158 isValidPayload = extractHeatParameters(artifactInfo);
3161 else if (ArtifactTypeEnum.YANG_XML.getType()
3162 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3163 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3165 .equalsIgnoreCase(artifactType)
3166 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3167 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3169 .equalsIgnoreCase(artifactType)
3170 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3171 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3173 .equalsIgnoreCase(artifactType)) {
3174 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3176 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3177 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3179 .equalsIgnoreCase(artifactType)
3180 || ArtifactTypeEnum.VES_EVENTS.getType()
3181 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3183 .equalsIgnoreCase(artifactType)) {
3184 String artifactFileName = artifactInfo.getArtifactName();
3185 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3186 switch (fileExtension) {
3188 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3191 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3195 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3202 if (isValidPayload.isRight()) {
3203 ResponseFormat responseFormat = isValidPayload.right().value();
3204 return Either.right(responseFormat);
3207 } // null/empty payload is normal if called from metadata update ONLY.
3208 // The validation of whether this is metadata/payload update case is
3209 // currently done separately
3211 if (!isArtifactMetadataUpdate) {
3212 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3213 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3214 return Either.right(responseFormat);
3217 log.trace("Ended payload handling");
3218 return Either.left(decodedPayload);
3221 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3222 // Basic YAML validation
3223 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3224 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3225 log.debug("Invalid YAML format");
3226 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3227 return Either.right(responseFormat);
3229 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3230 // HEAT specific YAML validation
3231 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3232 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3233 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3234 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3235 return Either.right(responseFormat);
3239 return Either.left(true);
3242 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3243 Either<Boolean, ResponseFormat> res = Either.left(true);
3244 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3245 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3246 log.debug("Invalid YAML format");
3247 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3248 res = Either.right(responseFormat);
3254 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3255 boolean isXmlValid = isValidXml(payload);
3257 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3258 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3259 log.debug("Invalid XML content");
3260 return Either.right(responseFormat);
3262 return Either.left(true);
3265 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3266 boolean isJsonValid = isValidJson(payload);
3268 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3269 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3270 log.debug("Invalid JSON content");
3271 return Either.right(responseFormat);
3273 return Either.left(true);
3276 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3277 boolean inTransaction) {
3278 User user = new User();
3279 user.setUserId(userUserId);
3280 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3281 if (parent.isRight()) {
3282 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3285 return Either.right(responseFormat);
3287 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3290 false, inTransaction);
3291 if (handleDelete.isRight()) {
3292 return Either.right(handleDelete.right().value());
3294 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3295 return Either.left(result.right().value());
3299 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3300 Operation op = new Operation();
3301 long time = System.currentTimeMillis();
3302 op.setCreationDate(time);
3304 String artifactName = artifactInfo.getArtifactName();
3305 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3307 op.setImplementation(artifactInfo);
3308 op.setLastUpdateDate(time);
3312 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3313 String newArtifactName = operationName + "_" + artifactName;
3314 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3315 return newArtifactName;
3319 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3321 // General validation
3322 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3323 log.debug(NULL_PARAMETER);
3324 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3327 // Normalizing artifact name
3328 artifactName = ValidationUtils.normalizeFileName(artifactName);
3330 // Resource validation
3331 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3332 if (validateResourceNameAndVersion.isRight()) {
3333 return Either.right(validateResourceNameAndVersion.right().value());
3336 Resource resource = validateResourceNameAndVersion.left().value();
3337 String resourceId = resource.getUniqueId();
3339 // Service validation
3340 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3341 if (validateServiceNameAndVersion.isRight()) {
3342 return Either.right(validateServiceNameAndVersion.right().value());
3345 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3346 if (artifacts == null || artifacts.isEmpty()) {
3347 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3348 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3351 ArtifactDefinition deploymentArtifact = null;
3353 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3354 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3355 .equals(artifactName)) {
3356 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3357 deploymentArtifact = artifactDefinition;
3362 if (deploymentArtifact == null) {
3363 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3364 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3367 // Downloading the artifact
3368 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3369 if (downloadArtifactEither.isRight()) {
3370 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3371 return Either.right(downloadArtifactEither.right().value());
3373 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3374 return Either.left(downloadArtifactEither.left().value().getRight());
3378 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3380 // General validation
3381 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3382 log.debug(NULL_PARAMETER);
3383 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3386 // Normalizing artifact name
3387 artifactName = ValidationUtils.normalizeFileName(artifactName);
3389 // Service validation
3390 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3391 if (validateServiceNameAndVersion.isRight()) {
3392 return Either.right(validateServiceNameAndVersion.right().value());
3395 Service service = validateServiceNameAndVersion.left().value();
3397 // ResourceInstance validation
3398 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3399 if (validateResourceInstance.isRight()) {
3400 return Either.right(validateResourceInstance.right().value());
3403 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3405 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3407 final String finalArtifactName = artifactName;
3408 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3410 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3412 .anyMatch(filterArtifactByName);
3413 ArtifactDefinition deployableArtifact;
3415 if (!hasDeploymentArtifacts) {
3416 log.debug("Deployment artifact with name {} not found", artifactName);
3417 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3420 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3421 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3422 // Downloading the artifact
3423 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3425 if (downloadArtifactEither.isRight()) {
3426 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3427 return Either.right(downloadArtifactEither.right().value());
3429 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3430 return Either.left(downloadArtifactEither.left().value().getRight());
3433 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3435 List<ComponentInstance> riList = service.getComponentInstances();
3436 for (ComponentInstance ri : riList) {
3437 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3438 return Either.left(ri);
3442 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3445 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3447 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3448 if (serviceListBySystemName.isRight()) {
3449 log.debug("Couldn't fetch any service with name {}", serviceName);
3450 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3452 .value(), ComponentTypeEnum.SERVICE), serviceName));
3454 List<Service> serviceList = serviceListBySystemName.left().value();
3455 if (serviceList == null || serviceList.isEmpty()) {
3456 log.debug("Couldn't fetch any service with name {}", serviceName);
3457 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3460 Service foundService = null;
3461 for (Service service : serviceList) {
3462 if (service.getVersion().equals(serviceVersion)) {
3463 log.trace("Found service with version {}", serviceVersion);
3464 foundService = service;
3469 if (foundService == null) {
3470 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3471 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3472 .getValue(), serviceVersion));
3474 return Either.left(foundService);
3477 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3479 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3480 if (resourceListBySystemName.isRight()) {
3481 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3482 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3484 .value()), resourceName));
3486 return Either.left(resourceListBySystemName.left().value());
3489 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3491 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3492 if (serviceName == null || serviceVersion == null || artifactName == null) {
3493 log.debug(NULL_PARAMETER);
3494 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3497 // Normalizing artifact name
3498 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3500 // Service validation
3501 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3502 if (validateServiceNameAndVersion.isRight()) {
3503 return Either.right(validateServiceNameAndVersion.right().value());
3506 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3508 // Looking for deployment or tosca artifacts
3509 Service service = validateServiceNameAndVersion.left().value();
3511 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3512 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3513 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3516 Optional<ArtifactDefinition> foundArtifactOptl = null;
3518 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3519 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3520 // filters artifact by name
3521 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3523 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3524 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3525 // filters TOSCA artifact by name
3526 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3528 if (!foundArtifactOptl.isPresent()) {
3529 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3530 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3532 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3533 // Downloading the artifact
3534 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3536 if (downloadArtifactEither.isRight()) {
3537 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3538 return Either.right(downloadArtifactEither.right().value());
3540 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3541 return Either.left(downloadArtifactEither.left().value().getRight());
3544 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3545 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3546 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3547 if (artifactById.isRight()) {
3548 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3549 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3550 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3552 ArtifactDefinition artifactDefinition = artifactById.left().value();
3553 if (artifactDefinition == null) {
3554 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3555 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3558 return downloadArtifact(artifactDefinition);
3561 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3562 boolean found = false;
3563 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3564 if (artifactsS != null) {
3565 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3566 if (entry.getValue().getUniqueId().equals(artifactId)) {
3572 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3573 if (!found && deploymentArtifactsS != null) {
3574 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3575 if (entry.getValue().getUniqueId().equals(artifactId)) {
3581 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3582 if (!found && toscaArtifactsS != null) {
3583 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3584 if (entry.getValue().getUniqueId().equals(artifactId)) {
3591 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3592 if (!found && interfaces != null) {
3593 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3594 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3595 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3596 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3597 .getImplementation()
3599 .equals(artifactId)) {
3607 switch (component.getComponentType()) {
3611 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3612 if (!found && apiArtifacts != null) {
3613 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3614 if (entry.getValue().getUniqueId().equals(artifactId)) {
3628 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3630 boolean found = false;
3631 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3632 ComponentInstance resourceInstance = null;
3633 for (ComponentInstance ri : resourceInstances) {
3634 if (ri.getUniqueId().equals(resourceInstanceId)) {
3635 resourceInstance = ri;
3639 if (resourceInstance != null) {
3640 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3641 if (artifacts != null) {
3642 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3643 if (entry.getValue().getUniqueId().equals(artifactId)) {
3650 artifacts = resourceInstance.getArtifacts();
3651 if (artifacts != null) {
3652 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3653 if (entry.getValue().getUniqueId().equals(artifactId)) {
3664 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3665 String containerComponentType) {
3667 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3668 componentForAudit.getNodeType();
3670 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3671 .getToscaFullElement(componentId);
3673 if (componentResult.isRight()) {
3674 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3675 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3676 log.debug("Service not found, serviceId {}", componentId);
3677 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3678 return Either.right(responseFormat);
3680 return Either.left(componentResult.left().value());
3683 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3684 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3685 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3686 if (canWork.isRight()) {
3687 String uniqueId = component.getUniqueId();
3688 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3689 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3691 .getComponentType(), null);
3692 return Either.right(canWork.right().value());
3695 return Either.left(true);
3698 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3700 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3701 String role = user.getRole();
3702 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3703 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3704 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3705 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3706 return Either.right(responseFormat);
3709 return Either.left(true);
3712 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3715 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3716 } catch(ComponentException e){
3718 user.setUserId(userId);
3719 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
3720 componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3721 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3724 return Either.left(user);
3727 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3728 AuditingActionEnum auditingAction = null;
3729 switch (operation.getArtifactOperationEnum()) {
3731 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3734 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3737 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3740 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3745 return auditingAction;
3748 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3749 String esArtifactId = artifactDefinition.getEsId();
3750 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3751 if (artifactfromES.isRight()) {
3752 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3753 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3754 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3755 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3756 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3757 .getArtifactDisplayName());
3759 return Either.right(responseFormat);
3762 ESArtifactData esArtifactData = artifactfromES.left().value();
3763 byte[] data = esArtifactData.getDataAsArray();
3765 log.debug("Artifact data from ES is null");
3766 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3768 String artifactName = artifactDefinition.getArtifactName();
3769 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3770 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3773 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3774 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3777 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3778 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3780 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3781 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3784 log.info("Failed to save artifact {}.", artifactData.getId());
3790 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3791 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3794 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3795 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3798 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3799 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3800 if (user.isRight()) {
3801 ResponseFormat responseFormat;
3802 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3803 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3804 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3807 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3808 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3810 return Either.right(responseFormat);
3813 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3815 .value(), groupType);
3816 return Either.left(artifactDefinition);
3819 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3820 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3822 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3823 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3824 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3826 artifactInfo.setArtifactDisplayName(artifactName);
3827 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3828 artifactInfo.setArtifactType(artifactType);
3829 artifactInfo.setDescription(artifactDescription);
3830 artifactInfo.setArtifactGroupType(groupType);
3831 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3833 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3835 return artifactInfo;
3838 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3839 String uniqueId = null;
3841 if (resourceId != null) {
3842 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3844 artifactInfo.setUniqueId(uniqueId);
3846 artifactInfo.setUserIdCreator(user.getUserId());
3847 String fullName = user.getFullName();
3848 artifactInfo.setUpdaterFullName(fullName);
3850 long time = System.currentTimeMillis();
3852 artifactInfo.setCreatorFullName(fullName);
3853 artifactInfo.setCreationDate(time);
3855 artifactInfo.setLastUpdateDate(time);
3856 artifactInfo.setUserIdLastUpdater(user.getUserId());
3858 artifactInfo.setMandatory(true);
3861 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3862 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3865 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3866 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3869 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3871 byte[] payload = payloadStr.getBytes();
3873 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3874 return Either.left(artifactData);
3878 * @param artifactDefinition
3881 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3882 String instanceId, boolean shouldLock, boolean inTransaction) {
3883 String payload = generateHeatEnvPayload(artifactDefinition);
3884 String prevUUID = artifactDefinition.getArtifactUUID();
3885 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3886 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3888 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3891 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3892 boolean shouldLock, boolean inTransaction, String instanceId) {
3893 String payload = generateHeatEnvPayload(artifactDefinition);
3894 String prevUUID = artifactDefinition.getArtifactUUID();
3895 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3896 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3898 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3901 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3902 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3903 List<ComponentInstance> componentInstances = component.getComponentInstances();
3904 if (componentInstances != null) {
3905 Optional<ComponentInstance> findFirst = componentInstances.stream()
3906 .filter(ci -> ci.getUniqueId()
3907 .equals(instanceId))
3909 if (findFirst.isPresent()) {
3910 ComponentInstance relevantInst = findFirst.get();
3911 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3912 .getGroupInstances());
3914 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3915 updatedGroupInstances.forEach(gi -> {
3916 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3917 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3919 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3920 if (status.isRight()) {
3921 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3922 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3923 .convertFromStorageResponse(status.right()
3924 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3925 return Either.right(responseFormat);
3931 return Either.left(updatedArtDef);
3934 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3935 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3936 StringBuilder sb = new StringBuilder();
3937 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3938 sb.append("parameters:\n");
3939 if (heatParameters != null) {
3940 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3942 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3944 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3946 String heatValue = heatParameterDefinition.getCurrentValue();
3947 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3948 heatValue = heatParameterDefinition.getDefaultValue();
3949 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3950 empltyHeatValues.add(heatParameterDefinition);
3954 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3959 .append(heatParameterDefinition.getName())
3962 .append(Boolean.parseBoolean(heatValue))
3967 .append(heatParameterDefinition.getName())
3970 .append(new BigDecimal(heatValue).toPlainString())
3973 case COMMA_DELIMITED_LIST:
3976 .append(heatParameterDefinition.getName())
3983 String value = heatValue;
3984 boolean starts = value.startsWith("\"");
3985 boolean ends = value.endsWith("\"");
3986 if (!(starts && ends)) {
3987 starts = value.startsWith("'");
3988 ends = value.endsWith("'");
3989 if (!(starts && ends)) {
3990 value = "\"" + value + "\"";
3994 .append(heatParameterDefinition.getName())
4004 if (!empltyHeatValues.isEmpty()) {
4005 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
4006 empltyHeatValues.forEach(hv -> {
4007 sb.append(" ").append(hv.getName()).append(":");
4008 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
4009 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
4010 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
4011 sb.append(" \"\"").append("\n");
4014 sb.append(" ").append("\n");
4019 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
4022 return sb.toString().replaceAll("\\\\n", "\n");
4026 * @param artifactDefinition
4030 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4031 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4032 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
4033 .getHeatParamsUpdateDate(),
4034 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4038 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4039 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4040 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
4041 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4045 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
4046 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
4048 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
4050 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
4051 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
4053 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
4054 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
4055 ESArtifactData artifactData = null;
4057 if (artifactDataRes.isLeft()) {
4058 artifactData = artifactDataRes.left().value();
4061 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4062 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4063 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4064 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4066 return Either.right(artifactDataRes.right().value());
4068 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4070 String esArtifactId = artifactDefinition.getEsId();
4071 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4072 ESArtifactData esArtifactData;
4073 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4074 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4075 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4076 if (artifactfromES.isRight()) {
4077 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4078 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4079 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4080 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4081 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4083 esArtifactData = artifactfromES.left().value();
4084 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4087 oldCheckSum = artifactDefinition.getArtifactChecksum();
4090 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4093 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4094 if (lockComponent.isRight()) {
4095 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4096 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4097 return Either.right(lockComponent.right().value());
4101 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4103 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4104 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4105 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4106 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4107 .getArtifactType(), artifactDefinition.getEsId());
4108 if (updateArifactDefinitionStatus.isRight()) {
4109 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4111 .value()), artifactDefinition.getArtifactDisplayName());
4112 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4113 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4114 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4115 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4117 return Either.right(responseFormat);
4122 oldCheckSum = artifactDefinition.getArtifactChecksum();
4123 artifactDefinition.setArtifactChecksum(newCheckSum);
4124 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4125 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4126 .getArtifactType(), artifactDefinition.getEsId());
4127 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4128 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4130 log.trace("Update Payload ", artifactDefinition.getEsId());
4132 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4134 artifactDefinition = updateArifactDefinitionStatus.left().value();
4135 artifactData.setId(artifactDefinition.getUniqueId());
4136 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4138 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4139 if (!inTransaction) {
4142 log.debug("Artifact Saved In ES {}", artifactData.getId());
4143 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4144 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4145 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4146 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4150 if (!inTransaction) {
4151 titanDao.rollback();
4153 log.info("Failed to save artifact {}.", artifactData.getId());
4154 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4155 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4156 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4157 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4159 return Either.right(responseFormat);
4163 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4165 .value()), artifactDefinition.getArtifactDisplayName());
4166 log.debug("Failed To update artifact {}", artifactData.getId());
4167 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4168 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4169 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4171 return Either.right(responseFormat);
4177 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4183 return Either.left(artifactDefinition);
4187 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4188 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4189 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4190 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4194 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4195 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4197 Map<String, Object> json = new HashMap<>();
4198 if (artifactId != null && !artifactId.isEmpty()) {
4199 json.put(Constants.ARTIFACT_ID, artifactId);
4202 json.put(Constants.ARTIFACT_NAME, artifactName);
4203 json.put(Constants.ARTIFACT_TYPE, artifactType);
4204 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4206 if (artifactContent != null) {
4207 log.debug("payload is encoded. perform decode");
4208 String encodedPayload = Base64.encodeBase64String(artifactContent);
4209 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4211 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4212 json.put(Constants.ARTIFACT_LABEL, label);
4213 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4214 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4215 : updatedRequiredArtifacts.stream()
4216 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4218 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4219 .map(e -> e.getFileName())
4220 .collect(Collectors.toList()));
4221 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4226 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4228 String jsonStr = gson.toJson(json);
4229 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4230 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4231 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4232 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4233 if (uploadArtifactToService.isRight()) {
4234 return Either.right(uploadArtifactToService.right().value());
4237 return Either.left(uploadArtifactToService.left().value());
4240 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4241 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4242 convertParentType(componentType);
4243 String parentId = parent.getUniqueId();
4244 ArtifactDefinition currArtifact = artifactInfo;
4246 if (origMd5 != null) {
4247 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4248 if (validateMd5.isRight()) {
4249 ResponseFormat responseFormat = validateMd5.right().value();
4250 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4251 return Either.right(responseFormat);
4254 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4255 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4256 if (deploymentValidationResult.isRight()) {
4257 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4258 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4259 return Either.right(responseFormat);
4262 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4263 if (payloadEither.isRight()) {
4264 ResponseFormat responseFormat = payloadEither.right().value();
4265 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4266 return Either.right(responseFormat);
4270 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4271 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4272 return Either.right(responseFormat);
4278 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4279 if (lockComponent.isRight()) {
4280 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4281 .value(), componentType, null);
4282 return Either.right(lockComponent.right().value());
4285 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4287 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4293 if (resultOp == null || resultOp.isRight()) {
4294 log.debug(ROLLBACK);
4295 if (!inTransaction) {
4296 titanDao.rollback();
4301 if (!inTransaction) {
4306 componentType = parent.getComponentType();
4308 NodeTypeEnum nodeType = componentType.getNodeType();
4309 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4313 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4314 ComponentTypeEnum componentType, String origMd5) {
4316 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4317 Either<ArtifactDefinition, Operation> insideEither = null;
4318 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4319 if (getRI.isRight()) {
4320 return Either.right(getRI.right().value());
4322 ComponentInstance ri = getRI.left().value();
4323 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4324 if (getArtifactRes.isRight()) {
4325 return Either.right(getArtifactRes.right().value());
4327 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4329 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4330 .equals(ArtifactTypeEnum.HEAT_VOL
4331 .getType()) || currArtifact
4333 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4334 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4335 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4337 return Either.right(responseFormat);
4339 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4340 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4341 new ArrayList<HeatParameterDefinition>();
4344 if (origMd5 != null) {
4345 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4346 .getName(), currentHeatEnvParams,
4347 updatedHeatEnvParams, currArtifact.getArtifactName());
4348 if (uploadParamsValidationResult.isRight()) {
4349 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4350 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4352 return Either.right(responseFormat);
4354 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4357 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4359 if (validateAndConvertHeatParamers.isRight()) {
4360 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4361 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4363 return Either.right(responseFormat);
4366 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4367 // fill reduced heat env parameters List for updating
4368 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4369 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4370 currArtifact.setListHeatParameters(currentHeatEnvParams);
4372 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4373 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4374 if (updateArifactRes.isRight()) {
4375 log.debug("Failed to update artifact on graph - {}", artifactId);
4376 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4379 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4381 return Either.right(responseFormat);
4383 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4384 if (error != StorageOperationStatus.OK) {
4385 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4386 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4388 return Either.right(responseFormat);
4391 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4393 .getUniqueId(), parent.getUniqueId());
4394 if (error != StorageOperationStatus.OK) {
4395 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4396 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4398 return Either.right(responseFormat);
4402 insideEither = Either.left(currArtifact);
4403 resultOp = Either.left(insideEither);
4404 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4405 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4410 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4411 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4412 String paramName = heatEnvParam.getName();
4413 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4414 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4415 String updatedParamValue = heatEnvParam.getCurrentValue();
4416 currHeatParam.setCurrentValue(updatedParamValue);
4422 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4423 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4425 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4426 Either<ArtifactDefinition, Operation> insideEither = null;
4427 String currentHeatId = currHeatArtifact.getUniqueId();
4429 String esArtifactId = currHeatArtifact.getEsId();
4430 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4431 if (artifactFromES.isRight()) {
4432 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4433 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4434 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4435 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4436 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4439 ESArtifactData esArtifactData = artifactFromES.left().value();
4441 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4443 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4444 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4445 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4447 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4451 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4453 paramName = heatEnvParam.getName();
4454 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4455 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4457 String updatedParamValue = heatEnvParam.getCurrentValue();
4458 if (updatedParamValue == null) {
4459 updatedParamValue = heatEnvParam.getDefaultValue();
4461 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4462 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4463 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4464 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4465 .getType(), paramType.getType(), paramName);
4466 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4467 return Either.right(responseFormat);
4470 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4471 newHeatEnvParams.add(currHeatParam);
4476 if (!newHeatEnvParams.isEmpty()) {
4477 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4478 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4479 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4481 if (operationStatus.isRight()) {
4482 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4484 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4487 return Either.right(responseFormat);
4490 updatedHeatArt = operationStatus.left().value();
4492 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4493 esArtifactData.setId(updatedHeatArt.getEsId());
4495 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4498 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4499 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4500 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4501 .getUniqueId(), responseFormat, componentType, null);
4504 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4505 log.debug(FAILED_SAVE_ARTIFACT);
4506 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4507 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4508 .getUniqueId(), responseFormat, componentType, null);
4509 resultOp = Either.right(responseFormat);
4512 insideEither = Either.left(updatedHeatArt);
4515 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4516 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4517 artifactEnvInfo.setArtifactChecksum(null);
4518 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4519 .getUniqueId(), componentType.getNodeType(), componentId);
4522 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4526 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4527 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4529 .value(), parent, componentType);
4530 if (result != ActionStatus.OK) {
4531 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4532 return Either.right(responseFormat);
4536 if (updatedHeatEnvParams.isEmpty()) {
4537 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4539 resultOp = Either.left(insideEither);
4540 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4541 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4546 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4547 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4548 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4549 return Either.right(responseFormat);
4553 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4554 StorageOperationStatus error = StorageOperationStatus.OK;
4555 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4556 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4557 List<String> groupInstancesId = null;
4558 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4559 groupInstancesId = groupsInstances.stream()
4560 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4561 .contains(artifactId))
4562 .map(GroupInstanceDataDefinition::getUniqueId)
4563 .collect(Collectors.toList());
4565 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4566 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4572 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4573 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4575 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4576 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4577 .getArtifactName(), currArtifactName);
4578 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4579 return Either.right(responseFormat);
4582 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4583 String paramName = uploadedHeatParam.getName();
4584 boolean isExistsInHeat = false;
4585 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4586 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4588 isExistsInHeat = true;
4589 uploadedHeatParam.setType(currHeatParam.getType());
4590 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4591 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4592 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4596 if (!isExistsInHeat) {
4597 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4598 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4599 return Either.right(responseFormat);
4602 return Either.left(updatedHeatEnvParams);
4605 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4606 ResponseFormat responseFormat = null;
4607 List<ComponentInstance> ris = component.getComponentInstances();
4608 for (ComponentInstance ri : ris) {
4609 if (riID.equals(ri.getUniqueId())) {
4610 return Either.left(ri);
4613 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4614 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4615 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4616 return Either.right(responseFormat);
4619 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4620 ResponseFormat responseFormat = null;
4621 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4622 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4623 if (artifactId.equals(artifact.getUniqueId())) {
4624 return Either.left(artifact);
4627 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4628 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4630 return Either.right(responseFormat);
4633 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4634 ArtifactDefinition ret;
4635 if (eitherArtifact.isLeft()) {
4636 ret = eitherArtifact.left().value();
4639 ret = eitherArtifact.right().value().getImplementationArtifact();
4645 * downloads artifact of component by UUIDs
4647 * @param componentType
4648 * @param componentUuid
4649 * @param artifactUUID
4650 * @param resourceCommonInfo
4653 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4654 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4655 Either<byte[], ResponseFormat> result;
4656 byte[] downloadedArtifact = null;
4657 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4658 if (errorWrapper.isEmpty() && component != null) {
4659 resourceCommonInfo.setResourceName(component.getName());
4660 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4662 if (errorWrapper.isEmpty()) {
4663 result = Either.left(downloadedArtifact);
4666 result = Either.right(errorWrapper.getInnerElement());
4672 * downloads an artifact of resource instance of component by UUIDs
4674 * @param componentType
4675 * @param componentUuid
4676 * @param resourceInstanceName
4677 * @param artifactUUID
4680 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4681 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4682 Either<byte[], ResponseFormat> result;
4683 byte[] downloadedArtifact = null;
4684 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4685 if (errorWrapper.isEmpty()) {
4686 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4689 if (errorWrapper.isEmpty()) {
4690 result = Either.left(downloadedArtifact);
4693 result = Either.right(errorWrapper.getInnerElement());
4699 * uploads an artifact to a component by UUID
4703 * @param componentType
4704 * @param componentUuid
4705 * @param resourceCommonInfo
4709 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4710 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4711 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4712 Component component = null;
4713 String componentId = null;
4714 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4715 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4716 String userId = request.getHeader(Constants.USER_ID_HEADER);
4718 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4719 if (getComponentRes.isRight()) {
4720 StorageOperationStatus status = getComponentRes.right().value();
4721 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4722 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4724 if (errorWrapper.isEmpty()) {
4725 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4726 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4728 if (!getComponentRes.left()
4730 .getMetadataDataDefinition()
4732 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4733 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4734 if (component != null) {
4735 componentId = component.getUniqueId();
4736 componentName = component.getName();
4739 resourceCommonInfo.setResourceName(componentName);
4741 if (errorWrapper.isEmpty()) {
4742 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4743 if (actionResult.isRight()) {
4744 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4747 return Either.right(actionResult.right().value());
4749 return Either.left(actionResult.left().value().left().value());
4751 return Either.right(errorWrapper.getInnerElement());
4754 * upload an artifact to a resource instance by UUID
4758 * @param componentType
4759 * @param componentUuid
4760 * @param resourceInstanceName
4764 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4765 ArtifactOperationInfo operation) {
4766 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4767 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4768 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4769 ArtifactDefinition uploadArtifact = null;
4770 Component component = null;
4771 String componentInstanceId;
4773 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4774 String userId = request.getHeader(Constants.USER_ID_HEADER);
4776 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4777 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4778 if (getComponentRes.isRight()) {
4779 StorageOperationStatus status = getComponentRes.right().value();
4780 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4781 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4783 if (errorWrapper.isEmpty() && !getComponentRes.left()
4785 .getMetadataDataDefinition()
4787 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4788 component = checkoutParentComponent(componentType, getComponentRes.left()
4790 .getMetadataDataDefinition()
4791 .getUniqueId(), userId, errorWrapper);
4793 if (errorWrapper.isEmpty()) {
4794 if (component == null) {
4795 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4798 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4801 if (errorWrapper.isEmpty()) {
4802 componentInstanceId = componentRiPair.getRight().getUniqueId();
4803 componentId = componentRiPair.getLeft().getUniqueId();
4804 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4806 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4807 .findParamByType(componentType));
4808 if (actionResult.isRight()) {
4809 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4812 errorWrapper.setInnerElement(actionResult.right().value());
4815 if (errorWrapper.isEmpty()) {
4816 uploadArtifact = actionResult.left().value().left().value();
4817 uploadArtifactResult = Either.left(uploadArtifact);
4820 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4822 return uploadArtifactResult;
4826 * updates an artifact on a component by UUID
4830 * @param componentType
4831 * @param componentUuid
4832 * @param artifactUUID
4836 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4837 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4838 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4839 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4840 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4841 ArtifactDefinition updateArtifact = null;
4842 Component component = null;
4843 String componentId = null;
4844 String artifactId = null;
4845 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4846 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4847 String userId = request.getHeader(Constants.USER_ID_HEADER);
4849 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4850 if (getComponentRes.isRight()) {
4851 StorageOperationStatus status = getComponentRes.right().value();
4852 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4853 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4855 if (errorWrapper.isEmpty()) {
4856 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4857 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4859 if (!getComponentRes.left()
4861 .getMetadataDataDefinition()
4863 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4864 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4865 if (component != null) {
4866 componentId = component.getUniqueId();
4867 componentName = component.getName();
4870 resourceCommonInfo.setResourceName(componentName);
4872 if (errorWrapper.isEmpty()) {
4873 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4875 if (errorWrapper.isEmpty()) {
4876 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4877 if (actionResult.isRight()) {
4878 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4881 errorWrapper.setInnerElement(actionResult.right().value());
4884 if (errorWrapper.isEmpty()) {
4885 updateArtifact = actionResult.left().value().left().value();
4886 updateArtifactResult = Either.left(updateArtifact);
4890 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4892 return updateArtifactResult;
4896 * updates an artifact on a resource instance by UUID
4900 * @param componentType
4901 * @param componentUuid
4902 * @param resourceInstanceName
4903 * @param artifactUUID
4904 * @param operation TODO
4907 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4908 ArtifactOperationInfo operation) {
4910 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4911 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4912 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4913 ArtifactDefinition updateArtifact = null;
4914 Component component = null;
4915 String componentInstanceId = null;
4916 String componentId = null;
4917 String artifactId = null;
4918 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4919 String userId = request.getHeader(Constants.USER_ID_HEADER);
4921 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4922 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4923 if (getComponentRes.isRight()) {
4924 StorageOperationStatus status = getComponentRes.right().value();
4925 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4926 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4928 if (errorWrapper.isEmpty() && !getComponentRes.left()
4930 .getMetadataDataDefinition()
4932 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4933 component = checkoutParentComponent(componentType, getComponentRes.left()
4935 .getMetadataDataDefinition()
4936 .getUniqueId(), userId, errorWrapper);
4938 if (errorWrapper.isEmpty()) {
4939 if (component == null) {
4940 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4943 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4946 if (errorWrapper.isEmpty()) {
4947 componentInstanceId = componentRiPair.getRight().getUniqueId();
4948 componentId = componentRiPair.getLeft().getUniqueId();
4949 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4951 if (errorWrapper.isEmpty()) {
4952 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4954 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4955 .findParamByType(componentType));
4956 if (actionResult.isRight()) {
4957 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4960 errorWrapper.setInnerElement(actionResult.right().value());
4963 if (errorWrapper.isEmpty()) {
4964 updateArtifact = actionResult.left().value().left().value();
4965 updateArtifactResult = Either.left(updateArtifact);
4968 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4970 return updateArtifactResult;
4973 private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4974 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4975 if (componentStorageOperationStatusEither.isRight()) {
4976 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4977 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4978 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4980 Component storedComponent = componentStorageOperationStatusEither.left().value();
4982 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4983 if(!optionalInterface.isPresent()) {
4984 log.debug("Failed to get resource interface for resource Id {}", componentId);
4985 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4988 //fetch the operation from storage
4989 InterfaceDefinition gotInterface = optionalInterface.get();
4990 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4991 Optional<Operation> optionalOperation = operationsMap.values()
4993 .filter(o -> o.getUniqueId().equals(operationUuid))
4995 if (!optionalOperation.isPresent()) {
4996 log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4997 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4998 return Either.right(responseFormat);
5001 Operation operation = optionalOperation.get();
5002 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
5003 implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
5004 implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
5005 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
5006 implementationArtifact.setDescription(artifactInfo.getDescription());
5007 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
5008 implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
5009 implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
5010 implementationArtifact.setEsId(artifactInfo.getEsId());
5011 operation.setImplementation(implementationArtifact);
5012 gotInterface.setOperationsMap(operationsMap);
5013 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
5014 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
5015 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
5016 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
5017 ActionStatus actionStatus =
5018 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
5019 return Either.right(componentsUtils.getResponseFormat(actionStatus));
5022 return Either.left(artifactInfo);
5026 * updates an artifact on a component by UUID
5030 * @param componentType
5031 * @param componentUuid
5032 * @param artifactUUID
5036 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
5037 String data, HttpServletRequest request, ComponentTypeEnum componentType,
5038 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
5039 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
5040 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5041 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
5042 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5043 ArtifactDefinition updateArtifact = null;
5044 String componentId = null;
5045 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
5046 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5047 String userId = request.getHeader(Constants.USER_ID_HEADER);
5048 ArtifactDefinition existingArtifactInfo = null;
5049 String interfaceName = null;
5051 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5052 if (getComponentRes.isRight()) {
5053 StorageOperationStatus status = getComponentRes.right().value();
5054 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5055 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5058 if (errorWrapper.isEmpty()) {
5059 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5060 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5061 if (!getComponentRes.left()
5063 .getMetadataDataDefinition()
5065 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5066 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5067 if (component != null) {
5068 componentId = component.getUniqueId();
5069 componentName = component.getName();
5073 resourceCommonInfo.setResourceName(componentName);
5076 if(errorWrapper.isEmpty()){
5077 Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
5078 if (interfaceNameEither.isRight()) {
5079 errorWrapper.setInnerElement(interfaceNameEither.right().value());
5082 interfaceName = interfaceNameEither.left().value();
5085 if(errorWrapper.isEmpty()){
5086 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
5087 if (toscaComponentEither.isRight()) {
5088 StorageOperationStatus status = toscaComponentEither.right().value();
5089 log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
5090 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5093 if (errorWrapper.isEmpty()) {
5094 NodeTypeEnum parentType = convertParentType(componentType);
5095 List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
5096 for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
5097 if(artifactDefinition.getArtifactName().equalsIgnoreCase(artifactInfo.getArtifactName())){
5098 existingArtifactInfo = artifactDefinition;
5102 if(existingArtifactInfo != null){
5103 return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
5109 if (errorWrapper.isEmpty()) {
5110 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5111 artifactUUID, artifactInfo, origMd5, data, interfaceName,
5112 operationUUID, null, null);
5113 if (actionResult.isRight()) {
5114 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5117 errorWrapper.setInnerElement(actionResult.right().value());
5121 if (errorWrapper.isEmpty()) {
5122 updateArtifact = actionResult.left().value().left().value();
5123 updateArtifactResult = Either.left(updateArtifact);
5127 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5129 return updateArtifactResult;
5132 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5133 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5134 if (componentStorageOperationStatusEither.isRight()) {
5135 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5136 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5137 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5139 Component storedComponent = componentStorageOperationStatusEither.left().value();
5141 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5142 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5143 if(!optionalInterface.isPresent()) {
5144 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5146 return Either.left(optionalInterface.get().getType());
5151 * deletes an artifact on a component by UUID
5154 * @param componentType
5155 * @param componentUuid
5156 * @param artifactUUID
5157 * @param resourceCommonInfo
5158 * @param operation TODO
5161 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5162 ArtifactOperationInfo operation) {
5164 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5165 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5166 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5167 ArtifactDefinition deleteArtifact = null;
5168 Component component = null;
5169 String componentId = null;
5170 String artifactId = null;
5171 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5172 String userId = request.getHeader(Constants.USER_ID_HEADER);
5174 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5175 if (getComponentRes.isRight()) {
5176 StorageOperationStatus status = getComponentRes.right().value();
5177 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5178 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5180 if (errorWrapper.isEmpty()) {
5181 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5182 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5183 if (!getComponentRes.left()
5185 .getMetadataDataDefinition()
5187 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5188 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5189 if (component != null) {
5190 componentId = component.getUniqueId();
5191 componentName = component.getName();
5194 resourceCommonInfo.setResourceName(componentName);
5196 if (errorWrapper.isEmpty()) {
5197 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5199 if (errorWrapper.isEmpty()) {
5200 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5201 if (actionResult.isRight()) {
5202 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5205 errorWrapper.setInnerElement(actionResult.right().value());
5208 if (errorWrapper.isEmpty()) {
5209 deleteArtifact = actionResult.left().value().left().value();
5210 deleteArtifactResult = Either.left(deleteArtifact);
5213 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5215 return deleteArtifactResult;
5219 * deletes an artifact from a resource instance by UUID
5222 * @param componentType
5223 * @param componentUuid
5224 * @param resourceInstanceName
5225 * @param artifactUUID
5226 * @param operation TODO
5229 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5230 ArtifactOperationInfo operation) {
5232 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5233 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5234 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5235 ArtifactDefinition deleteArtifact = null;
5236 Component component = null;
5237 String componentInstanceId = null;
5238 String componentId = null;
5239 String artifactId = null;
5240 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5241 String userId = request.getHeader(Constants.USER_ID_HEADER);
5242 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5243 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5244 if (getComponentRes.isRight()) {
5245 StorageOperationStatus status = getComponentRes.right().value();
5246 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5247 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5249 if (errorWrapper.isEmpty() && !getComponentRes.left()
5251 .getMetadataDataDefinition()
5253 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5254 component = checkoutParentComponent(componentType, getComponentRes.left()
5256 .getMetadataDataDefinition()
5257 .getUniqueId(), userId, errorWrapper);
5259 if (errorWrapper.isEmpty()) {
5260 if (component == null) {
5261 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5264 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5267 if (errorWrapper.isEmpty()) {
5268 componentInstanceId = componentRiPair.getRight().getUniqueId();
5269 componentId = componentRiPair.getLeft().getUniqueId();
5270 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5272 if (errorWrapper.isEmpty()) {
5274 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5275 .findParamByType(componentType));
5277 if (actionResult.isRight()) {
5278 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5281 errorWrapper.setInnerElement(actionResult.right().value());
5284 if (errorWrapper.isEmpty()) {
5285 deleteArtifact = actionResult.left().value().left().value();
5286 deleteArtifactResult = Either.left(deleteArtifact);
5289 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5291 return deleteArtifactResult;
5294 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5295 String artifactId = null;
5296 ArtifactDefinition foundArtifact = null;
5297 if (instance.getDeploymentArtifacts() != null) {
5298 foundArtifact = instance.getDeploymentArtifacts()
5301 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5302 .equals(artifactUUID))
5306 if (foundArtifact == null && instance.getArtifacts() != null) {
5307 foundArtifact = instance.getArtifacts()
5310 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5311 .equals(artifactUUID))
5315 if (foundArtifact == null) {
5316 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5317 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5320 artifactId = foundArtifact.getUniqueId();
5325 @SuppressWarnings("unchecked")
5326 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5327 Map<String, String> existingEnvVersions) {
5328 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5330 .getDeploymentResourceInstanceArtifacts();
5331 if (deploymentResourceArtifacts == null) {
5332 log.debug("no deployment artifacts are configured for generated artifacts");
5333 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5335 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5336 if (placeHolderData == null) {
5337 log.debug("no env type {} are configured for generated artifacts", envType);
5338 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5341 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5342 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5343 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5344 if (createArtifactPlaceHolder.isRight()) {
5345 return Either.right(createArtifactPlaceHolder.right().value());
5347 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5348 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5349 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5350 artifactHeatEnv.setTimeout(0);
5351 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5352 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5353 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5354 ArtifactDefinition heatEnvPlaceholder;
5355 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5356 if (parentType != NodeTypeEnum.ResourceInstance) {
5357 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5358 .getUniqueId(), parentType, parentId);
5359 if (addHeatEnvArtifact.isRight()) {
5360 log.debug("failed to create heat env artifact on resource instance");
5361 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5363 .value(), false), "", null));
5365 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5368 heatEnvPlaceholder = artifactHeatEnv;
5369 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5370 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5373 ComponentTypeEnum componentType = component.getComponentType();
5374 if (parentType == NodeTypeEnum.ResourceInstance) {
5375 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5377 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5378 new ResourceCommonInfo(parentName, componentType.getValue()),
5379 ResourceVersionInfo.newBuilder().build(),
5380 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5381 null, heatEnvPlaceholder, null);
5382 return Either.left(heatEnvPlaceholder);
5385 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5386 if (artifact.getListHeatParameters() == null) {
5389 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5390 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5391 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5392 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5393 heatEnvParameter.setCurrentValue(null);
5394 heatEnvParameters.add(heatEnvParameter);
5396 artifactDefinition.setListHeatParameters(heatEnvParameters);
5399 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5400 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5401 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5402 String name = heatArtifact.getArtifactName();
5405 name = heatArtifact.getArtifactLabel();
5406 fileName = name + "." + envExtension;
5409 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5411 heatEnvArtifact.setArtifactName(fileName);
5414 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5415 if (null != existingEnvVersions) {
5416 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5417 if (null != prevVersion) {
5418 heatEnvArtifact.setArtifactVersion(prevVersion);
5424 * Handles Artifacts Request For Inner Component
5426 * @param artifactsToHandle
5429 * @param vfcsNewCreatedArtifacts
5432 * @param inTransaction
5435 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5436 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5438 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5439 ComponentTypeEnum componentType = component.getComponentType();
5440 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5441 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5442 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5446 for (ArtifactDefinition artifact : artifactsToHandle) {
5447 originData = buildJsonStringForCsarVfcArtifact(artifact);
5448 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5449 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5450 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5451 if (actionResult.isRight()) {
5452 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5453 .getName(), actionResult.right().value());
5454 errorWrapper.setInnerElement(actionResult.right().value());
5455 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5456 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5460 uploadedArtifacts.add(actionResult.left().value().left().value());
5462 if (errorWrapper.isEmpty()) {
5463 handleArtifactsResult = Either.left(uploadedArtifacts);
5466 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5469 catch (Exception e) {
5470 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5471 handleArtifactsResult = Either.right(responseFormat);
5472 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5474 return handleArtifactsResult;
5477 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5478 ComponentInstance componentInstance = null;
5479 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5480 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5481 if (errorWrapper.isEmpty()) {
5482 componentInstance = component.getComponentInstances()
5484 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5485 .equals(normalizedName))
5488 if (componentInstance == null) {
5489 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5491 .getValue(), component.getName()));
5492 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5495 return componentInstance;
5498 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5500 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5501 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5502 ComponentInstance componentInstance = component.getComponentInstances()
5504 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5505 .equals(normalizedName))
5508 if (componentInstance == null) {
5509 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5511 .getValue(), component.getName()));
5512 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5515 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5517 return relatedComponentComponentInstancePair;
5520 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5521 ComponentInstance componentInstance;
5522 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5523 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5524 if (errorWrapper.isEmpty()) {
5525 componentInstance = component.getComponentInstances()
5527 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5530 if (componentInstance == null) {
5531 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5533 .getValue(), component.getName()));
5534 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5537 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5540 return relatedComponentComponentInstancePair;
5543 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5545 byte[] downloadedArtifact = null;
5546 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5547 List<ArtifactDefinition> artifactsList = null;
5548 ArtifactDefinition deploymentArtifact = null;
5549 if (artifacts != null && !artifacts.isEmpty()) {
5550 artifactsList = artifacts.values()
5552 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5553 .equals(artifactUUID))
5554 .collect(Collectors.toList());
5556 if (artifactsList == null || artifactsList.isEmpty()) {
5557 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5558 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5560 if (errorWrapper.isEmpty()) {
5561 deploymentArtifact = artifactsList.get(0);
5562 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5563 if (downloadArtifactEither.isRight()) {
5564 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5565 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5568 if (errorWrapper.isEmpty()) {
5569 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5570 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5572 return downloadedArtifact;
5575 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5576 Component component = null;
5577 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5578 if (getComponentRes.isRight()) {
5579 StorageOperationStatus status = getComponentRes.right().value();
5580 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5581 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5584 component = getComponentRes.left().value();
5589 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5590 Component component = null;
5591 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5592 if (getComponentRes.isRight()) {
5593 StorageOperationStatus status = getComponentRes.right().value();
5594 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5595 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5598 List<Component> value = getComponentRes.left().value();
5599 if (value.isEmpty()) {
5600 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5601 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5602 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5605 component = value.get(0);
5611 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5612 String artifactId = null;
5613 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5614 StorageOperationStatus storageStatus;
5615 ArtifactDefinition latestArtifact = null;
5616 List<ArtifactDefinition> artifacts = null;
5617 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5618 if (getArtifactsRes.isRight()) {
5619 storageStatus = getArtifactsRes.right().value();
5620 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5621 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5622 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5624 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5626 if (errorWrapper.isEmpty()) {
5627 artifacts = getArtifactsRes.left()
5631 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5632 .equals(artifactUUID))
5633 .collect(Collectors.toList());
5634 if (artifacts == null || artifacts.isEmpty()) {
5635 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5636 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5639 if (errorWrapper.isEmpty()) {
5640 latestArtifact = artifacts.stream().max((a1, a2) -> {
5641 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5642 if (compareRes == 0) {
5643 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5644 .getLastUpdateDate());
5648 if (latestArtifact == null) {
5649 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5650 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5653 if (errorWrapper.isEmpty()) {
5654 artifactId = latestArtifact.getUniqueId();
5659 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5661 Component component = null;
5662 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5663 if (getUserRes.isRight()) {
5664 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5667 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5669 if (errorWrapper.isEmpty()) {
5670 User modifier = getUserRes.left().value();
5671 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5672 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5673 if (checkoutRes.isRight()) {
5674 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5675 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5676 errorWrapper.setInnerElement(checkoutRes.right().value());
5679 component = checkoutRes.left().value();
5685 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5686 Map<String, Object> json = new HashMap<>();
5687 String artifactName = artifact.getArtifactName();
5688 json.put(Constants.ARTIFACT_NAME, artifactName);
5689 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5690 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5691 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5692 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5693 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5694 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5695 return gson.toJson(json);
5699 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5700 this.nodeTemplateOperation = nodeTemplateOperation;