2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import fj.data.Either;
27 import org.apache.commons.codec.binary.Base64;
28 import org.apache.commons.collections.CollectionUtils;
29 import org.apache.commons.collections.MapUtils;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.elasticsearch.common.Strings;
33 import org.openecomp.sdc.be.components.ArtifactsResolver;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
35 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
36 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
41 import org.openecomp.sdc.be.config.ConfigurationManager;
42 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
45 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
46 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
47 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
51 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
52 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
53 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
54 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
55 import org.openecomp.sdc.be.model.*;
56 import org.openecomp.sdc.be.model.heat.HeatParameterType;
57 import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
58 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
59 import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
60 import org.openecomp.sdc.be.model.operations.api.*;
61 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
62 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
63 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
64 import org.openecomp.sdc.be.resources.data.ESArtifactData;
65 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
66 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
67 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
68 import org.openecomp.sdc.be.servlets.RepresentationUtils;
69 import org.openecomp.sdc.be.tosca.CsarUtils;
70 import org.openecomp.sdc.be.tosca.ToscaError;
71 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
72 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
73 import org.openecomp.sdc.be.user.IUserBusinessLogic;
74 import org.openecomp.sdc.be.user.Role;
75 import org.openecomp.sdc.be.user.UserBusinessLogic;
76 import org.openecomp.sdc.be.utils.TypeUtils;
77 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
78 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
79 import org.openecomp.sdc.common.api.Constants;
80 import org.openecomp.sdc.common.datastructure.Wrapper;
81 import org.openecomp.sdc.common.log.wrappers.Logger;
82 import org.openecomp.sdc.common.util.GeneralUtility;
83 import org.openecomp.sdc.common.util.ValidationUtils;
84 import org.openecomp.sdc.common.util.YamlToObjectConverter;
85 import org.openecomp.sdc.exception.ResponseFormat;
87 import org.springframework.beans.factory.annotation.Autowired;
89 import org.yaml.snakeyaml.Yaml;
91 import javax.servlet.http.HttpServletRequest;
92 import javax.xml.XMLConstants;
93 import javax.xml.parsers.ParserConfigurationException;
94 import javax.xml.parsers.SAXParserFactory;
95 import java.io.ByteArrayInputStream;
96 import java.io.IOException;
97 import java.math.BigDecimal;
99 import java.util.Map.Entry;
100 import java.util.function.Predicate;
101 import java.util.function.Supplier;
102 import java.util.stream.Collectors;
104 @org.springframework.stereotype.Component("artifactBusinessLogic")
105 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
106 private static final String RESOURCE_INSTANCE = "resource instance";
107 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
108 private static final String ARTIFACT_DESCRIPTION = "artifact description";
109 private static final String ARTIFACT_LABEL = "artifact label";
110 private static final String ARTIFACT_URL = "artifact url";
111 private static final String ARTIFACT_NAME = "artifact name";
112 private static final String ARTIFACT_PAYLOAD = "artifact payload";
114 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
115 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
116 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
118 public static final String HEAT_ENV_NAME = "heatEnv";
119 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
120 public static final String HEAT_ENV_SUFFIX = "env";
121 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
123 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
124 public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
125 public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
126 public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
127 public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
128 public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
129 public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
130 public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
131 public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
132 public static final String NULL_PARAMETER = "One of the function parameteres is null";
133 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
134 public static final String ROLLBACK = "all changes rollback";
135 public static final String COMMIT = "all changes committed";
136 public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
137 public static final String UPDATE_ARTIFACT = "Update Artifact";
138 public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
139 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
141 @javax.annotation.Resource
142 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
143 @javax.annotation.Resource
144 private IUserAdminOperation userOperaton;
146 @javax.annotation.Resource
147 private IElementOperation elementOperation;
149 @javax.annotation.Resource
150 private ResourceBusinessLogic resourceBusinessLogic;
152 @javax.annotation.Resource
153 private ServiceBusinessLogic serviceBusinessLogic;
155 @javax.annotation.Resource
156 private UserBusinessLogic userAdminManager;
158 @javax.annotation.Resource
159 private IHeatParametersOperation heatParametersOperation;
162 private ArtifactCassandraDao artifactCassandraDao;
165 private ToscaExportHandler toscaExportUtils;
168 private CsarUtils csarUtils;
171 private LifecycleBusinessLogic lifecycleBusinessLogic;
174 private IUserBusinessLogic userBusinessLogic;
177 private NodeTemplateOperation nodeTemplateOperation;
180 private ArtifactsResolver artifactsResolver;
183 private InterfaceOperation interfaceOperation;
185 public enum ArtifactOperationEnum {
186 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
188 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
189 return operation == CREATE || operation == LINK;
193 public class ArtifactOperationInfo {
195 private ArtifactOperationEnum artifactOperationEnum;
196 private boolean isExternalApi;
197 private boolean ignoreLifecycleState;
199 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
200 this.artifactOperationEnum = artifactOperationEnum;
201 this.isExternalApi = isExternalApi;
202 this.ignoreLifecycleState = ignoreLifecycleState;
205 public boolean isExternalApi() {
206 return isExternalApi;
209 public boolean ignoreLifecycleState() {
210 return ignoreLifecycleState;
213 public ArtifactOperationEnum getArtifactOperationEnum() {
214 return artifactOperationEnum;
220 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
221 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
222 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
225 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
226 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
228 // step 1 - detect auditing type
229 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
230 // step 2 - check header
231 if (userId == null) {
232 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
233 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
234 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
235 return Either.right(responseFormat);
237 // step 3 - check user existence
238 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
239 if (userResult.isRight()) {
240 return Either.right(userResult.right().value());
243 // step 4 - check user's role
244 User user = userResult.left().value();
245 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
246 if (validateUserRole.isRight()) {
247 return Either.right(validateUserRole.right().value());
251 // 5. check service/resource existence
252 // 6. check service/resource check out
253 // 7. user is owner of checkout state
254 org.openecomp.sdc.be.model.Component component = null;
255 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
256 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
257 if (validateComponent.isRight()) {
258 return Either.right(validateComponent.right().value());
260 component = validateComponent.left().value();
261 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
262 if (validateWorkOnResource.isRight()) {
263 return Either.right(validateWorkOnResource.right().value());
267 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
268 shouldLock, inTransaction, true);
272 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
273 * For regular usage use <br>
274 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
278 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
279 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
280 Component parent = component;
281 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
283 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
284 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
286 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
287 if (errorWrapper.isEmpty()) {
289 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
292 result = Either.right(errorWrapper.getInnerElement());
297 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
298 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
299 ArtifactDefinition validatedArtifactInfo = artifactInfo;
300 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
301 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
302 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
303 if (validateArtifact.isRight()) {
304 ResponseFormat responseFormat = validateArtifact.right().value();
305 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
306 errorWrapper.setInnerElement(validateArtifact.right().value());
308 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
309 validatedArtifactInfo = validateArtifact.left().value();
310 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
313 return validatedArtifactInfo;
316 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
317 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
318 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
320 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
321 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
322 ComponentInstance componentInstance = component.getComponentInstances()
324 .filter(p -> p.getUniqueId().equals(componentId))
327 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
329 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
331 .filter(p -> p.getUniqueId()
332 .equals(validatedArtifact.getUniqueId()))
335 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
336 .getName(), user, componentId, shouldLock, inTransaction);
337 if (eitherGenerated.isRight()) {
338 errorWrapper.setInnerElement(eitherGenerated.right().value());
343 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
344 boolean needGenerate;
345 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
346 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
347 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
348 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
349 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
353 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
354 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
356 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
359 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
360 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
362 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
363 if (generated.isRight()) {
366 byte[] decodedPayload = artifactDefinition.getPayloadData();
367 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
368 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
369 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
370 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
371 shouldLock, inTransaction);
375 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
376 log.debug("tosca artifact generation");
377 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
378 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
380 if (generated.isRight()) {
381 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
384 return Either.right(generated.right().value());
386 byte[] value = generated.left().value();
387 artifactInfo.setPayload(value);
391 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
392 if (exportComponent.isRight()) {
393 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
395 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
396 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
397 return Either.right(responseFormat);
399 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
400 String payload = exportComponent.left().value().getMainYaml();
401 artifactInfo.setPayloadData(payload);
403 return Either.left(Either.left(artifactInfo));
406 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
407 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
408 switch (operation.getArtifactOperationEnum()) {
410 if (artifactGenerationRequired(parent, artifactInfo)) {
411 return generateNotSavedArtifact(parent, artifactInfo);
413 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
415 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
417 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
418 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
419 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
420 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
421 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
422 if (needUpdateGroup && result.isLeft()) {
423 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
424 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
425 .value(), parent, componentType, componentId);
426 if (error != ActionStatus.OK) {
427 result = Either.right(componentsUtils.getResponseFormat(error));
432 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
433 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
436 if (result == null) {
437 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
438 if (needUpdateGroup && result.isLeft()) {
439 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
441 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
442 .value(), parent, componentType);
443 if (error != ActionStatus.OK) {
444 result = Either.right(componentsUtils.getResponseFormat(error));
450 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
452 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
457 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
458 List<GroupDefinition> groups = parent.getGroups();
459 if (groups != null && !groups.isEmpty()) {
460 List<GroupDataDefinition> groupToUpdate = groups.stream()
461 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
462 .contains(artifactInfo
464 .collect(Collectors.toList());
465 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
466 groupToUpdate.forEach(g -> {
467 g.getArtifacts().remove(artifactInfo.getUniqueId());
468 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
469 g.getArtifacts().add(artAfterUpdate.getUniqueId());
470 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
472 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
473 if (status.isRight()) {
474 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
475 return componentsUtils.convertFromStorageResponse(status.right().value());
479 return ActionStatus.OK;
482 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
483 List<GroupDefinition> groups = parent.getGroups();
484 if (groups != null && !groups.isEmpty()) {
485 List<GroupDataDefinition> groupToUpdate = groups.stream()
486 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
487 .contains(artifactInfoHeat
489 .collect(Collectors.toList());
490 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
491 groupToUpdate.forEach(g -> {
492 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
493 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
494 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
495 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
496 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
497 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
499 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
500 if (status.isRight()) {
501 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
502 return componentsUtils.convertFromStorageResponse(status.right().value());
506 return ActionStatus.OK;
509 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
510 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
511 List<GroupInstance> groupInstances = null;
512 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
514 .filter(ci -> ci.getUniqueId().equals(parentId))
516 if (componentInstOp.isPresent()) {
517 groupInstances = componentInstOp.get().getGroupInstances();
519 if (CollectionUtils.isNotEmpty(groupInstances)) {
520 boolean isUpdated = false;
521 for (GroupInstance groupInstance : groupInstances) {
523 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
524 .contains(artifactInfo
526 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
527 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
530 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
531 .contains(artifactInfo
532 .getArtifactUUID())) {
533 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
534 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
538 updatedGroupInstances.add(groupInstance);
542 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
543 if (status.isRight()) {
544 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
545 return componentsUtils.convertFromStorageResponse(status.right().value());
547 return ActionStatus.OK;
550 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
551 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
552 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
553 result = generateToscaArtifact(parent, artifactInfo, false, false);
556 String heatArtifactId = artifactInfo.getGeneratedFromId();
557 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
558 if (heatRes.isRight()) {
559 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
561 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
564 return Either.right(responseFormat);
566 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
567 artifactInfo.setPayloadData(generatedPayload);
568 result = Either.left(Either.left(artifactInfo));
573 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
574 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
575 convertParentType(componentType);
576 String parentId = parent.getUniqueId();
577 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
578 .getGeneratedFromId());
579 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
581 if (origMd5 != null) {
582 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
583 if (validateMd5.isRight()) {
584 ResponseFormat responseFormat = validateMd5.right().value();
585 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
586 return Either.right(responseFormat);
589 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
591 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
592 if (payloadEither.isRight()) {
593 ResponseFormat responseFormat = payloadEither.right().value();
594 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
595 return Either.right(responseFormat);
599 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
600 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
601 return Either.right(responseFormat);
607 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
608 if (lockComponent.isRight()) {
609 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
610 .value(), componentType, null);
611 return Either.right(lockComponent.right().value());
614 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
616 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
622 if (resultOp == null || resultOp.isRight()) {
624 if (!inTransaction) {
630 if (!inTransaction) {
635 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
640 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
641 if (artifactGenerationRequired(component, csarArtifact)) {
642 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
644 if (generated.isRight()) {
645 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
648 return Either.right(generated.right().value());
650 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
653 return downloadArtifact(csarArtifact);
656 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
657 // perform all validation in common flow
658 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
659 null, parentId, containerComponentType);
660 if (result.isRight()) {
661 return Either.right(result.right().value());
663 ArtifactDefinition artifactDefinition;
664 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
665 if (insideValue.isLeft()) {
666 artifactDefinition = insideValue.left().value();
669 artifactDefinition = insideValue.right().value().getImplementationArtifact();
671 // for tosca artifacts and heat env on VF level generated on download without saving
672 if (artifactDefinition.getPayloadData() != null) {
673 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
676 return downloadArtifact(artifactDefinition);
679 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
681 // detect auditing type
682 Map<String, ArtifactDefinition> resMap = null;
683 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
688 if (userId == null) {
689 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
690 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
692 resultOp = Either.right(responseFormat);
696 // check user existence
700 validateUserExists(userId, "get artifacts", false);
702 // 5. check service/resource existence
703 // 6. check service/resource check out
704 // 7. user is owner of checkout state
705 org.openecomp.sdc.be.model.Component component = null;
706 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
707 ComponentParametersView componentFilter = new ComponentParametersView();
708 componentFilter.disableAll();
709 componentFilter.setIgnoreArtifacts(false);
710 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
711 componentFilter.setIgnoreComponentInstances(false);
714 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
715 .findByParamName(containerComponentType), componentFilter);
717 if (validateComponent.isRight()) {
718 resultOp = Either.right(validateComponent.right().value());
721 component = validateComponent.left().value();
722 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
723 if (lockComponent.isRight()) {
725 resultOp = Either.right(lockComponent.right().value());
730 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
732 if (groupType == null) {
733 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
734 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
736 resultOp = Either.right(responseFormat);
740 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
741 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
742 if (list != null && !list.isEmpty()) {
743 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
746 resMap = new HashMap<>();
748 resultOp = Either.left(resMap);
753 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
754 .getNodeType(), groupType, componentId);
755 if (artifactsMapStatus.isRight()) {
756 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
757 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
758 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
759 resultOp = Either.right(responseFormat);
762 resMap = new HashMap<>();
763 resultOp = Either.left(resMap);
767 resMap = artifactsMapStatus.left().value();
768 resultOp = Either.left(resMap);
775 if (resultOp == null || resultOp.isRight()) {
784 componentType = component.getComponentType();
785 NodeTypeEnum nodeType = componentType.getNodeType();
786 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
791 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
793 // check artifact existence
794 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
796 if (artifactResult.isRight()) {
797 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
798 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
799 log.debug("addArtifact - artifact {} not found", artifactId);
800 return Either.right(responseFormat);
804 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
807 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
809 return Either.right(responseFormat);
813 // check artifact belong to component
814 boolean found = false;
815 switch (componentType) {
818 found = checkArtifactInComponent(component, artifactId);
820 case RESOURCE_INSTANCE:
821 found = checkArtifactInResourceInstance(component, componentId, artifactId);
827 String componentName = componentType.name().toLowerCase();
828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
829 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
830 return Either.right(responseFormat);
832 return Either.left(artifactResult.left().value());
835 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
836 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
838 String artifactId = null;
841 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
842 if (payloadEither.isRight()) {
843 return Either.right(payloadEither.right().value());
845 byte[] decodedPayload = payloadEither.left().value();
846 convertParentType(componentType);
849 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
850 if (lockComponent.isRight()) {
851 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
852 .value(), componentType, null);
853 return Either.right(lockComponent.right().value());
856 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
859 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
864 unlockComponent(resultOp, parent, inTransaction);
871 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
872 Component parent, boolean shouldLock, boolean inTransaction) {
875 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
876 if (lockComponent.isRight()) {
877 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
878 .value(), componentType, null);
879 return Either.right(lockComponent.right().value());
882 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
885 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
890 unlockComponent(resultOp, parent, inTransaction);
897 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
898 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
900 convertParentType(componentType);
904 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
906 if (lockComponent.isRight()) {
907 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
908 .value(), componentType, null);
909 return Either.right(lockComponent.right().value());
913 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
915 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
921 unlockComponent(resultOp, parent, inTransaction);
926 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
927 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
929 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
931 if (payloadEither.isRight()) {
932 return Either.right(payloadEither.right().value());
934 byte[] decodedPayload = payloadEither.left().value();
936 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
939 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
940 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
942 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
943 if (validateMd5.isRight()) {
944 ResponseFormat responseFormat = validateMd5.right().value();
945 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
946 return Either.right(responseFormat);
950 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
951 if (validateResult.isRight()) {
952 ResponseFormat responseFormat = validateResult.right().value();
953 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
954 return Either.right(validateResult.right().value());
957 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
958 if (payloadEither.isRight()) {
959 ResponseFormat responseFormat = payloadEither.right().value();
960 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
961 log.debug("Error during handle payload");
962 return Either.right(responseFormat);
965 // validate heat parameters. this part must be after the parameters are
966 // extracted in "handlePayload"
967 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
969 if (validateAndConvertHeatParamers.isRight()) {
970 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
971 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
972 log.debug("Error during handle payload");
973 return Either.right(responseFormat);
975 return payloadEither;
978 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
979 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
981 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
987 user.setUserId("UNKNOWN");
989 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
992 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
993 switch (componentTypeEnum) {
995 Resource resource = (Resource) component;
996 if (resource == null) {
997 // In that case, component ID should be instead of name
998 resource = new Resource();
999 resource.setName(componentId);
1001 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1002 ResourceVersionInfo.newBuilder()
1003 .artifactUuid(prevArtifactUuid)
1004 .build(), currentArtifactUuid, artifactDefinition);
1008 Service service = (Service) component;
1009 if (service == null) {
1010 // In that case, component ID should be instead of name
1011 service = new Service();
1012 service.setName(componentId);
1014 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1015 ResourceVersionInfo.newBuilder()
1016 .artifactUuid(prevArtifactUuid)
1018 ResourceVersionInfo.newBuilder()
1019 .artifactUuid(currentArtifactUuid)
1021 null, artifactDefinition, null);
1024 case RESOURCE_INSTANCE:
1025 if (resourceInstanceName == null) {
1026 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1028 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1029 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1030 ResourceVersionInfo.newBuilder()
1031 .artifactUuid(prevArtifactUuid)
1033 ResourceVersionInfo.newBuilder()
1034 .artifactUuid(currentArtifactUuid)
1036 null, artifactDefinition, null);
1043 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1044 ComponentInstance resourceInstance = component.getComponentInstances()
1046 .filter(p -> p.getUniqueId().equals(componentId))
1049 String resourceInstanceName = null;
1050 if (resourceInstance != null) {
1051 resourceInstanceName = resourceInstance.getName();
1053 return resourceInstanceName;
1056 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1057 StringBuilder sb = new StringBuilder();
1058 if (artifactDefinition != null) {
1059 sb.append(artifactDefinition.getArtifactGroupType().getType())
1062 .append(artifactDefinition.getArtifactLabel())
1065 .append(artifactDefinition.getArtifactType())
1067 .append(artifactDefinition.getArtifactName())
1069 .append(artifactDefinition.getTimeout())
1071 .append(artifactDefinition.getEsId());
1074 if (artifactDefinition.getArtifactVersion() != null) {
1076 sb.append(artifactDefinition.getArtifactVersion());
1082 if (artifactDefinition.getArtifactUUID() != null) {
1083 sb.append(artifactDefinition.getArtifactUUID());
1089 return sb.toString();
1092 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1094 if (origMd5 != null) {
1095 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1096 if (!encodeBase64Str.equals(origMd5)) {
1097 log.debug("The calculated md5 is different then the received one");
1098 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1102 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1103 log.debug("Missing md5 header during artifact create");
1104 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1107 if (payload != null && payload.length != 0) {
1108 log.debug("Cannot have payload while md5 header is missing");
1109 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1112 return Either.left(true);
1115 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1116 ComponentTypeEnum componentType, Component parentComponent) {
1118 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1119 if (artifactById.isRight()) {
1120 return Either.right(artifactById.right().value());
1122 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1124 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1125 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1126 if (validateInformationalArtifactRes.isRight()) {
1127 return Either.right(validateInformationalArtifactRes.right().value());
1129 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1130 if (validateAndSetArtifactname.isRight()) {
1131 return Either.right(validateAndSetArtifactname.right().value());
1133 if (operationName != null && interfaceName != null) {
1134 operationName = operationName.toLowerCase();
1135 interfaceName = interfaceName.toLowerCase();
1137 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1138 if (logicalNameStatus.isRight()) {
1139 return Either.right(logicalNameStatus.right().value());
1141 // This is a patch to block possibility of updating service api fields
1142 // through other artifacts flow
1144 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1145 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1146 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1149 checkCreateFields(user, artifactInfo, artifactGroupType);
1152 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1153 if (currentArtifactInfo != null) {
1154 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1157 // artifactGroupType is not allowed to be updated
1158 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1159 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1160 if (validateGroupType.isRight()) {
1161 return Either.right(validateGroupType.right().value());
1164 NodeTypeEnum parentType = convertParentType(componentType);
1166 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1168 if (isDeploymentArtifact(artifactInfo)) {
1169 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1170 if (deploymentValidationResult.isRight()) {
1171 return Either.right(deploymentValidationResult.right().value());
1175 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1178 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1179 if (descriptionResult.isRight()) {
1180 return Either.right(descriptionResult.right().value());
1183 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1184 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1185 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1186 if (validateServiceApiType.isRight()) {
1187 return Either.right(validateServiceApiType.right().value());
1189 // Change of type is not allowed and should be ignored
1191 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1193 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1194 if (validateUrl.isRight()) {
1195 return Either.right(validateUrl.right().value());
1198 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1199 if (validateUpdate.isRight()) {
1200 log.debug("serviceApi first update cnnot be without payload.");
1201 return Either.right(validateUpdate.right().value());
1205 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1206 if (validateArtifactType.isRight()) {
1207 return Either.right(validateArtifactType.right().value());
1209 if (artifactInfo.getApiUrl() != null) {
1210 artifactInfo.setApiUrl(null);
1211 log.error("Artifact URL cannot be set through this API - ignoring");
1214 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1215 artifactInfo.setServiceApi(false);
1216 log.error("Artifact service API flag cannot be changed - ignoring");
1220 return Either.left(artifactInfo);
1223 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1224 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1225 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1226 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1227 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1231 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1233 Either<ArtifactDefinition, ResponseFormat> result = null;
1234 ArtifactDefinition foundArtifact = null;
1235 if (StringUtils.isNotEmpty(artifactId)) {
1236 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1238 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1239 log.debug("Artifact {} already exist", artifactId);
1240 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1242 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1243 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1244 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1246 if (result == null) {
1247 result = Either.left(foundArtifact);
1252 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1253 ArtifactDefinition foundArtifact;
1254 if (parentComponent.getUniqueId().equals(parentId)) {
1255 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1258 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1259 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1261 return foundArtifact;
1264 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1265 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1266 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1267 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1268 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1269 if (artifactType == null) {
1270 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1271 .getArtifactType()));
1273 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1274 String artifactTypeName = artifactType.getType();
1275 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1276 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1278 .getResourceInformationalArtifacts();
1279 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1280 if (!validArtifactTypes.contains(artifactTypeName)) {
1281 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1284 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1285 .getValidForResourceTypes();
1286 if (!validResourceType.contains(parentResourceType.name())) {
1287 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1291 return validationResult;
1294 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1295 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1296 return NodeTypeEnum.Resource;
1298 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1299 return NodeTypeEnum.ResourceInstance;
1302 return NodeTypeEnum.Service;
1306 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1307 boolean shouldLock, boolean inTransaction) {
1309 NodeTypeEnum parentType = convertParentType(componentType);
1310 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1311 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1312 ArtifactDefinition foundArtifact = null;
1313 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1314 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1315 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1316 boolean isDuplicated = false;
1318 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1321 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1322 if (lockComponent.isRight()) {
1323 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1324 .value(), componentType, null);
1325 resultOp = Either.right(lockComponent.right().value());
1328 if (resultOp == null) {
1329 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1330 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1331 if (getContainerRes.isRight()) {
1332 log.debug("Failed to fetch the container component {}. ", parentId);
1333 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1335 .value()), artifactId);
1336 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1337 resultOp = Either.right(responseFormat);
1340 if (resultOp == null) {
1341 fetchedContainerComponent = getContainerRes.left().value();
1342 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1343 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1344 if (getArtifactRes.isRight()) {
1345 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1347 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1348 .value(), artifactId);
1349 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1350 resultOp = Either.right(responseFormat);
1353 foundArtifact = getArtifactRes.left().value().getLeft();
1354 esId = foundArtifact.getEsId();
1357 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1358 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1359 .getComponentType()));
1360 if (needCloneRes.isRight()) {
1361 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1362 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1364 .value()), foundArtifact.getArtifactDisplayName());
1365 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1366 resultOp = Either.right(responseFormat);
1369 boolean isNeedToDeleteArtifactFromDB = true;
1370 if (resultOp == null) {
1372 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1373 String instanceId = parentId;
1374 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1376 if (isOnlyResourceInstanceArtifact.isRight()) {
1377 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1378 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1379 .value(), foundArtifact
1380 .getArtifactDisplayName());
1381 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1382 return Either.right(responseFormat);
1384 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1387 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1390 if (updatedArtifactRes.isRight()) {
1391 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1392 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1394 .value()), foundArtifact.getArtifactDisplayName());
1395 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1396 resultOp = Either.right(responseFormat);
1399 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1403 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1404 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1405 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1406 if (cassandraStatus != CassandraOperationStatus.OK) {
1407 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1408 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1409 .getArtifactDisplayName());
1410 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1411 resultOp = Either.right(responseFormat);
1414 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1416 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1420 .getGroupInstances());
1421 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1422 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1423 if (status.isRight()) {
1424 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1425 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1427 .value()), foundArtifact.getArtifactDisplayName());
1428 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1429 resultOp = Either.right(responseFormat);
1433 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1434 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1435 if (status != StorageOperationStatus.OK) {
1436 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1437 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1438 .getArtifactDisplayName());
1439 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1440 resultOp = Either.right(responseFormat);
1443 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1444 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1446 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1447 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1448 if (status.isRight()) {
1449 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1450 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1452 .value()), foundArtifact.getArtifactDisplayName());
1453 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1454 resultOp = Either.right(responseFormat);
1458 if (resultOp == null) {
1459 resultOp = Either.left(Either.left(foundArtifact));
1460 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1466 unlockComponent(resultOp, parent, inTransaction);
1471 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1472 Either<Boolean, ActionStatus> result = Either.left(true);
1473 ComponentInstance foundInstance = null;
1474 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1476 .filter(i -> i.getUniqueId().equals(instanceId))
1478 if (!componentInstanceOpt.isPresent()) {
1479 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1482 foundInstance = componentInstanceOpt.get();
1483 String componentUid = foundInstance.getComponentUid();
1484 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1485 if (getContainerRes.isRight()) {
1486 log.debug("Failed to fetch the container component {}. ", componentUid);
1487 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1489 Component origComponent = getContainerRes.left().value();
1490 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1491 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1492 Optional<String> op = deploymentArtifacts.keySet()
1494 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1496 if (op.isPresent()) {
1497 return Either.left(false);
1500 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1501 if (artifacts != null && !artifacts.isEmpty()) {
1502 Optional<String> op = artifacts.keySet()
1504 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1506 if (op.isPresent()) {
1507 return Either.left(false);
1515 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1516 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1517 boolean isUpdated = false;
1518 if (groups != null) {
1519 for (GroupDefinition group : groups) {
1521 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1522 group.getArtifacts().remove(artifactId);
1525 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1526 .contains(foundArtifact.getArtifactUUID())) {
1527 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1531 updatedGroups.add(group);
1535 return updatedGroups;
1538 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1539 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1540 if (CollectionUtils.isNotEmpty(groupInstances)) {
1541 boolean isUpdated = false;
1542 for (GroupInstance groupInstance : groupInstances) {
1544 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1545 .contains(artifactId)) {
1546 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1549 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1550 .contains(foundArtifact
1551 .getArtifactUUID())) {
1552 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1556 updatedGroupInstances.add(groupInstance);
1560 return updatedGroupInstances;
1563 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1565 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1566 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1567 String componentId = component.getUniqueId();
1568 String instanceId = componentId.equals(parentId) ? null : parentId;
1570 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1571 resetMandatoryArtifactFields(foundArtifact);
1572 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1574 else if (cloneIsNeeded) {
1575 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1576 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1579 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1580 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1585 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1587 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1588 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1589 ComponentInstance foundInstance = null;
1590 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1591 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1593 .filter(i -> i.getUniqueId()
1596 if (!componentInstanceOpt.isPresent()) {
1597 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1600 foundInstance = componentInstanceOpt.get();
1601 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1605 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1607 if (result == null) {
1608 if (artifacts.containsKey(artifactId)) {
1609 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1612 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1618 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1619 Map<String, ArtifactDefinition> currArtifacts;
1620 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1621 currArtifacts = component.getDeploymentArtifacts()
1624 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1625 if (MapUtils.isNotEmpty(currArtifacts)) {
1626 artifacts.putAll(currArtifacts);
1629 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1630 currArtifacts = component.getArtifacts()
1633 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1634 if (MapUtils.isNotEmpty(currArtifacts)) {
1635 artifacts.putAll(currArtifacts);
1638 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1639 currArtifacts = component.getToscaArtifacts()
1642 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1643 if (MapUtils.isNotEmpty(currArtifacts)) {
1644 artifacts.putAll(currArtifacts);
1649 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1650 Map<String, ArtifactDefinition> currArtifacts;
1651 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1652 currArtifacts = instance.getDeploymentArtifacts()
1655 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1656 if (MapUtils.isNotEmpty(currArtifacts)) {
1657 artifacts.putAll(currArtifacts);
1660 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1661 currArtifacts = instance.getArtifacts()
1664 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1665 if (MapUtils.isNotEmpty(currArtifacts)) {
1666 artifacts.putAll(currArtifacts);
1671 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1672 if (fetchedArtifact != null) {
1673 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1674 fetchedArtifact.setEsId(null);
1675 fetchedArtifact.setArtifactName(null);
1676 fetchedArtifact.setDescription(null);
1677 fetchedArtifact.setApiUrl(null);
1678 fetchedArtifact.setArtifactChecksum(null);
1679 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1680 fetchedArtifact.setArtifactUUID(null);
1681 long time = System.currentTimeMillis();
1682 fetchedArtifact.setPayloadUpdateDate(time);
1683 fetchedArtifact.setHeatParameters(null);
1684 fetchedArtifact.setHeatParamsUpdateDate(null);
1688 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1689 StorageOperationStatus error = StorageOperationStatus.OK;
1690 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1691 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1692 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1697 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1699 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1701 if (artifactById.isRight()) {
1702 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1703 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1704 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1705 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1706 return Either.right(responseFormat);
1708 ArtifactDefinition artifactDefinition = artifactById.left().value();
1709 if (artifactDefinition == null) {
1710 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1711 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1712 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1713 return Either.right(responseFormat);
1716 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1717 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1718 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1719 return Either.left(insideEither);
1722 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1723 ComponentTypeEnum componentType) {
1725 String artifactLabel = artifactInfo.getArtifactLabel();
1726 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1728 BeEcompErrorManager.getInstance()
1729 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1730 log.debug("missing artifact logical name for component {}", componentId);
1731 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1733 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1735 if (operationName != null) {
1736 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1737 log.debug("artifact label cannot be set {}", artifactLabel);
1738 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1741 artifactLabel = operationName;
1744 String displayName = artifactInfo.getArtifactDisplayName();
1745 if (displayName == null || displayName.isEmpty()) {
1746 displayName = artifactLabel;
1748 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1749 artifactInfo.setArtifactDisplayName(displayName);
1751 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1752 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1753 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1755 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1757 if (artifactLabel.isEmpty()) {
1758 log.debug("missing normalized artifact logical name for component {}", componentId);
1759 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1762 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1763 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1764 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1765 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1767 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1768 log.debug("Non unique Artifact label : {}", artifactLabel);
1769 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1772 artifactInfo.setArtifactLabel(artifactLabel);
1774 return Either.left(ActionStatus.OK);
1777 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1778 boolean isUnique = true;
1779 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1780 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1781 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1784 artifacts = artifactToscaOperation.getArtifacts(componentId);
1787 if (artifacts.isLeft()) {
1788 for (String label : artifacts.left().value().keySet()) {
1789 if (label.equals(artifactLabel)) {
1795 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1796 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1797 .getAllInterfacesOfResource(componentId, true, true);
1798 if (allInterfacesOfResource.isLeft()) {
1799 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1800 for (Operation operation : interace.getOperationsMap().values()) {
1801 if (operation.getImplementation() != null && operation.getImplementation()
1803 .equals(artifactLabel)) {
1814 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1815 ComponentTypeEnum componentType) {
1816 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1817 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1818 String artifactName = artifactInfo.getArtifactName();
1819 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1820 if (artifacts.left().value().values().stream()
1821 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1822 //check whether it is the same artifact we hold (by label)
1823 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1827 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1828 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1833 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1834 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1835 .getAllInterfacesOfResource(componentId, true, true);
1837 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1838 return !allInterfacesOfResource.left().value()
1840 .stream().map(InterfaceDefinition :: getOperationsMap)
1841 .flatMap(map -> map.values().stream())
1842 .map(OperationDataDefinition::getImplementation)
1843 .filter(Objects::nonNull)
1844 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1845 && !artifactLabel.equals(add.getArtifactLabel()));
1850 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1851 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1852 .getAllInterfacesOfResource(componentId, true, true);
1854 if (allInterfacesOfResource.isLeft()){
1855 return !allInterfacesOfResource.left().value()
1857 .stream().map(InterfaceDefinition :: getOperationsMap)
1858 .flatMap(map -> map.values().stream())
1859 .map(OperationDataDefinition::getImplementation)
1860 .filter(Objects::nonNull)
1861 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1866 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1867 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1868 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1869 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1870 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1873 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1875 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1876 log.debug("failed to retrieve artifacts for {} ", componentId);
1877 return Either.right(artifactsResponse.right().value());
1879 return Either.left(artifactsResponse.left().value().entrySet()
1881 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1882 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1885 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1886 return artifacts.entrySet()
1888 .map(x -> x.getValue().getArtifactName())
1889 .collect(Collectors.toList());
1892 // ***************************************************************
1894 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1895 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1896 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1897 Either<ArtifactDefinition, Operation> insideEither = null;
1898 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1899 String instanceId = null;
1900 String instanceName = null;
1901 if (foundInstance != null) {
1902 instanceId = foundInstance.getUniqueId();
1903 instanceName = foundInstance.getName();
1905 boolean isLeft = false;
1906 String artifactUniqueId = null;
1907 StorageOperationStatus error = null;
1908 // information/deployment/api aritfacts
1909 log.trace("Try to create entry on graph");
1910 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1911 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1912 .getUniqueId(), nodeType, true, instanceId);
1914 isLeft = result.isLeft();
1916 artifactUniqueId = result.left().value().getUniqueId();
1917 result.left().value();
1919 insideEither = Either.left(result.left().value());
1920 resultOp = Either.left(insideEither);
1922 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1923 if (error != StorageOperationStatus.OK) {
1929 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1930 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1934 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1935 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1936 .getArtifactDisplayName());
1937 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1938 resultOp = Either.right(responseFormat);
1944 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1945 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1947 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1948 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1949 Either<ArtifactDefinition, Operation> insideEither = null;
1950 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1951 String instanceId = null;
1952 String instanceName = null;
1953 if (foundInstance != null) {
1954 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1955 log.debug("Failed to create artifact, already exists");
1956 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1957 .getArtifactLabel());
1958 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1960 resultOp = Either.right(responseFormat);
1964 instanceId = foundInstance.getUniqueId();
1965 instanceName = foundInstance.getName();
1967 if (artifactData == null) {
1968 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1969 log.debug("Failed to create artifact object for ES.");
1970 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1971 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1972 resultOp = Either.right(responseFormat);
1976 // set on graph object id of artifact in ES!
1977 artifactInfo.setEsId(artifactData.getId());
1979 boolean isLeft = false;
1980 String artifactUniqueId = null;
1981 StorageOperationStatus error = null;
1982 if (interfaceType != null && operationName != null) {
1983 // lifecycle artifact
1984 Operation operation = convertToOperation(artifactInfo, operationName);
1986 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1988 isLeft = result.isLeft();
1990 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1991 result.left().value().getImplementation();
1993 insideEither = Either.right(result.left().value());
1994 resultOp = Either.left(insideEither);
1997 error = result.right().value();
2001 // information/deployment/api aritfacts
2002 log.trace("Try to create entry on graph");
2003 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2004 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2005 .getUniqueId(), nodeType, true, instanceId);
2007 isLeft = result.isLeft();
2009 artifactUniqueId = result.left().value().getUniqueId();
2010 artifactData.setId(result.left().value().getEsId());
2011 insideEither = Either.left(result.left().value());
2012 resultOp = Either.left(insideEither);
2014 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2015 if (error != StorageOperationStatus.OK) {
2021 error = result.right().value();
2025 boolean res = saveArtifacts(artifactData, parentId);
2028 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2030 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2031 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2035 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2036 log.debug(FAILED_SAVE_ARTIFACT);
2037 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2038 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2040 resultOp = Either.right(responseFormat);
2045 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2046 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2047 .getArtifactDisplayName());
2048 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2049 resultOp = Either.right(responseFormat);
2055 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2056 ComponentInstance foundInstance = null;
2057 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2058 foundInstance = containerComponent.getComponentInstances()
2060 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2064 return foundInstance;
2067 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2069 Either<Boolean, ResponseFormat> result = Either.left(true);
2070 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
2072 validateArtifactTypeExists(responseWrapper, artifactInfo);
2074 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2076 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2078 if (responseWrapper.isEmpty()) {
2079 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2082 // Common code for all types
2083 // not allowed to change artifactType
2084 if (responseWrapper.isEmpty() && !isCreate) {
2085 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2086 if (validateServiceApiType.isRight()) {
2087 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2090 if (responseWrapper.isEmpty()) {
2091 if (parentType.equals(NodeTypeEnum.Resource)) {
2092 Resource resource = (Resource) parentComponent;
2093 ResourceTypeEnum resourceType = resource.getResourceType();
2094 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2095 if (config == null) {
2096 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2097 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2098 .getArtifactType()));
2101 List<String> myList = config.getValidForResourceTypes();
2102 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2103 if (either.isRight()) {
2104 responseWrapper.setInnerElement(either.right().value());
2109 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2112 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2113 String artifactName = artifactInfo.getArtifactName();
2114 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2115 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2119 if (responseWrapper.isEmpty()) {
2120 switch (artifactType) {
2124 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2127 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2128 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2130 case DCAE_INVENTORY_TOSCA:
2131 case DCAE_INVENTORY_JSON:
2132 case DCAE_INVENTORY_POLICY:
2133 // Validation is done in handle payload.
2134 case DCAE_INVENTORY_DOC:
2135 case DCAE_INVENTORY_BLUEPRINT:
2136 case DCAE_INVENTORY_EVENT:
2137 // No specific validation
2139 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2145 if (!responseWrapper.isEmpty()) {
2146 result = Either.right(responseWrapper.getInnerElement());
2151 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2152 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2153 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2154 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2155 .getArtifactType());
2156 responseWrapper.setInnerElement(responseFormat);
2157 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2161 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2162 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2163 if (parentType.equals(NodeTypeEnum.Resource)) {
2164 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2166 .getResourceDeploymentArtifacts();
2168 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2169 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2171 .getResourceInstanceDeploymentArtifacts();
2174 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2176 .getServiceDeploymentArtifacts();
2178 return resourceDeploymentArtifacts;
2181 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2182 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2183 if (artifactType == null) {
2184 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2185 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2186 .getArtifactType());
2187 responseWrapper.setInnerElement(responseFormat);
2188 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2192 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2193 ArtifactTypeConfig retConfig = null;
2194 String fileType = artifactType.getType();
2195 if (parentType.equals(NodeTypeEnum.Resource)) {
2196 retConfig = ConfigurationManager.getConfigurationManager()
2198 .getResourceDeploymentArtifacts()
2201 else if (parentType.equals(NodeTypeEnum.Service)) {
2202 retConfig = ConfigurationManager.getConfigurationManager()
2204 .getServiceDeploymentArtifacts()
2207 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2208 retConfig = ConfigurationManager.getConfigurationManager()
2210 .getResourceInstanceDeploymentArtifacts()
2216 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2217 // extract heat parameters
2218 if (artifactInfo.getPayloadData() != null) {
2219 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2220 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2221 .getArtifactType());
2222 if (heatParameters.isRight() && (!heatParameters.right()
2224 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2225 log.info("failed to parse heat parameters ");
2226 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2227 .getArtifactType());
2228 return Either.right(responseFormat);
2230 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2231 artifactInfo.setListHeatParameters(heatParameters.left().value());
2234 return Either.left(true);
2239 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2240 String fileType = artifactType.getType();
2241 List<String> acceptedTypes = null;
2242 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2243 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2244 log.debug("parent type of artifact can be either resource or service");
2245 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2249 if (deploymentAcceptedTypes == null) {
2250 log.debug("parent type of artifact can be either resource or service");
2251 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2252 .getArtifactType()));
2256 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2259 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2262 String artifactName = artifactInfo.getArtifactName();
2263 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2264 // Pavel - File extension validation is case-insensitive - Ella,
2266 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2267 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2268 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2273 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2275 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
2276 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
2277 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2279 if (errorWrapper.isEmpty()) {
2280 validateValidYaml(errorWrapper, artifactInfo);
2283 if (errorWrapper.isEmpty()) {
2284 // Validate Heat Exist
2285 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2286 .getComponentType());
2289 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2290 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2293 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2294 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2298 Either<Boolean, ResponseFormat> eitherResponse;
2299 if (errorWrapper.isEmpty()) {
2300 eitherResponse = Either.left(true);
2303 eitherResponse = Either.right(errorWrapper.getInnerElement());
2305 return eitherResponse;
2308 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2309 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2310 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2311 if (fillArtifactPayload.isRight()) {
2312 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2313 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2317 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2321 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2322 Either<Boolean, ResponseFormat> result = Either.left(true);
2323 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2325 if (eitherArtifactData.isLeft()) {
2326 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2327 data = Base64.encodeBase64(data);
2328 payloadWrapper.setInnerElement(data);
2331 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2334 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2335 result = Either.right(responseFormat);
2341 @SuppressWarnings("unchecked")
2342 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2343 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2344 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2345 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2346 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2348 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2349 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2350 if (eitherHeatEnvProperties.isRight()) {
2351 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2352 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2353 errorWrapper.setInnerElement(responseFormat);
2354 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2356 else if (eitherHeatProperties.isRight()) {
2357 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2358 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2359 .getArtifactName(), heatArtifact.getArtifactName());
2360 errorWrapper.setInnerElement(responseFormat);
2361 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2362 .getArtifactName());
2365 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2366 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2367 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2368 if (!heatEnvPropertiesKeys.isEmpty()) {
2369 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2370 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2371 .getArtifactName(), heatArtifact.getArtifactName());
2372 errorWrapper.setInnerElement(responseFormat);
2377 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2378 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2379 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2381 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2382 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2383 .getArtifactType());
2384 errorWrapper.setInnerElement(responseFormat);
2385 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2389 private boolean isValidXml(byte[] xmlToParse) {
2390 boolean isXmlValid = true;
2392 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2393 setFeatures(reader);
2394 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2396 catch (ParserConfigurationException | IOException | SAXException e) {
2397 log.debug("Xml is invalid : {}", e.getMessage(), e);
2403 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2405 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2406 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2408 catch (SAXNotRecognizedException e) {
2409 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2413 private boolean isValidJson(byte[] jsonToParse) {
2414 String parsed = new String(jsonToParse);
2416 gson.fromJson(parsed, Object.class);
2418 catch (Exception e) {
2419 log.debug("Json is invalid : {}", e.getMessage(), e);
2425 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2426 boolean artifactNameFound = false;
2427 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2430 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2431 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2433 if (artifactNameFound) {
2434 String parentName = parentComponent.getName();
2435 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2436 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2437 .name(), parentName, artifactName);
2439 errorWrapper.setInnerElement(responseFormat);
2440 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2445 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2446 ComponentTypeEnum componentType) {
2447 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2448 if (res.isRight()) {
2449 ResponseFormat responseFormat;
2450 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2451 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2454 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2456 errorWrapper.setInnerElement(responseFormat);
2459 ArtifactDefinition heatArtifact = res.left().value();
2460 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2463 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2464 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2465 // timeout > 0 for HEAT artifacts
2466 Integer timeout = artifactInfo.getTimeout();
2467 if (timeout == null) {
2468 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2469 artifactInfo.setTimeout(defaultTimeout);
2470 // HEAT artifact but timeout is invalid
2472 else if (timeout < 1) {
2473 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2476 // US649856 - Allow several HEAT files on Resource
2477 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2478 return Either.left(true);
2481 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2482 String listToString = (typeList != null) ? typeList.toString() : "";
2483 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2484 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2485 .getArtifactName(), listToString, resourceType.getValue());
2486 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2487 String resourceTypeName = resourceType.name();
2488 if (typeList != null && typeList.contains(resourceTypeName)) {
2489 either = Either.left(true);
2494 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2495 if (artifactInfo.getHeatParameters() != null) {
2496 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2497 String parameterType = heatParam.getType();
2498 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2499 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2500 if (heatParameterType == null) {
2501 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2503 return Either.right(responseFormat);
2506 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2507 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2508 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2509 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2510 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2511 .getType(), heatParam.getName());
2512 return Either.right(responseFormat);
2516 return Either.left(artifactInfo);
2519 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2520 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2521 if (parentComponent.getDeploymentArtifacts() != null) {
2522 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2523 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2524 if (getRI.isRight()) {
2525 return deploymentArtifacts;
2527 ComponentInstance ri = getRI.left().value();
2528 if (ri.getDeploymentArtifacts() != null) {
2529 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2532 else if (parentComponent.getDeploymentArtifacts() != null) {
2533 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2536 return deploymentArtifacts;
2539 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2540 // on create if null add informational to current
2541 if (artifactInfo.getArtifactGroupType() == null) {
2542 artifactInfo.setArtifactGroupType(type);
2544 if (artifactInfo.getUniqueId() != null) {
2545 log.error("artifact uniqid cannot be set ignoring");
2547 artifactInfo.setUniqueId(null);
2549 if (artifactInfo.getArtifactRef() != null) {
2550 log.error("artifact ref cannot be set ignoring");
2552 artifactInfo.setArtifactRef(null);
2554 if (artifactInfo.getArtifactRepository() != null) {
2555 log.error("artifact repository cannot be set ignoring");
2557 artifactInfo.setArtifactRepository(null);
2559 if (artifactInfo.getUserIdCreator() != null) {
2560 log.error("creator uuid cannot be set ignoring");
2562 artifactInfo.setArtifactCreator(user.getUserId());
2564 if (artifactInfo.getUserIdLastUpdater() != null) {
2565 log.error("userId of last updater cannot be set ignoring");
2567 artifactInfo.setUserIdLastUpdater(user.getUserId());
2569 if (artifactInfo.getCreatorFullName() != null) {
2570 log.error("creator Full name cannot be set ignoring");
2572 String fullName = user.getFirstName() + " " + user.getLastName();
2573 artifactInfo.setUpdaterFullName(fullName);
2575 if (artifactInfo.getUpdaterFullName() != null) {
2576 log.error("updater Full name cannot be set ignoring");
2578 artifactInfo.setUpdaterFullName(fullName);
2580 if (artifactInfo.getCreationDate() != null) {
2581 log.error("Creation Date cannot be set ignoring");
2583 long time = System.currentTimeMillis();
2584 artifactInfo.setCreationDate(time);
2586 if (artifactInfo.getLastUpdateDate() != null) {
2587 log.error("Last Update Date cannot be set ignoring");
2589 artifactInfo.setLastUpdateDate(time);
2591 if (artifactInfo.getEsId() != null) {
2592 log.error("es id cannot be set ignoring");
2594 artifactInfo.setEsId(null);
2599 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2600 String id = artifactId;
2601 if (artifactId == null || artifactId.isEmpty()) {
2602 String uniqueId = null;
2603 if (interfaceName != null && operationName != null) {
2604 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2605 .getArtifactLabel());
2608 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2610 artifactInfo.setUniqueId(uniqueId);
2611 artifactInfo.setEsId(uniqueId);
2615 artifactInfo.setUniqueId(artifactId);
2616 artifactInfo.setEsId(artifactId);
2621 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2622 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2623 BeEcompErrorManager.getInstance()
2624 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2625 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2626 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2629 boolean artifactTypeExist = false;
2630 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2631 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2633 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2634 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2638 allArtifactTypes = elementOperation.getAllArtifactTypes();
2640 if (allArtifactTypes.isRight()) {
2641 BeEcompErrorManager.getInstance()
2642 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2646 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2648 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2651 for (ArtifactType type : allArtifactTypes.left().value()) {
2652 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2653 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2654 artifactTypeExist = true;
2659 if (!artifactTypeExist) {
2660 BeEcompErrorManager.getInstance()
2661 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2662 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2663 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2664 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2665 .getArtifactType()));
2668 return Either.left(ActionStatus.OK);
2671 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2673 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2674 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2676 if (parentType.equals(NodeTypeEnum.Service)) {
2677 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2679 .getServiceDeploymentArtifacts();
2681 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2682 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2684 .getResourceInstanceDeploymentArtifacts();
2687 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2689 .getResourceDeploymentArtifacts();
2691 if (deploymentArtifacts != null) {
2692 for (String artifactType : deploymentArtifacts.keySet()) {
2693 ArtifactType artifactT = new ArtifactType();
2694 artifactT.setName(artifactType);
2695 artifactTypes.add(artifactT);
2697 return Either.left(artifactTypes);
2700 return Either.right(ActionStatus.GENERAL_ERROR);
2705 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2706 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2707 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2709 return Either.left(true);
2713 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2714 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2715 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2718 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2719 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2720 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2722 artifactInfo.setArtifactName(normalizeFileName);
2724 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2725 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2728 return Either.left(true);
2731 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2732 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2733 log.info("artifact type is missing operation ignored");
2734 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2737 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2738 log.info("artifact type cannot be changed operation ignored");
2739 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2741 return Either.left(true);
2744 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2745 if (artifactInfo.getArtifactGroupType() == null) {
2746 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2749 else if (!currentArtifact.getArtifactGroupType()
2751 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2752 log.info("artifact group type cannot be changed. operation failed");
2753 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2755 return Either.left(artifactInfo);
2758 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2760 // on update if null add informational to current
2761 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2762 currentArtifact.setArtifactGroupType(type);
2765 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2766 log.error("artifact uniqid cannot be set ignoring");
2768 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2770 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2771 .equals(artifactInfo.getArtifactRef())) {
2772 log.error("artifact ref cannot be set ignoring");
2774 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2776 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2777 .equals(artifactInfo.getArtifactRepository())) {
2778 log.error("artifact repository cannot be set ignoring");
2780 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2782 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2783 .equals(artifactInfo.getUserIdCreator())) {
2784 log.error("creator uuid cannot be set ignoring");
2786 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2788 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2789 .equals(artifactInfo.getArtifactCreator())) {
2790 log.error("artifact creator cannot be set ignoring");
2792 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2794 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2795 .equals(artifactInfo.getUserIdLastUpdater())) {
2796 log.error("userId of last updater cannot be set ignoring");
2798 artifactInfo.setUserIdLastUpdater(user.getUserId());
2800 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2801 .equals(artifactInfo.getCreatorFullName())) {
2802 log.error("creator Full name cannot be set ignoring");
2804 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2806 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2807 .equals(artifactInfo.getUpdaterFullName())) {
2808 log.error("updater Full name cannot be set ignoring");
2810 String fullName = user.getFirstName() + " " + user.getLastName();
2811 artifactInfo.setUpdaterFullName(fullName);
2813 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2814 .equals(artifactInfo.getCreationDate())) {
2815 log.error("Creation Date cannot be set ignoring");
2817 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2819 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2820 .equals(artifactInfo.getLastUpdateDate())) {
2821 log.error("Last Update Date cannot be set ignoring");
2823 long time = System.currentTimeMillis();
2824 artifactInfo.setLastUpdateDate(time);
2826 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2827 log.error("es id cannot be set ignoring");
2829 artifactInfo.setEsId(currentArtifact.getUniqueId());
2831 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2832 .equals(artifactInfo.getArtifactDisplayName())) {
2833 log.error(" Artifact Display Name cannot be set ignoring");
2835 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2837 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2838 .equals(artifactInfo.getServiceApi())) {
2839 log.debug("serviceApi cannot be set. ignoring.");
2841 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2843 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2844 .equals(artifactInfo.getArtifactGroupType())) {
2845 log.debug("artifact group cannot be set. ignoring.");
2847 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2849 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2851 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2852 .isEmpty() && !currentArtifact.getArtifactUUID()
2853 .equals(artifactInfo.getArtifactUUID())) {
2854 log.debug("artifact UUID cannot be set. ignoring.");
2856 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2858 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2859 .getHeatParameters()
2860 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2861 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2865 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2867 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2868 for (HeatParameterDefinition parameter : heatParameters) {
2869 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2871 if (currentParam != null) {
2873 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2874 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2875 parameter.setName(currentParam.getName());
2877 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2878 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2879 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2880 parameter.setDefaultValue(currentParam.getDefaultValue());
2882 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2883 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2884 parameter.setType(currentParam.getType());
2886 if (parameter.getDescription() != null && !parameter.getDescription()
2887 .equalsIgnoreCase(currentParam.getDescription())) {
2888 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2889 parameter.setDescription(currentParam.getDescription());
2892 // check and set current value
2893 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2894 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2895 parameter.setCurrentValue(currentParam.getDefaultValue());
2901 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2903 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2904 for (HeatParameterDefinition param : currentParameters) {
2905 currentParamsMap.put(param.getUniqueId(), param);
2907 return currentParamsMap;
2910 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2911 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2912 log.debug("Artifact url cannot be empty.");
2913 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2915 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2917 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2918 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2920 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2921 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2924 return Either.left(true);
2927 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2928 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2929 log.debug("Artifact description cannot be empty.");
2930 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2932 String description = artifactInfo.getDescription();
2933 description = ValidationUtils.removeNoneUtf8Chars(description);
2934 description = ValidationUtils.normaliseWhitespace(description);
2935 description = ValidationUtils.stripOctets(description);
2936 description = ValidationUtils.removeHtmlTagsOnly(description);
2937 if (!ValidationUtils.validateIsEnglish(description)) {
2938 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2940 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2941 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2942 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2944 artifactInfo.setDescription(description);
2945 return Either.left(true);
2948 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2949 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2950 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2951 String prevArtifactId = null;
2952 String currArtifactId = artifactId;
2954 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2955 Either<ArtifactDefinition, Operation> insideEither = null;
2957 log.trace("Try to update entry on graph");
2958 String artifactUniqueId = null;
2959 ArtifactDefinition artifactDefinition = artifactInfo;
2960 StorageOperationStatus error;
2963 if (interfaceType == null || operationUuid == null) {
2964 log.debug("Entity on graph is updated. Update artifact in ES");
2966 // Changing previous and current artifactId for auditing
2967 prevArtifactId = currArtifactId;
2968 currArtifactId = artifactDefinition.getUniqueId();
2971 if (decodedPayload == null) {
2972 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2973 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2975 if (artifactFromCassandra.isRight()) {
2976 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2977 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2979 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2980 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2981 resultOp = Either.right(responseFormat);
2984 // clone data to new artifact
2985 artifactData.setData(artifactFromCassandra.left().value().getData());
2986 artifactData.setId(artifactFromCassandra.left().value().getId());
2989 if (artifactDefinition.getEsId() == null) {
2990 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2991 artifactData.setId(artifactDefinition.getUniqueId());
2995 NodeTypeEnum convertParentType = convertParentType(componentType);
2996 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
2997 .getUniqueId(), artifactId, convertParentType, parentId);
2998 isLeft = result.isLeft();
3000 artifactUniqueId = result.left().value().getUniqueId();
3001 artifactDefinition = result.left().value();
3002 String artifactType = artifactInfo.getArtifactType();
3003 if (NodeTypeEnum.Resource == convertParentType
3004 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3005 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3006 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3007 && !artifactUniqueId.equals(artifactId)) {
3008 // need to update the generated id in heat env
3009 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3010 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3012 .filter(a -> a.getValue()
3013 .getGeneratedFromId() != null && a
3015 .getGeneratedFromId()
3016 .equals(artifactId))
3018 if (findFirst.isPresent()) {
3019 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3020 artifactEnvInfo.setArtifactChecksum(null);
3021 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3024 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3026 insideEither = Either.left(result.left().value());
3027 resultOp = Either.left(insideEither);
3028 if (error != StorageOperationStatus.OK) {
3033 error = result.right().value();
3037 // create new entry in ES
3039 if (artifactData.getData() != null) {
3040 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3041 artifactData.setId(artifactDefinition.getEsId());
3043 res = saveArtifacts(artifactData, parentId);
3049 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3050 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3051 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3053 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3054 log.debug(FAILED_SAVE_ARTIFACT);
3055 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3056 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3057 resultOp = Either.right(responseFormat);
3060 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3061 decodedPayload, componentType, auditingAction, operationUuid, artifactData, prevArtifactId,
3062 currArtifactId, artifactDefinition);
3068 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3069 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3070 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction,
3071 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3072 ArtifactDefinition artifactDefinition) {
3073 StorageOperationStatus error;
3074 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3075 if (decodedPayload == null) {
3076 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3077 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3079 if (artifactFromCassandra.isRight()) {
3080 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3081 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3083 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3084 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3085 resultOp = Either.right(responseFormat);
3088 // clone data to new artifact
3089 artifactData.setData(artifactFromCassandra.left().value().getData());
3090 artifactData.setId(artifactFromCassandra.left().value().getId());
3092 // todo if not exist(first time)
3096 if (artifactDefinition.getEsId() == null) {
3097 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3098 artifactData.setId(artifactDefinition.getUniqueId());
3101 NodeTypeEnum convertParentType = convertParentType(componentType);
3102 // fetch the resource from storage
3103 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
3104 toscaOperationFacade.getToscaElement(parentId);
3105 if (resourceStorageOperationStatusEither.isRight()) {
3106 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
3107 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
3108 return Either.right(componentsUtils
3109 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
3111 Resource storedResource = resourceStorageOperationStatusEither.left().value();
3113 String interfaceToscaName = InterfaceUtils.createInterfaceToscaResourceName(
3114 storedResource.getName());
3115 //fetch the interface from storage
3116 Optional<InterfaceDefinition> interfaceDefinition = storedResource.getInterfaces().values()
3118 .filter(interfaceDef -> interfaceDef.getToscaResourceName()
3119 .equals(interfaceToscaName))
3121 if (!interfaceDefinition.isPresent()) {
3122 log.debug("Failed to get resource interface for resource Id {}", parentId);
3123 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3124 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3125 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3126 currArtifactId, responseFormat, componentType, null);
3127 return Either.right(responseFormat);
3130 //fetch the operation from storage
3131 InterfaceDefinition gotInterface = interfaceDefinition.get();
3132 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
3133 Optional<Operation> optionalOperation = operationsMap.values()
3135 .filter(o -> o.getUniqueId().equals(operationUuid))
3137 if (!optionalOperation.isPresent()) {
3138 log.debug("Failed to get resource interface operation for resource Id {} " +
3139 " and operationId {}", parentId, operationUuid);
3140 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3141 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3142 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3143 currArtifactId, responseFormat, componentType, null);
3144 return Either.right(responseFormat);
3147 Operation operation = optionalOperation.get();
3148 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
3149 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
3150 implementationArtifact.setDescription(artifactInfo.getDescription());
3151 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
3152 implementationArtifact.setArtifactLabel(artifactInfo.getUniqueId());
3153 implementationArtifact.setEsId(artifactInfo.getEsId());
3154 operation.setImplementation(implementationArtifact);
3155 gotInterface.setOperationsMap(operationsMap);
3156 Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
3157 interfaceOperation.updateInterface(storedResource.getUniqueId(), gotInterface);
3158 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
3159 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
3160 ActionStatus actionStatus =
3161 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
3162 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3165 String uniqueId = implementationArtifact.getUniqueId();
3166 Either<Long, CassandraOperationStatus> artifactCount = artifactCassandraDao.getCountOfArtifactById(uniqueId);
3167 if(artifactCount.isLeft()){
3168 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.deleteArtifact(uniqueId);
3169 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3170 log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
3171 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3172 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3173 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3176 artifactData.setId(uniqueId);
3177 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3178 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3179 log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
3180 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3181 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3182 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3184 return Either.left(Either.left(implementationArtifact));
3187 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3188 log.trace("Starting payload handling");
3189 byte[] payload = artifactInfo.getPayloadData();
3190 byte[] decodedPayload = null;
3192 if (payload != null && payload.length != 0) {
3193 // the generated artifacts were already decoded by the handler
3194 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3195 if (decodedPayload.length == 0) {
3196 log.debug("Failed to decode the payload.");
3197 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3198 return Either.right(responseFormat);
3201 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3202 artifactInfo.setArtifactChecksum(checkSum);
3203 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3205 // Specific payload validations of different types
3206 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3207 if (isDeploymentArtifact(artifactInfo)) {
3208 log.trace("Starting deployment artifacts payload validation");
3209 String artifactType = artifactInfo.getArtifactType();
3210 if (ArtifactTypeEnum.HEAT.getType()
3211 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3212 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3214 .equalsIgnoreCase(artifactType)
3215 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3216 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3217 if (isValidPayload.isLeft()) {
3218 isValidPayload = extractHeatParameters(artifactInfo);
3221 else if (ArtifactTypeEnum.YANG_XML.getType()
3222 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3223 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3225 .equalsIgnoreCase(artifactType)
3226 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3227 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3229 .equalsIgnoreCase(artifactType)
3230 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3231 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3233 .equalsIgnoreCase(artifactType)) {
3234 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3236 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3237 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3239 .equalsIgnoreCase(artifactType)
3240 || ArtifactTypeEnum.VES_EVENTS.getType()
3241 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3243 .equalsIgnoreCase(artifactType)) {
3244 String artifactFileName = artifactInfo.getArtifactName();
3245 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3246 switch (fileExtension) {
3248 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3251 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3255 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3262 if (isValidPayload.isRight()) {
3263 ResponseFormat responseFormat = isValidPayload.right().value();
3264 return Either.right(responseFormat);
3267 } // null/empty payload is normal if called from metadata update ONLY.
3268 // The validation of whether this is metadata/payload update case is
3269 // currently done separately
3271 if (!isArtifactMetadataUpdate) {
3272 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3273 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3274 return Either.right(responseFormat);
3277 log.trace("Ended payload handling");
3278 return Either.left(decodedPayload);
3281 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3282 // Basic YAML validation
3283 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3284 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3285 log.debug("Invalid YAML format");
3286 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3287 return Either.right(responseFormat);
3289 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3290 // HEAT specific YAML validation
3291 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3292 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3293 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3294 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3295 return Either.right(responseFormat);
3299 return Either.left(true);
3302 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3303 Either<Boolean, ResponseFormat> res = Either.left(true);
3304 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3305 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3306 log.debug("Invalid YAML format");
3307 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3308 res = Either.right(responseFormat);
3314 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3315 boolean isXmlValid = isValidXml(payload);
3317 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3318 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3319 log.debug("Invalid XML content");
3320 return Either.right(responseFormat);
3322 return Either.left(true);
3325 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3326 boolean isJsonValid = isValidJson(payload);
3328 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3329 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3330 log.debug("Invalid JSON content");
3331 return Either.right(responseFormat);
3333 return Either.left(true);
3336 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3337 boolean inTransaction) {
3338 User user = new User();
3339 user.setUserId(userUserId);
3340 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3341 if (parent.isRight()) {
3342 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3345 return Either.right(responseFormat);
3347 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3350 false, inTransaction);
3351 if (handleDelete.isRight()) {
3352 return Either.right(handleDelete.right().value());
3354 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3355 return Either.left(result.right().value());
3359 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3360 Operation op = new Operation();
3361 long time = System.currentTimeMillis();
3362 op.setCreationDate(time);
3364 String artifactName = artifactInfo.getArtifactName();
3365 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3367 op.setImplementation(artifactInfo);
3368 op.setLastUpdateDate(time);
3372 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3373 String newArtifactName = operationName + "_" + artifactName;
3374 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3375 return newArtifactName;
3379 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3381 // General validation
3382 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3383 log.debug(NULL_PARAMETER);
3384 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3387 // Normalizing artifact name
3388 artifactName = ValidationUtils.normalizeFileName(artifactName);
3390 // Resource validation
3391 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3392 if (validateResourceNameAndVersion.isRight()) {
3393 return Either.right(validateResourceNameAndVersion.right().value());
3396 Resource resource = validateResourceNameAndVersion.left().value();
3397 String resourceId = resource.getUniqueId();
3399 // Service validation
3400 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3401 if (validateServiceNameAndVersion.isRight()) {
3402 return Either.right(validateServiceNameAndVersion.right().value());
3405 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3406 if (artifacts == null || artifacts.isEmpty()) {
3407 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3408 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3411 ArtifactDefinition deploymentArtifact = null;
3413 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3414 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3415 .equals(artifactName)) {
3416 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3417 deploymentArtifact = artifactDefinition;
3422 if (deploymentArtifact == null) {
3423 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3424 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3427 // Downloading the artifact
3428 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3429 if (downloadArtifactEither.isRight()) {
3430 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3431 return Either.right(downloadArtifactEither.right().value());
3433 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3434 return Either.left(downloadArtifactEither.left().value().getRight());
3438 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3440 // General validation
3441 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3442 log.debug(NULL_PARAMETER);
3443 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3446 // Normalizing artifact name
3447 artifactName = ValidationUtils.normalizeFileName(artifactName);
3449 // Service validation
3450 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3451 if (validateServiceNameAndVersion.isRight()) {
3452 return Either.right(validateServiceNameAndVersion.right().value());
3455 Service service = validateServiceNameAndVersion.left().value();
3457 // ResourceInstance validation
3458 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3459 if (validateResourceInstance.isRight()) {
3460 return Either.right(validateResourceInstance.right().value());
3463 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3465 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3467 final String finalArtifactName = artifactName;
3468 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3470 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3472 .anyMatch(filterArtifactByName);
3473 ArtifactDefinition deployableArtifact;
3475 if (!hasDeploymentArtifacts) {
3476 log.debug("Deployment artifact with name {} not found", artifactName);
3477 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3480 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3481 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3482 // Downloading the artifact
3483 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3485 if (downloadArtifactEither.isRight()) {
3486 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3487 return Either.right(downloadArtifactEither.right().value());
3489 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3490 return Either.left(downloadArtifactEither.left().value().getRight());
3493 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3495 List<ComponentInstance> riList = service.getComponentInstances();
3496 for (ComponentInstance ri : riList) {
3497 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3498 return Either.left(ri);
3502 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3505 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3507 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3508 if (serviceListBySystemName.isRight()) {
3509 log.debug("Couldn't fetch any service with name {}", serviceName);
3510 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3512 .value(), ComponentTypeEnum.SERVICE), serviceName));
3514 List<Service> serviceList = serviceListBySystemName.left().value();
3515 if (serviceList == null || serviceList.isEmpty()) {
3516 log.debug("Couldn't fetch any service with name {}", serviceName);
3517 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3520 Service foundService = null;
3521 for (Service service : serviceList) {
3522 if (service.getVersion().equals(serviceVersion)) {
3523 log.trace("Found service with version {}", serviceVersion);
3524 foundService = service;
3529 if (foundService == null) {
3530 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3531 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3532 .getValue(), serviceVersion));
3534 return Either.left(foundService);
3537 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3539 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3540 if (resourceListBySystemName.isRight()) {
3541 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3542 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3544 .value()), resourceName));
3546 return Either.left(resourceListBySystemName.left().value());
3549 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3551 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3552 if (serviceName == null || serviceVersion == null || artifactName == null) {
3553 log.debug(NULL_PARAMETER);
3554 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3557 // Normalizing artifact name
3558 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3560 // Service validation
3561 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3562 if (validateServiceNameAndVersion.isRight()) {
3563 return Either.right(validateServiceNameAndVersion.right().value());
3566 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3568 // Looking for deployment or tosca artifacts
3569 Service service = validateServiceNameAndVersion.left().value();
3571 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3572 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3573 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3576 Optional<ArtifactDefinition> foundArtifactOptl = null;
3578 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3579 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3580 // filters artifact by name
3581 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3583 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3584 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3585 // filters TOSCA artifact by name
3586 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3588 if (!foundArtifactOptl.isPresent()) {
3589 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3590 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3592 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3593 // Downloading the artifact
3594 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3596 if (downloadArtifactEither.isRight()) {
3597 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3598 return Either.right(downloadArtifactEither.right().value());
3600 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3601 return Either.left(downloadArtifactEither.left().value().getRight());
3604 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3605 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3606 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3607 if (artifactById.isRight()) {
3608 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3609 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3610 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3612 ArtifactDefinition artifactDefinition = artifactById.left().value();
3613 if (artifactDefinition == null) {
3614 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3615 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3618 return downloadArtifact(artifactDefinition);
3621 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3622 boolean found = false;
3623 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3624 if (artifactsS != null) {
3625 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3626 if (entry.getValue().getUniqueId().equals(artifactId)) {
3632 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3633 if (!found && deploymentArtifactsS != null) {
3634 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3635 if (entry.getValue().getUniqueId().equals(artifactId)) {
3641 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3642 if (!found && toscaArtifactsS != null) {
3643 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3644 if (entry.getValue().getUniqueId().equals(artifactId)) {
3650 switch (component.getComponentType()) {
3652 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3653 if (!found && interfaces != null) {
3654 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3655 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3656 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3657 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3658 .getImplementation()
3660 .equals(artifactId)) {
3669 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3670 if (!found && apiArtifacts != null) {
3671 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3672 if (entry.getValue().getUniqueId().equals(artifactId)) {
3686 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3688 boolean found = false;
3689 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3690 ComponentInstance resourceInstance = null;
3691 for (ComponentInstance ri : resourceInstances) {
3692 if (ri.getUniqueId().equals(resourceInstanceId)) {
3693 resourceInstance = ri;
3697 if (resourceInstance != null) {
3698 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3699 if (artifacts != null) {
3700 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3701 if (entry.getValue().getUniqueId().equals(artifactId)) {
3708 artifacts = resourceInstance.getArtifacts();
3709 if (artifacts != null) {
3710 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3711 if (entry.getValue().getUniqueId().equals(artifactId)) {
3722 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3723 String containerComponentType) {
3725 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3726 componentForAudit.getNodeType();
3728 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3729 .getToscaFullElement(componentId);
3731 if (componentResult.isRight()) {
3732 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3733 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3734 log.debug("Service not found, serviceId {}", componentId);
3735 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3736 return Either.right(responseFormat);
3738 return Either.left(componentResult.left().value());
3741 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3742 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3743 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3744 if (canWork.isRight()) {
3745 String uniqueId = component.getUniqueId();
3746 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3747 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3749 .getComponentType(), null);
3750 return Either.right(canWork.right().value());
3753 return Either.left(true);
3756 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3758 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3759 String role = user.getRole();
3760 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3761 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3762 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3763 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3764 return Either.right(responseFormat);
3767 return Either.left(true);
3770 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3773 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3774 } catch(ComponentException e){
3776 user.setUserId(userId);
3777 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
3778 componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3779 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3782 return Either.left(user);
3785 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3786 AuditingActionEnum auditingAction = null;
3787 switch (operation.getArtifactOperationEnum()) {
3789 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3792 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3795 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3798 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3803 return auditingAction;
3806 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3807 String esArtifactId = artifactDefinition.getEsId();
3808 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3809 if (artifactfromES.isRight()) {
3810 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3811 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3812 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3813 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3814 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3815 .getArtifactDisplayName());
3817 return Either.right(responseFormat);
3820 ESArtifactData esArtifactData = artifactfromES.left().value();
3821 byte[] data = esArtifactData.getDataAsArray();
3823 log.debug("Artifact data from ES is null");
3824 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3826 String artifactName = artifactDefinition.getArtifactName();
3827 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3828 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3831 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3832 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3835 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3836 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3838 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3839 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3842 log.info("Failed to save artifact {}.", artifactData.getId());
3848 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3849 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3852 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3853 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3856 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3857 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3858 if (user.isRight()) {
3859 ResponseFormat responseFormat;
3860 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3861 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3862 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3865 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3866 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3868 return Either.right(responseFormat);
3871 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3873 .value(), groupType);
3874 return Either.left(artifactDefinition);
3877 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3878 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3880 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3881 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3882 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3884 artifactInfo.setArtifactDisplayName(artifactName);
3885 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3886 artifactInfo.setArtifactType(artifactType);
3887 artifactInfo.setDescription(artifactDescription);
3888 artifactInfo.setArtifactGroupType(groupType);
3889 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3891 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3893 return artifactInfo;
3896 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3897 String uniqueId = null;
3899 if (resourceId != null) {
3900 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3902 artifactInfo.setUniqueId(uniqueId);
3904 artifactInfo.setUserIdCreator(user.getUserId());
3905 String fullName = user.getFullName();
3906 artifactInfo.setUpdaterFullName(fullName);
3908 long time = System.currentTimeMillis();
3910 artifactInfo.setCreatorFullName(fullName);
3911 artifactInfo.setCreationDate(time);
3913 artifactInfo.setLastUpdateDate(time);
3914 artifactInfo.setUserIdLastUpdater(user.getUserId());
3916 artifactInfo.setMandatory(true);
3919 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3920 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3923 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3924 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3927 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3929 byte[] payload = payloadStr.getBytes();
3931 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3932 return Either.left(artifactData);
3936 * @param artifactDefinition
3939 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3940 String instanceId, boolean shouldLock, boolean inTransaction) {
3941 String payload = generateHeatEnvPayload(artifactDefinition);
3942 String prevUUID = artifactDefinition.getArtifactUUID();
3943 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3944 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3946 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3949 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3950 boolean shouldLock, boolean inTransaction, String instanceId) {
3951 String payload = generateHeatEnvPayload(artifactDefinition);
3952 String prevUUID = artifactDefinition.getArtifactUUID();
3953 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3954 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3956 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3959 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3960 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3961 List<ComponentInstance> componentInstances = component.getComponentInstances();
3962 if (componentInstances != null) {
3963 Optional<ComponentInstance> findFirst = componentInstances.stream()
3964 .filter(ci -> ci.getUniqueId()
3965 .equals(instanceId))
3967 if (findFirst.isPresent()) {
3968 ComponentInstance relevantInst = findFirst.get();
3969 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3970 .getGroupInstances());
3972 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3973 updatedGroupInstances.forEach(gi -> {
3974 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3975 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3977 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3978 if (status.isRight()) {
3979 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3980 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3981 .convertFromStorageResponse(status.right()
3982 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3983 return Either.right(responseFormat);
3989 return Either.left(updatedArtDef);
3992 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3993 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3994 StringBuilder sb = new StringBuilder();
3995 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3996 sb.append("parameters:\n");
3997 if (heatParameters != null) {
3998 heatParameters.sort(Comparator.comparing(e -> e.getName()));
4000 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
4002 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
4004 String heatValue = heatParameterDefinition.getCurrentValue();
4005 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
4006 heatValue = heatParameterDefinition.getDefaultValue();
4007 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
4008 empltyHeatValues.add(heatParameterDefinition);
4012 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
4017 .append(heatParameterDefinition.getName())
4020 .append(Boolean.parseBoolean(heatValue))
4025 .append(heatParameterDefinition.getName())
4028 .append(new BigDecimal(heatValue).toPlainString())
4031 case COMMA_DELIMITED_LIST:
4034 .append(heatParameterDefinition.getName())
4041 String value = heatValue;
4042 boolean starts = value.startsWith("\"");
4043 boolean ends = value.endsWith("\"");
4044 if (!(starts && ends)) {
4045 starts = value.startsWith("'");
4046 ends = value.endsWith("'");
4047 if (!(starts && ends)) {
4048 value = "\"" + value + "\"";
4052 .append(heatParameterDefinition.getName())
4062 if (!empltyHeatValues.isEmpty()) {
4063 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
4064 empltyHeatValues.forEach(hv -> {
4065 sb.append(" ").append(hv.getName()).append(":");
4066 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
4067 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
4068 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
4069 sb.append(" \"\"").append("\n");
4072 sb.append(" ").append("\n");
4077 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
4080 return sb.toString().replaceAll("\\\\n", "\n");
4084 * @param artifactDefinition
4088 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4089 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4090 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
4091 .getHeatParamsUpdateDate(),
4092 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4096 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4097 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4098 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
4099 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4103 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
4104 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
4106 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
4108 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
4109 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
4111 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
4112 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
4113 ESArtifactData artifactData = null;
4115 if (artifactDataRes.isLeft()) {
4116 artifactData = artifactDataRes.left().value();
4119 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4120 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4121 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4122 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4124 return Either.right(artifactDataRes.right().value());
4126 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4128 String esArtifactId = artifactDefinition.getEsId();
4129 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4130 ESArtifactData esArtifactData;
4131 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4132 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4133 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4134 if (artifactfromES.isRight()) {
4135 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4136 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4137 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4138 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4139 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4141 esArtifactData = artifactfromES.left().value();
4142 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4145 oldCheckSum = artifactDefinition.getArtifactChecksum();
4148 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4151 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4152 if (lockComponent.isRight()) {
4153 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4154 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4155 return Either.right(lockComponent.right().value());
4159 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4161 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4162 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4163 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4164 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4165 .getArtifactType(), artifactDefinition.getEsId());
4166 if (updateArifactDefinitionStatus.isRight()) {
4167 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4169 .value()), artifactDefinition.getArtifactDisplayName());
4170 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4171 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4172 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4173 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4175 return Either.right(responseFormat);
4180 oldCheckSum = artifactDefinition.getArtifactChecksum();
4181 artifactDefinition.setArtifactChecksum(newCheckSum);
4182 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4183 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4184 .getArtifactType(), artifactDefinition.getEsId());
4185 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4186 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4188 log.trace("Update Payload ", artifactDefinition.getEsId());
4190 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4192 artifactDefinition = updateArifactDefinitionStatus.left().value();
4193 artifactData.setId(artifactDefinition.getUniqueId());
4194 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4196 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4197 if (!inTransaction) {
4200 log.debug("Artifact Saved In ES {}", artifactData.getId());
4201 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4202 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4203 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4204 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4208 if (!inTransaction) {
4209 titanDao.rollback();
4211 log.info("Failed to save artifact {}.", artifactData.getId());
4212 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4213 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4214 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4215 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4217 return Either.right(responseFormat);
4221 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4223 .value()), artifactDefinition.getArtifactDisplayName());
4224 log.debug("Failed To update artifact {}", artifactData.getId());
4225 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4226 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4227 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4229 return Either.right(responseFormat);
4235 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4241 return Either.left(artifactDefinition);
4245 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4246 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4247 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4248 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4252 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4253 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4255 Map<String, Object> json = new HashMap<String, Object>();
4256 if (artifactId != null && !artifactId.isEmpty()) {
4257 json.put(Constants.ARTIFACT_ID, artifactId);
4260 json.put(Constants.ARTIFACT_NAME, artifactName);
4261 json.put(Constants.ARTIFACT_TYPE, artifactType);
4262 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4264 if (artifactContent != null) {
4265 log.debug("payload is encoded. perform decode");
4266 String encodedPayload = Base64.encodeBase64String(artifactContent);
4267 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4269 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4270 json.put(Constants.ARTIFACT_LABEL, label);
4271 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4272 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4273 : updatedRequiredArtifacts.stream()
4274 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4276 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4277 .map(e -> e.getFileName())
4278 .collect(Collectors.toList()));
4279 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4284 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4286 String jsonStr = gson.toJson(json);
4287 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4288 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4289 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4290 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4291 if (uploadArtifactToService.isRight()) {
4292 return Either.right(uploadArtifactToService.right().value());
4295 return Either.left(uploadArtifactToService.left().value());
4298 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4299 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4300 convertParentType(componentType);
4301 String parentId = parent.getUniqueId();
4302 ArtifactDefinition currArtifact = artifactInfo;
4304 if (origMd5 != null) {
4305 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4306 if (validateMd5.isRight()) {
4307 ResponseFormat responseFormat = validateMd5.right().value();
4308 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4309 return Either.right(responseFormat);
4312 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4313 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4314 if (deploymentValidationResult.isRight()) {
4315 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4316 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4317 return Either.right(responseFormat);
4320 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4321 if (payloadEither.isRight()) {
4322 ResponseFormat responseFormat = payloadEither.right().value();
4323 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4324 return Either.right(responseFormat);
4328 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4329 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4330 return Either.right(responseFormat);
4336 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4337 if (lockComponent.isRight()) {
4338 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4339 .value(), componentType, null);
4340 return Either.right(lockComponent.right().value());
4343 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4345 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4351 if (resultOp == null || resultOp.isRight()) {
4352 log.debug(ROLLBACK);
4353 if (!inTransaction) {
4354 titanDao.rollback();
4359 if (!inTransaction) {
4364 componentType = parent.getComponentType();
4366 NodeTypeEnum nodeType = componentType.getNodeType();
4367 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4371 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4372 ComponentTypeEnum componentType, String origMd5) {
4374 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4375 Either<ArtifactDefinition, Operation> insideEither = null;
4376 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4377 if (getRI.isRight()) {
4378 return Either.right(getRI.right().value());
4380 ComponentInstance ri = getRI.left().value();
4381 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4382 if (getArtifactRes.isRight()) {
4383 return Either.right(getArtifactRes.right().value());
4385 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4387 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4388 .equals(ArtifactTypeEnum.HEAT_VOL
4389 .getType()) || currArtifact
4391 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4392 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4393 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4395 return Either.right(responseFormat);
4397 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4398 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4399 new ArrayList<HeatParameterDefinition>();
4402 if (origMd5 != null) {
4403 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4404 .getName(), currentHeatEnvParams,
4405 updatedHeatEnvParams, currArtifact.getArtifactName());
4406 if (uploadParamsValidationResult.isRight()) {
4407 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4408 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4410 return Either.right(responseFormat);
4412 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4415 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4417 if (validateAndConvertHeatParamers.isRight()) {
4418 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4419 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4421 return Either.right(responseFormat);
4424 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4425 // fill reduced heat env parameters List for updating
4426 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4427 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4428 currArtifact.setListHeatParameters(currentHeatEnvParams);
4430 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4431 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4432 if (updateArifactRes.isRight()) {
4433 log.debug("Failed to update artifact on graph - {}", artifactId);
4434 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4437 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4439 return Either.right(responseFormat);
4441 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4442 if (error != StorageOperationStatus.OK) {
4443 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4444 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4446 return Either.right(responseFormat);
4449 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4451 .getUniqueId(), parent.getUniqueId());
4452 if (error != StorageOperationStatus.OK) {
4453 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4454 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4456 return Either.right(responseFormat);
4460 insideEither = Either.left(currArtifact);
4461 resultOp = Either.left(insideEither);
4462 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4463 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4468 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4469 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4470 String paramName = heatEnvParam.getName();
4471 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4472 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4473 String updatedParamValue = heatEnvParam.getCurrentValue();
4474 currHeatParam.setCurrentValue(updatedParamValue);
4480 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4481 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4483 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4484 Either<ArtifactDefinition, Operation> insideEither = null;
4485 String currentHeatId = currHeatArtifact.getUniqueId();
4487 String esArtifactId = currHeatArtifact.getEsId();
4488 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4489 if (artifactFromES.isRight()) {
4490 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4491 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4492 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4493 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4494 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4497 ESArtifactData esArtifactData = artifactFromES.left().value();
4499 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4501 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4502 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4503 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4505 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4509 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4511 paramName = heatEnvParam.getName();
4512 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4513 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4515 String updatedParamValue = heatEnvParam.getCurrentValue();
4516 if (updatedParamValue == null) {
4517 updatedParamValue = heatEnvParam.getDefaultValue();
4519 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4520 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4521 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4522 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4523 .getType(), paramType.getType(), paramName);
4524 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4525 return Either.right(responseFormat);
4528 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4529 newHeatEnvParams.add(currHeatParam);
4534 if (!newHeatEnvParams.isEmpty()) {
4535 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4536 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4537 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4539 if (operationStatus.isRight()) {
4540 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4542 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4545 return Either.right(responseFormat);
4548 updatedHeatArt = operationStatus.left().value();
4550 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4551 esArtifactData.setId(updatedHeatArt.getEsId());
4553 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4556 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4557 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4558 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4559 .getUniqueId(), responseFormat, componentType, null);
4562 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4563 log.debug(FAILED_SAVE_ARTIFACT);
4564 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4565 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4566 .getUniqueId(), responseFormat, componentType, null);
4567 resultOp = Either.right(responseFormat);
4570 insideEither = Either.left(updatedHeatArt);
4573 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4574 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4575 artifactEnvInfo.setArtifactChecksum(null);
4576 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4577 .getUniqueId(), componentType.getNodeType(), componentId);
4580 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4584 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4585 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4587 .value(), parent, componentType);
4588 if (result != ActionStatus.OK) {
4589 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4590 return Either.right(responseFormat);
4594 if (updatedHeatEnvParams.isEmpty()) {
4595 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4597 resultOp = Either.left(insideEither);
4598 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4599 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4604 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4605 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4606 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4607 return Either.right(responseFormat);
4611 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4612 StorageOperationStatus error = StorageOperationStatus.OK;
4613 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4614 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4615 List<String> groupInstancesId = null;
4616 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4617 groupInstancesId = groupsInstances.stream()
4618 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4619 .contains(artifactId))
4620 .map(GroupInstanceDataDefinition::getUniqueId)
4621 .collect(Collectors.toList());
4623 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4624 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4630 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4631 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4633 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4634 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4635 .getArtifactName(), currArtifactName);
4636 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4637 return Either.right(responseFormat);
4640 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4641 String paramName = uploadedHeatParam.getName();
4642 boolean isExistsInHeat = false;
4643 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4644 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4646 isExistsInHeat = true;
4647 uploadedHeatParam.setType(currHeatParam.getType());
4648 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4649 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4650 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4654 if (!isExistsInHeat) {
4655 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4656 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4657 return Either.right(responseFormat);
4660 return Either.left(updatedHeatEnvParams);
4663 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4664 ResponseFormat responseFormat = null;
4665 List<ComponentInstance> ris = component.getComponentInstances();
4666 for (ComponentInstance ri : ris) {
4667 if (riID.equals(ri.getUniqueId())) {
4668 return Either.left(ri);
4671 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4672 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4673 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4674 return Either.right(responseFormat);
4677 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4678 ResponseFormat responseFormat = null;
4679 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4680 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4681 if (artifactId.equals(artifact.getUniqueId())) {
4682 return Either.left(artifact);
4685 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4686 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4688 return Either.right(responseFormat);
4691 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4692 ArtifactDefinition ret;
4693 if (eitherArtifact.isLeft()) {
4694 ret = eitherArtifact.left().value();
4697 ret = eitherArtifact.right().value().getImplementationArtifact();
4703 * downloads artifact of component by UUIDs
4705 * @param componentType
4706 * @param componentUuid
4707 * @param artifactUUID
4708 * @param resourceCommonInfo
4711 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4712 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4713 Either<byte[], ResponseFormat> result;
4714 byte[] downloadedArtifact = null;
4715 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4716 if (errorWrapper.isEmpty() && component != null) {
4717 resourceCommonInfo.setResourceName(component.getName());
4718 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4720 if (errorWrapper.isEmpty()) {
4721 result = Either.left(downloadedArtifact);
4724 result = Either.right(errorWrapper.getInnerElement());
4730 * downloads an artifact of resource instance of component by UUIDs
4732 * @param componentType
4733 * @param componentUuid
4734 * @param resourceInstanceName
4735 * @param artifactUUID
4738 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4739 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4740 Either<byte[], ResponseFormat> result;
4741 byte[] downloadedArtifact = null;
4742 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4743 if (errorWrapper.isEmpty()) {
4744 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4747 if (errorWrapper.isEmpty()) {
4748 result = Either.left(downloadedArtifact);
4751 result = Either.right(errorWrapper.getInnerElement());
4757 * uploads an artifact to a component by UUID
4761 * @param componentType
4762 * @param componentUuid
4763 * @param resourceCommonInfo
4767 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4768 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4769 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4770 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4771 ArtifactDefinition uploadArtifact = null;
4772 Component component = null;
4773 String componentId = null;
4774 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4775 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4776 String userId = request.getHeader(Constants.USER_ID_HEADER);
4778 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4779 if (getComponentRes.isRight()) {
4780 StorageOperationStatus status = getComponentRes.right().value();
4781 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4782 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4784 if (errorWrapper.isEmpty()) {
4785 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4786 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4788 if (!getComponentRes.left()
4790 .getMetadataDataDefinition()
4792 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4793 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4794 if (component != null) {
4795 componentId = component.getUniqueId();
4796 componentName = component.getName();
4799 resourceCommonInfo.setResourceName(componentName);
4801 if (errorWrapper.isEmpty()) {
4802 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4803 if (actionResult.isRight()) {
4804 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4807 return Either.right(actionResult.right().value());
4809 return Either.left(actionResult.left().value().left().value());
4811 return Either.right(errorWrapper.getInnerElement());
4814 * upload an artifact to a resource instance by UUID
4818 * @param componentType
4819 * @param componentUuid
4820 * @param resourceInstanceName
4824 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4825 ArtifactOperationInfo operation) {
4826 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4827 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4828 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4829 ArtifactDefinition uploadArtifact = null;
4830 Component component = null;
4831 String componentInstanceId;
4833 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4834 String userId = request.getHeader(Constants.USER_ID_HEADER);
4836 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4837 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4838 if (getComponentRes.isRight()) {
4839 StorageOperationStatus status = getComponentRes.right().value();
4840 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4841 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4843 if (errorWrapper.isEmpty() && !getComponentRes.left()
4845 .getMetadataDataDefinition()
4847 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4848 component = checkoutParentComponent(componentType, getComponentRes.left()
4850 .getMetadataDataDefinition()
4851 .getUniqueId(), userId, errorWrapper);
4853 if (errorWrapper.isEmpty()) {
4854 if (component == null) {
4855 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4858 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4861 if (errorWrapper.isEmpty()) {
4862 componentInstanceId = componentRiPair.getRight().getUniqueId();
4863 componentId = componentRiPair.getLeft().getUniqueId();
4864 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4866 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4867 .findParamByType(componentType));
4868 if (actionResult.isRight()) {
4869 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4872 errorWrapper.setInnerElement(actionResult.right().value());
4875 if (errorWrapper.isEmpty()) {
4876 uploadArtifact = actionResult.left().value().left().value();
4877 uploadArtifactResult = Either.left(uploadArtifact);
4880 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4882 return uploadArtifactResult;
4886 * updates an artifact on a component by UUID
4890 * @param componentType
4891 * @param componentUuid
4892 * @param artifactUUID
4896 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4897 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4898 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4899 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4900 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4901 ArtifactDefinition updateArtifact = null;
4902 Component component = null;
4903 String componentId = null;
4904 String artifactId = null;
4905 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4906 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4907 String userId = request.getHeader(Constants.USER_ID_HEADER);
4909 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4910 if (getComponentRes.isRight()) {
4911 StorageOperationStatus status = getComponentRes.right().value();
4912 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4913 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4915 if (errorWrapper.isEmpty()) {
4916 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4917 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4919 if (!getComponentRes.left()
4921 .getMetadataDataDefinition()
4923 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4924 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4925 if (component != null) {
4926 componentId = component.getUniqueId();
4927 componentName = component.getName();
4930 resourceCommonInfo.setResourceName(componentName);
4932 if (errorWrapper.isEmpty()) {
4933 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4935 if (errorWrapper.isEmpty()) {
4936 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4937 if (actionResult.isRight()) {
4938 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4941 errorWrapper.setInnerElement(actionResult.right().value());
4944 if (errorWrapper.isEmpty()) {
4945 updateArtifact = actionResult.left().value().left().value();
4946 updateArtifactResult = Either.left(updateArtifact);
4950 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4952 return updateArtifactResult;
4956 * updates an artifact on a resource instance by UUID
4960 * @param componentType
4961 * @param componentUuid
4962 * @param resourceInstanceName
4963 * @param artifactUUID
4964 * @param operation TODO
4967 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4968 ArtifactOperationInfo operation) {
4970 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4971 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4972 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4973 ArtifactDefinition updateArtifact = null;
4974 Component component = null;
4975 String componentInstanceId = null;
4976 String componentId = null;
4977 String artifactId = null;
4978 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4979 String userId = request.getHeader(Constants.USER_ID_HEADER);
4981 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4982 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4983 if (getComponentRes.isRight()) {
4984 StorageOperationStatus status = getComponentRes.right().value();
4985 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4986 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4988 if (errorWrapper.isEmpty() && !getComponentRes.left()
4990 .getMetadataDataDefinition()
4992 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4993 component = checkoutParentComponent(componentType, getComponentRes.left()
4995 .getMetadataDataDefinition()
4996 .getUniqueId(), userId, errorWrapper);
4998 if (errorWrapper.isEmpty()) {
4999 if (component == null) {
5000 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5003 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5006 if (errorWrapper.isEmpty()) {
5007 componentInstanceId = componentRiPair.getRight().getUniqueId();
5008 componentId = componentRiPair.getLeft().getUniqueId();
5009 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5011 if (errorWrapper.isEmpty()) {
5012 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
5014 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
5015 .findParamByType(componentType));
5016 if (actionResult.isRight()) {
5017 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5020 errorWrapper.setInnerElement(actionResult.right().value());
5023 if (errorWrapper.isEmpty()) {
5024 updateArtifact = actionResult.left().value().left().value();
5025 updateArtifactResult = Either.left(updateArtifact);
5028 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5030 return updateArtifactResult;
5034 * updates an artifact on a component by UUID
5038 * @param componentType
5039 * @param componentUuid
5040 * @param artifactUUID
5041 * @param operation TODO
5044 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
5045 String data, HttpServletRequest request, ComponentTypeEnum componentType,
5046 String componentUuid, String artifactUUID, String operationUUID,
5047 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
5048 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5049 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
5050 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5051 ArtifactDefinition updateArtifact = null;
5052 String componentId = null;
5053 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
5054 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5055 String userId = request.getHeader(Constants.USER_ID_HEADER);
5057 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5058 if (getComponentRes.isRight()) {
5059 StorageOperationStatus status = getComponentRes.right().value();
5060 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5061 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5063 if (errorWrapper.isEmpty()) {
5064 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5065 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5066 if (!getComponentRes.left()
5068 .getMetadataDataDefinition()
5070 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5071 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5072 if (component != null) {
5073 componentId = component.getUniqueId();
5074 componentName = component.getName();
5078 resourceCommonInfo.setResourceName(componentName);
5080 if (errorWrapper.isEmpty()) {
5081 Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId);
5082 if (interfaceName.isRight()) {
5083 errorWrapper.setInnerElement(interfaceName.right().value());
5085 if (errorWrapper.isEmpty()) {
5086 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5087 artifactUUID, artifactInfo, origMd5, data, interfaceName.left().value(),
5088 operationUUID, null, null);
5089 if (actionResult.isRight()) {
5090 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5093 errorWrapper.setInnerElement(actionResult.right().value());
5097 if (errorWrapper.isEmpty()) {
5098 updateArtifact = actionResult.left().value().left().value();
5099 updateArtifactResult = Either.left(updateArtifact);
5103 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5105 return updateArtifactResult;
5108 private Either<String, ResponseFormat> fetchInterfaceName(String componentId) {
5109 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
5110 toscaOperationFacade.getToscaElement(componentId);
5111 if (resourceStorageOperationStatusEither.isRight()) {
5112 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
5113 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
5114 return Either.right(componentsUtils
5115 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5117 Resource storedResource = resourceStorageOperationStatusEither.left().value();
5119 return Either.left(InterfaceUtils.createInterfaceToscaResourceName(
5120 storedResource.getName()));
5125 * deletes an artifact on a component by UUID
5128 * @param componentType
5129 * @param componentUuid
5130 * @param artifactUUID
5131 * @param resourceCommonInfo
5132 * @param operation TODO
5135 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5136 ArtifactOperationInfo operation) {
5138 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5139 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5140 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5141 ArtifactDefinition deleteArtifact = null;
5142 Component component = null;
5143 String componentId = null;
5144 String artifactId = null;
5145 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5146 String userId = request.getHeader(Constants.USER_ID_HEADER);
5148 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5149 if (getComponentRes.isRight()) {
5150 StorageOperationStatus status = getComponentRes.right().value();
5151 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5152 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5154 if (errorWrapper.isEmpty()) {
5155 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5156 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5157 if (!getComponentRes.left()
5159 .getMetadataDataDefinition()
5161 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5162 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5163 if (component != null) {
5164 componentId = component.getUniqueId();
5165 componentName = component.getName();
5168 resourceCommonInfo.setResourceName(componentName);
5170 if (errorWrapper.isEmpty()) {
5171 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5173 if (errorWrapper.isEmpty()) {
5174 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5175 if (actionResult.isRight()) {
5176 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5179 errorWrapper.setInnerElement(actionResult.right().value());
5182 if (errorWrapper.isEmpty()) {
5183 deleteArtifact = actionResult.left().value().left().value();
5184 deleteArtifactResult = Either.left(deleteArtifact);
5187 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5189 return deleteArtifactResult;
5193 * deletes an artifact from a resource instance by UUID
5196 * @param componentType
5197 * @param componentUuid
5198 * @param resourceInstanceName
5199 * @param artifactUUID
5200 * @param operation TODO
5203 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5204 ArtifactOperationInfo operation) {
5206 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5207 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5208 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5209 ArtifactDefinition deleteArtifact = null;
5210 Component component = null;
5211 String componentInstanceId = null;
5212 String componentId = null;
5213 String artifactId = null;
5214 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5215 String userId = request.getHeader(Constants.USER_ID_HEADER);
5216 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5217 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5218 if (getComponentRes.isRight()) {
5219 StorageOperationStatus status = getComponentRes.right().value();
5220 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5221 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5223 if (errorWrapper.isEmpty() && !getComponentRes.left()
5225 .getMetadataDataDefinition()
5227 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5228 component = checkoutParentComponent(componentType, getComponentRes.left()
5230 .getMetadataDataDefinition()
5231 .getUniqueId(), userId, errorWrapper);
5233 if (errorWrapper.isEmpty()) {
5234 if (component == null) {
5235 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5238 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5241 if (errorWrapper.isEmpty()) {
5242 componentInstanceId = componentRiPair.getRight().getUniqueId();
5243 componentId = componentRiPair.getLeft().getUniqueId();
5244 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5246 if (errorWrapper.isEmpty()) {
5248 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5249 .findParamByType(componentType));
5251 if (actionResult.isRight()) {
5252 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5255 errorWrapper.setInnerElement(actionResult.right().value());
5258 if (errorWrapper.isEmpty()) {
5259 deleteArtifact = actionResult.left().value().left().value();
5260 deleteArtifactResult = Either.left(deleteArtifact);
5263 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5265 return deleteArtifactResult;
5268 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5269 String artifactId = null;
5270 ArtifactDefinition foundArtifact = null;
5271 if (instance.getDeploymentArtifacts() != null) {
5272 foundArtifact = instance.getDeploymentArtifacts()
5275 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5276 .equals(artifactUUID))
5280 if (foundArtifact == null && instance.getArtifacts() != null) {
5281 foundArtifact = instance.getArtifacts()
5284 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5285 .equals(artifactUUID))
5289 if (foundArtifact == null) {
5290 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5291 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5294 artifactId = foundArtifact.getUniqueId();
5299 @SuppressWarnings("unchecked")
5300 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5301 Map<String, String> existingEnvVersions) {
5302 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5304 .getDeploymentResourceInstanceArtifacts();
5305 if (deploymentResourceArtifacts == null) {
5306 log.debug("no deployment artifacts are configured for generated artifacts");
5307 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5309 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5310 if (placeHolderData == null) {
5311 log.debug("no env type {} are configured for generated artifacts", envType);
5312 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5315 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5316 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5317 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5318 if (createArtifactPlaceHolder.isRight()) {
5319 return Either.right(createArtifactPlaceHolder.right().value());
5321 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5322 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5323 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5324 artifactHeatEnv.setTimeout(0);
5325 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5326 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5327 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5328 ArtifactDefinition heatEnvPlaceholder;
5329 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5330 if (parentType != NodeTypeEnum.ResourceInstance) {
5331 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5332 .getUniqueId(), parentType, parentId);
5333 if (addHeatEnvArtifact.isRight()) {
5334 log.debug("failed to create heat env artifact on resource instance");
5335 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5337 .value(), false), "", null));
5339 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5342 heatEnvPlaceholder = artifactHeatEnv;
5343 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5344 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5347 ComponentTypeEnum componentType = component.getComponentType();
5348 if (parentType == NodeTypeEnum.ResourceInstance) {
5349 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5351 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5352 new ResourceCommonInfo(parentName, componentType.getValue()),
5353 ResourceVersionInfo.newBuilder().build(),
5354 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5355 null, heatEnvPlaceholder, null);
5356 return Either.left(heatEnvPlaceholder);
5359 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5360 if (artifact.getListHeatParameters() == null) {
5363 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5364 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5365 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5366 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5367 heatEnvParameter.setCurrentValue(null);
5368 heatEnvParameters.add(heatEnvParameter);
5370 artifactDefinition.setListHeatParameters(heatEnvParameters);
5373 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5374 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5375 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5376 String name = heatArtifact.getArtifactName();
5379 name = heatArtifact.getArtifactLabel();
5380 fileName = name + "." + envExtension;
5383 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5385 heatEnvArtifact.setArtifactName(fileName);
5388 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5389 if (null != existingEnvVersions) {
5390 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5391 if (null != prevVersion) {
5392 heatEnvArtifact.setArtifactVersion(prevVersion);
5398 * Handles Artifacts Request For Inner Component
5400 * @param artifactsToHandle
5403 * @param vfcsNewCreatedArtifacts
5406 * @param inTransaction
5409 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5410 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5412 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5413 ComponentTypeEnum componentType = component.getComponentType();
5414 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5415 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5416 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5420 for (ArtifactDefinition artifact : artifactsToHandle) {
5421 originData = buildJsonStringForCsarVfcArtifact(artifact);
5422 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5423 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5424 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5425 if (actionResult.isRight()) {
5426 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5427 .getName(), actionResult.right().value());
5428 errorWrapper.setInnerElement(actionResult.right().value());
5429 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5430 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5434 uploadedArtifacts.add(actionResult.left().value().left().value());
5436 if (errorWrapper.isEmpty()) {
5437 handleArtifactsResult = Either.left(uploadedArtifacts);
5440 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5443 catch (Exception e) {
5444 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5445 handleArtifactsResult = Either.right(responseFormat);
5446 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5448 return handleArtifactsResult;
5451 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5452 ComponentInstance componentInstance = null;
5453 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5454 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5455 if (errorWrapper.isEmpty()) {
5456 componentInstance = component.getComponentInstances()
5458 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5459 .equals(normalizedName))
5462 if (componentInstance == null) {
5463 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5465 .getValue(), component.getName()));
5466 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5469 return componentInstance;
5472 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5474 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5475 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5476 ComponentInstance componentInstance = component.getComponentInstances()
5478 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5479 .equals(normalizedName))
5482 if (componentInstance == null) {
5483 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5485 .getValue(), component.getName()));
5486 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5489 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5491 return relatedComponentComponentInstancePair;
5494 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5495 ComponentInstance componentInstance;
5496 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5497 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5498 if (errorWrapper.isEmpty()) {
5499 componentInstance = component.getComponentInstances()
5501 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5504 if (componentInstance == null) {
5505 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5507 .getValue(), component.getName()));
5508 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5511 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5514 return relatedComponentComponentInstancePair;
5517 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5519 byte[] downloadedArtifact = null;
5520 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5521 List<ArtifactDefinition> artifactsList = null;
5522 ArtifactDefinition deploymentArtifact = null;
5523 if (artifacts != null && !artifacts.isEmpty()) {
5524 artifactsList = artifacts.values()
5526 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5527 .equals(artifactUUID))
5528 .collect(Collectors.toList());
5530 if (artifactsList == null || artifactsList.isEmpty()) {
5531 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5532 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5534 if (errorWrapper.isEmpty()) {
5535 deploymentArtifact = artifactsList.get(0);
5536 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5537 if (downloadArtifactEither.isRight()) {
5538 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5539 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5542 if (errorWrapper.isEmpty()) {
5543 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5544 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5546 return downloadedArtifact;
5549 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5550 Component component = null;
5551 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5552 if (getComponentRes.isRight()) {
5553 StorageOperationStatus status = getComponentRes.right().value();
5554 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5555 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5558 component = getComponentRes.left().value();
5563 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5564 Component component = null;
5565 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5566 if (getComponentRes.isRight()) {
5567 StorageOperationStatus status = getComponentRes.right().value();
5568 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5569 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5572 List<Component> value = getComponentRes.left().value();
5573 if (value.isEmpty()) {
5574 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5575 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5576 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5579 component = value.get(0);
5585 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5586 String artifactId = null;
5587 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5588 StorageOperationStatus storageStatus;
5589 ArtifactDefinition latestArtifact = null;
5590 List<ArtifactDefinition> artifacts = null;
5591 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5592 if (getArtifactsRes.isRight()) {
5593 storageStatus = getArtifactsRes.right().value();
5594 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5595 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5596 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5598 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5600 if (errorWrapper.isEmpty()) {
5601 artifacts = getArtifactsRes.left()
5605 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5606 .equals(artifactUUID))
5607 .collect(Collectors.toList());
5608 if (artifacts == null || artifacts.isEmpty()) {
5609 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5610 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5613 if (errorWrapper.isEmpty()) {
5614 latestArtifact = artifacts.stream().max((a1, a2) -> {
5615 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5616 if (compareRes == 0) {
5617 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5618 .getLastUpdateDate());
5622 if (latestArtifact == null) {
5623 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5624 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5627 if (errorWrapper.isEmpty()) {
5628 artifactId = latestArtifact.getUniqueId();
5633 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5635 Component component = null;
5636 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5637 if (getUserRes.isRight()) {
5638 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5641 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5643 if (errorWrapper.isEmpty()) {
5644 User modifier = getUserRes.left().value();
5645 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5646 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5647 if (checkoutRes.isRight()) {
5648 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5649 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5650 errorWrapper.setInnerElement(checkoutRes.right().value());
5653 component = checkoutRes.left().value();
5659 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5660 Map<String, Object> json = new HashMap<>();
5661 String artifactName = artifact.getArtifactName();
5662 json.put(Constants.ARTIFACT_NAME, artifactName);
5663 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5664 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5665 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5666 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5667 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5668 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5669 return gson.toJson(json);
5673 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5674 this.nodeTemplateOperation = nodeTemplateOperation;