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 java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.function.Predicate;
37 import java.util.function.Supplier;
38 import java.util.stream.Collectors;
40 import javax.servlet.http.HttpServletRequest;
41 import javax.xml.XMLConstants;
42 import javax.xml.parsers.ParserConfigurationException;
43 import javax.xml.parsers.SAXParserFactory;
45 import org.apache.commons.codec.binary.Base64;
46 import org.apache.commons.collections.CollectionUtils;
47 import org.apache.commons.collections.MapUtils;
48 import org.apache.commons.lang.StringUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.elasticsearch.common.Strings;
51 import org.openecomp.sdc.be.components.ArtifactsResolver;
52 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
53 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
54 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
55 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
56 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
57 import org.openecomp.sdc.be.config.BeEcompErrorManager;
58 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
59 import org.openecomp.sdc.be.config.ConfigurationManager;
60 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
61 import org.openecomp.sdc.be.dao.api.ActionStatus;
62 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
63 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
64 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
65 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
66 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
67 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
68 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
69 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
70 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
71 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
72 import org.openecomp.sdc.be.model.ArtifactDefinition;
73 import org.openecomp.sdc.be.model.ArtifactType;
74 import org.openecomp.sdc.be.model.Component;
75 import org.openecomp.sdc.be.model.ComponentInstance;
76 import org.openecomp.sdc.be.model.ComponentParametersView;
77 import org.openecomp.sdc.be.model.GroupDefinition;
78 import org.openecomp.sdc.be.model.GroupInstance;
79 import org.openecomp.sdc.be.model.HeatParameterDefinition;
80 import org.openecomp.sdc.be.model.InterfaceDefinition;
81 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
82 import org.openecomp.sdc.be.model.LifecycleStateEnum;
83 import org.openecomp.sdc.be.model.Operation;
84 import org.openecomp.sdc.be.model.Resource;
85 import org.openecomp.sdc.be.model.Service;
86 import org.openecomp.sdc.be.model.User;
87 import org.openecomp.sdc.be.model.heat.HeatParameterType;
88 import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
89 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
90 import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
91 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
92 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
93 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
94 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
95 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
96 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
97 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
98 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
99 import org.openecomp.sdc.be.resources.data.ESArtifactData;
100 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
101 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
102 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
103 import org.openecomp.sdc.be.servlets.RepresentationUtils;
104 import org.openecomp.sdc.be.tosca.CsarUtils;
105 import org.openecomp.sdc.be.tosca.ToscaError;
106 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
107 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
108 import org.openecomp.sdc.be.user.IUserBusinessLogic;
109 import org.openecomp.sdc.be.user.Role;
110 import org.openecomp.sdc.be.user.UserBusinessLogic;
111 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
112 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
113 import org.openecomp.sdc.common.api.Constants;
114 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
115 import org.openecomp.sdc.common.datastructure.Wrapper;
116 import org.openecomp.sdc.common.util.GeneralUtility;
117 import org.openecomp.sdc.common.util.ValidationUtils;
118 import org.openecomp.sdc.common.util.YamlToObjectConverter;
119 import org.openecomp.sdc.exception.ResponseFormat;
120 import org.slf4j.Logger;
121 import org.slf4j.LoggerFactory;
122 import org.springframework.beans.factory.annotation.Autowired;
123 import org.xml.sax.InputSource;
124 import org.xml.sax.SAXException;
125 import org.xml.sax.SAXNotRecognizedException;
126 import org.xml.sax.SAXNotSupportedException;
127 import org.xml.sax.XMLReader;
128 import org.yaml.snakeyaml.Yaml;
130 import com.google.common.annotations.VisibleForTesting;
131 import com.google.gson.Gson;
132 import com.google.gson.GsonBuilder;
134 import fj.data.Either;
136 @org.springframework.stereotype.Component("artifactBusinessLogic")
137 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
138 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
139 private static final String ARTIFACT_DESCRIPTION = "artifact description";
140 private static final String ARTIFACT_LABEL = "artifact label";
141 private static final String ARTIFACT_URL = "artifact url";
142 private static final String ARTIFACT_NAME = "artifact name";
143 private static final String ARTIFACT_PAYLOAD = "artifact payload";
145 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
146 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
147 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
149 public static final String HEAT_ENV_NAME = "heatEnv";
150 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
151 public static final String HEAT_ENV_SUFFIX = "env";
152 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
154 private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
155 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
157 @javax.annotation.Resource
158 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
159 @javax.annotation.Resource
160 private IUserAdminOperation userOperaton;
162 @javax.annotation.Resource
163 private IElementOperation elementOperation;
165 @javax.annotation.Resource
166 private ResourceBusinessLogic resourceBusinessLogic;
168 @javax.annotation.Resource
169 private ServiceBusinessLogic serviceBusinessLogic;
171 @javax.annotation.Resource
172 private UserBusinessLogic userAdminManager;
174 @javax.annotation.Resource
175 private IHeatParametersOperation heatParametersOperation;
178 private ArtifactCassandraDao artifactCassandraDao;
181 private ToscaExportHandler toscaExportUtils;
184 private CsarUtils csarUtils;
187 private LifecycleBusinessLogic lifecycleBusinessLogic;
190 private IUserBusinessLogic userBusinessLogic;
193 private NodeTemplateOperation nodeTemplateOperation;
196 private ArtifactsResolver artifactsResolver;
199 private InterfaceOperation interfaceOperation;
201 public enum ArtifactOperationEnum {
202 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
204 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
205 return operation == CREATE || operation == LINK;
209 public class ArtifactOperationInfo {
211 private ArtifactOperationEnum artifactOperationEnum;
212 private boolean isExternalApi;
213 private boolean ignoreLifecycleState;
215 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
216 this.artifactOperationEnum = artifactOperationEnum;
217 this.isExternalApi = isExternalApi;
218 this.ignoreLifecycleState = ignoreLifecycleState;
221 public boolean isExternalApi() {
222 return isExternalApi;
225 public boolean ignoreLifecycleState() {
226 return ignoreLifecycleState;
229 public ArtifactOperationEnum getArtifactOperationEnum() {
230 return artifactOperationEnum;
236 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
237 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
238 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
241 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
242 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
244 // step 1 - detect auditing type
245 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
246 // step 2 - check header
247 if (userId == null) {
248 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
249 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
250 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
251 return Either.right(responseFormat);
253 // step 3 - check user existence
254 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
255 if (userResult.isRight()) {
256 return Either.right(userResult.right().value());
259 // step 4 - check user's role
260 User user = userResult.left().value();
261 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
262 if (validateUserRole.isRight()) {
263 return Either.right(validateUserRole.right().value());
267 // 5. check service/resource existence
268 // 6. check service/resource check out
269 // 7. user is owner of checkout state
270 org.openecomp.sdc.be.model.Component component = null;
271 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
272 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
273 if (validateComponent.isRight()) {
274 return Either.right(validateComponent.right().value());
276 component = validateComponent.left().value();
277 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
278 if (validateWorkOnResource.isRight()) {
279 return Either.right(validateWorkOnResource.right().value());
283 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
284 shouldLock, inTransaction, true);
288 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
289 * For regular usage use <br>
290 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
294 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
295 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
296 Component parent = component;
297 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
299 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
300 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
302 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
303 if (errorWrapper.isEmpty()) {
305 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
308 result = Either.right(errorWrapper.getInnerElement());
313 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
314 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
315 ArtifactDefinition validatedArtifactInfo = artifactInfo;
316 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
317 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
318 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
319 if (validateArtifact.isRight()) {
320 ResponseFormat responseFormat = validateArtifact.right().value();
321 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
322 errorWrapper.setInnerElement(validateArtifact.right().value());
324 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
325 validatedArtifactInfo = validateArtifact.left().value();
326 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
329 return validatedArtifactInfo;
332 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
333 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
334 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
336 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
337 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
338 ComponentInstance componentInstance = component.getComponentInstances()
340 .filter(p -> p.getUniqueId().equals(componentId))
343 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
345 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
347 .filter(p -> p.getUniqueId()
348 .equals(validatedArtifact.getUniqueId()))
351 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
352 .getName(), user, componentId, shouldLock, inTransaction);
353 if (eitherGenerated.isRight()) {
354 errorWrapper.setInnerElement(eitherGenerated.right().value());
359 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
360 boolean needGenerate;
361 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
362 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
363 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
364 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
365 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
369 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
370 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
372 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
375 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
376 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
378 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
379 if (generated.isRight()) {
382 byte[] decodedPayload = artifactDefinition.getPayloadData();
383 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
384 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
385 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
386 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
387 shouldLock, inTransaction);
391 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
392 log.debug("tosca artifact generation");
393 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
394 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
396 if (generated.isRight()) {
397 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
400 return Either.right(generated.right().value());
402 byte[] value = generated.left().value();
403 artifactInfo.setPayload(value);
407 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
408 if (exportComponent.isRight()) {
409 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
411 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
412 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
413 return Either.right(responseFormat);
415 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
416 String payload = exportComponent.left().value().getMainYaml();
417 artifactInfo.setPayloadData(payload);
419 return Either.left(Either.left(artifactInfo));
422 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
423 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
424 /*if (interfaceName != null && operationName != null) {
425 interfaceName = interfaceName.toLowerCase();
426 operationName = operationName.toLowerCase();
428 switch (operation.getArtifactOperationEnum()) {
430 if (artifactGenerationRequired(parent, artifactInfo)) {
431 return generateNotSavedArtifact(parent, artifactInfo);
433 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
435 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
437 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
438 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
439 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
440 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
441 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
442 if (needUpdateGroup && result.isLeft()) {
443 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
444 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
445 .value(), parent, componentType, componentId);
446 if (error != ActionStatus.OK) {
447 result = Either.right(componentsUtils.getResponseFormat(error));
452 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
453 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
456 if (result == null) {
457 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
458 if (needUpdateGroup && result.isLeft()) {
459 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
461 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
462 .value(), parent, componentType);
463 if (error != ActionStatus.OK) {
464 result = Either.right(componentsUtils.getResponseFormat(error));
470 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
472 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
477 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
478 List<GroupDefinition> groups = parent.getGroups();
479 if (groups != null && !groups.isEmpty()) {
480 List<GroupDataDefinition> groupToUpdate = groups.stream()
481 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
482 .contains(artifactInfo
484 .collect(Collectors.toList());
485 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
486 groupToUpdate.forEach(g -> {
487 g.getArtifacts().remove(artifactInfo.getUniqueId());
488 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
489 g.getArtifacts().add(artAfterUpdate.getUniqueId());
490 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
492 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
493 if (status.isRight()) {
494 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
495 return componentsUtils.convertFromStorageResponse(status.right().value());
499 return ActionStatus.OK;
502 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
503 List<GroupDefinition> groups = parent.getGroups();
504 if (groups != null && !groups.isEmpty()) {
505 List<GroupDataDefinition> groupToUpdate = groups.stream()
506 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
507 .contains(artifactInfoHeat
509 .collect(Collectors.toList());
510 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
511 groupToUpdate.forEach(g -> {
512 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
513 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
514 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
515 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
516 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
517 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
519 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
520 if (status.isRight()) {
521 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
522 return componentsUtils.convertFromStorageResponse(status.right().value());
526 return ActionStatus.OK;
529 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
530 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
531 List<GroupInstance> groupInstances = null;
532 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
534 .filter(ci -> ci.getUniqueId().equals(parentId))
536 if (componentInstOp.isPresent()) {
537 groupInstances = componentInstOp.get().getGroupInstances();
539 if (CollectionUtils.isNotEmpty(groupInstances)) {
540 boolean isUpdated = false;
541 for (GroupInstance groupInstance : groupInstances) {
543 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
544 .contains(artifactInfo
546 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
547 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
550 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
551 .contains(artifactInfo
552 .getArtifactUUID())) {
553 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
554 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
558 updatedGroupInstances.add(groupInstance);
562 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
563 if (status.isRight()) {
564 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
565 return componentsUtils.convertFromStorageResponse(status.right().value());
567 return ActionStatus.OK;
570 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
571 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
572 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
573 result = generateToscaArtifact(parent, artifactInfo, false, false);
576 String heatArtifactId = artifactInfo.getGeneratedFromId();
577 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
578 if (heatRes.isRight()) {
579 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
581 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
584 return Either.right(responseFormat);
586 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
587 artifactInfo.setPayloadData(generatedPayload);
588 result = Either.left(Either.left(artifactInfo));
593 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
594 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
595 convertParentType(componentType);
596 String parentId = parent.getUniqueId();
597 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
598 .getGeneratedFromId());
599 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
601 if (origMd5 != null) {
602 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
603 if (validateMd5.isRight()) {
604 ResponseFormat responseFormat = validateMd5.right().value();
605 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
606 return Either.right(responseFormat);
609 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
611 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
612 if (payloadEither.isRight()) {
613 ResponseFormat responseFormat = payloadEither.right().value();
614 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
615 return Either.right(responseFormat);
619 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
620 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
621 return Either.right(responseFormat);
627 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
628 if (lockComponent.isRight()) {
629 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
630 .value(), componentType, null);
631 return Either.right(lockComponent.right().value());
634 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
636 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
642 if (resultOp == null || resultOp.isRight()) {
643 log.debug("all changes rollback");
644 if (!inTransaction) {
649 log.debug("all changes committed");
650 if (!inTransaction) {
655 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
660 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
661 if (artifactGenerationRequired(component, csarArtifact)) {
662 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
664 if (generated.isRight()) {
665 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
668 return Either.right(generated.right().value());
670 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
673 return downloadArtifact(csarArtifact);
676 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
677 // perform all validation in common flow
678 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
679 null, parentId, containerComponentType);
680 if (result.isRight()) {
681 return Either.right(result.right().value());
683 ArtifactDefinition artifactDefinition;
684 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
685 if (insideValue.isLeft()) {
686 artifactDefinition = insideValue.left().value();
689 artifactDefinition = insideValue.right().value().getImplementationArtifact();
691 // for tosca artifacts and heat env on VF level generated on download without saving
692 if (artifactDefinition.getPayloadData() != null) {
693 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
696 return downloadArtifact(artifactDefinition);
699 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
701 // detect auditing type
702 Map<String, ArtifactDefinition> resMap = null;
703 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
708 if (userId == null) {
709 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
710 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
712 resultOp = Either.right(responseFormat);
716 // check user existence
720 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
721 if (userResult.isRight()) {
723 resultOp = Either.right(userResult.right().value());
727 userResult.left().value();
730 // 5. check service/resource existence
731 // 6. check service/resource check out
732 // 7. user is owner of checkout state
733 org.openecomp.sdc.be.model.Component component = null;
734 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
735 ComponentParametersView componentFilter = new ComponentParametersView();
736 componentFilter.disableAll();
737 componentFilter.setIgnoreArtifacts(false);
738 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
739 componentFilter.setIgnoreComponentInstances(false);
742 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
743 .findByParamName(containerComponentType), componentFilter);
745 if (validateComponent.isRight()) {
746 resultOp = Either.right(validateComponent.right().value());
749 component = validateComponent.left().value();
750 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
751 if (lockComponent.isRight()) {
753 resultOp = Either.right(lockComponent.right().value());
758 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
760 if (groupType == null) {
761 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
762 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
764 resultOp = Either.right(responseFormat);
768 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
769 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
770 if (list != null && !list.isEmpty()) {
771 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
774 resMap = new HashMap<>();
776 resultOp = Either.left(resMap);
781 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
782 .getNodeType(), groupType, componentId);
783 if (artifactsMapStatus.isRight()) {
784 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
785 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
786 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
787 resultOp = Either.right(responseFormat);
790 resMap = new HashMap<>();
791 resultOp = Either.left(resMap);
795 resMap = artifactsMapStatus.left().value();
796 resultOp = Either.left(resMap);
803 if (resultOp == null || resultOp.isRight()) {
804 log.debug("all changes rollback");
808 log.debug("all changes committed");
812 componentType = component.getComponentType();
813 NodeTypeEnum nodeType = componentType.getNodeType();
814 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
819 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
821 // check artifact existence
822 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
824 if (artifactResult.isRight()) {
825 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
826 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
827 log.debug("addArtifact - artifact {} not found", artifactId);
828 return Either.right(responseFormat);
832 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
835 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
837 return Either.right(responseFormat);
841 // check artifact belong to component
842 boolean found = false;
843 switch (componentType) {
846 found = checkArtifactInComponent(component, artifactId);
848 case RESOURCE_INSTANCE:
849 found = checkArtifactInResourceInstance(component, componentId, artifactId);
855 String componentName = componentType.name().toLowerCase();
856 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
857 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
858 return Either.right(responseFormat);
860 return Either.left(artifactResult.left().value());
863 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
864 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
866 String artifactId = null;
869 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
870 if (payloadEither.isRight()) {
871 return Either.right(payloadEither.right().value());
873 byte[] decodedPayload = payloadEither.left().value();
874 convertParentType(componentType);
877 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
878 if (lockComponent.isRight()) {
879 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
880 .value(), componentType, null);
881 return Either.right(lockComponent.right().value());
884 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
887 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
892 unlockComponent(resultOp, parent, inTransaction);
899 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
900 Component parent, boolean shouldLock, boolean inTransaction) {
903 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
904 if (lockComponent.isRight()) {
905 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
906 .value(), componentType, null);
907 return Either.right(lockComponent.right().value());
910 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
913 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
918 unlockComponent(resultOp, parent, inTransaction);
925 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
926 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
928 convertParentType(componentType);
932 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
934 if (lockComponent.isRight()) {
935 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
936 .value(), componentType, null);
937 return Either.right(lockComponent.right().value());
941 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
943 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
949 unlockComponent(resultOp, parent, inTransaction);
954 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
955 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
957 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
959 if (payloadEither.isRight()) {
960 return Either.right(payloadEither.right().value());
962 byte[] decodedPayload = payloadEither.left().value();
964 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
967 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
968 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
970 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
971 if (validateMd5.isRight()) {
972 ResponseFormat responseFormat = validateMd5.right().value();
973 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
974 return Either.right(responseFormat);
978 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
979 if (validateResult.isRight()) {
980 ResponseFormat responseFormat = validateResult.right().value();
981 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
982 return Either.right(validateResult.right().value());
985 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
986 if (payloadEither.isRight()) {
987 ResponseFormat responseFormat = payloadEither.right().value();
988 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
989 log.debug("Error during handle payload");
990 return Either.right(responseFormat);
993 // validate heat parameters. this part must be after the parameters are
994 // extracted in "handlePayload"
995 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
997 if (validateAndConvertHeatParamers.isRight()) {
998 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
999 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
1000 log.debug("Error during handle payload");
1001 return Either.right(responseFormat);
1003 return payloadEither;
1006 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1007 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1009 if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType()
1010 .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
1013 String artifactData = buildAuditingArtifactData(artifactDefinition);
1017 user.setUserId("UNKNOWN");
1019 switch (componentTypeEnum) {
1021 Resource resource = (Resource) component;
1022 if (resource == null) {
1023 // In that case, component ID should be instead of name
1024 resource = new Resource();
1025 resource.setName(componentId);
1027 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1028 ResourceAuditData.newBuilder()
1029 .artifactUuid(prevArtifactUuid)
1030 .build(), currentArtifactUuid, artifactData);
1034 Service service = (Service) component;
1035 if (service == null) {
1036 // In that case, component ID should be instead of name
1037 service = new Service();
1038 service.setName(componentId);
1040 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE,
1041 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1042 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1043 null, null, artifactData, null);
1046 case RESOURCE_INSTANCE:
1047 if (resourceInstanceName == null) {
1048 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1050 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE,
1051 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1052 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1053 resourceInstanceName, null, artifactData, null);
1060 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1061 ComponentInstance resourceInstance = component.getComponentInstances()
1063 .filter(p -> p.getUniqueId().equals(componentId))
1066 String resourceInstanceName = null;
1067 if (resourceInstance != null) {
1068 resourceInstanceName = resourceInstance.getName();
1070 return resourceInstanceName;
1073 public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
1074 Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1075 // Putting together artifact info
1076 String artifactData = buildAuditingArtifactData(artifactDefinition);
1077 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
1078 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
1079 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
1080 return auditingFields;
1085 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1086 StringBuilder sb = new StringBuilder();
1087 if (artifactDefinition != null) {
1088 sb.append(artifactDefinition.getArtifactGroupType().getType())
1091 .append(artifactDefinition.getArtifactLabel())
1094 .append(artifactDefinition.getArtifactType())
1096 .append(artifactDefinition.getArtifactName())
1098 .append(artifactDefinition.getTimeout())
1100 .append(artifactDefinition.getEsId());
1103 if (artifactDefinition.getArtifactVersion() != null) {
1105 sb.append(artifactDefinition.getArtifactVersion());
1111 if (artifactDefinition.getArtifactUUID() != null) {
1112 sb.append(artifactDefinition.getArtifactUUID());
1118 return sb.toString();
1121 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1123 if (origMd5 != null) {
1124 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1125 if (!encodeBase64Str.equals(origMd5)) {
1126 log.debug("The calculated md5 is different then the received one");
1127 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1131 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1132 log.debug("Missing md5 header during artifact create");
1133 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1136 if (payload != null && payload.length != 0) {
1137 log.debug("Cannot have payload while md5 header is missing");
1138 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1141 return Either.left(true);
1144 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1145 ComponentTypeEnum componentType, Component parentComponent) {
1147 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1148 if (artifactById.isRight()) {
1149 return Either.right(artifactById.right().value());
1151 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1153 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1154 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1155 if (validateInformationalArtifactRes.isRight()) {
1156 return Either.right(validateInformationalArtifactRes.right().value());
1158 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1159 if (validateAndSetArtifactname.isRight()) {
1160 return Either.right(validateAndSetArtifactname.right().value());
1162 if (operationName != null && interfaceName != null) {
1163 operationName = operationName.toLowerCase();
1164 interfaceName = interfaceName.toLowerCase();
1166 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1167 if (logicalNameStatus.isRight()) {
1168 return Either.right(logicalNameStatus.right().value());
1170 // This is a patch to block possibility of updating service api fields
1171 // through other artifacts flow
1173 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1174 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1175 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1178 checkCreateFields(user, artifactInfo, artifactGroupType);
1181 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1182 if (currentArtifactInfo != null) {
1183 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1186 // artifactGroupType is not allowed to be updated
1187 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1188 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1189 if (validateGroupType.isRight()) {
1190 return Either.right(validateGroupType.right().value());
1194 NodeTypeEnum parentType = convertParentType(componentType);
1197 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1199 if (isDeploymentArtifact(artifactInfo)) {
1200 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1201 if (deploymentValidationResult.isRight()) {
1202 return Either.right(deploymentValidationResult.right().value());
1206 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1209 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1210 if (descriptionResult.isRight()) {
1211 return Either.right(descriptionResult.right().value());
1214 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1215 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1216 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1217 if (validateServiceApiType.isRight()) {
1218 return Either.right(validateServiceApiType.right().value());
1220 // Change of type is not allowed and should be ignored
1222 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1224 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1225 if (validateUrl.isRight()) {
1226 return Either.right(validateUrl.right().value());
1229 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1230 if (validateUpdate.isRight()) {
1231 log.debug("serviceApi first update cnnot be without payload.");
1232 return Either.right(validateUpdate.right().value());
1236 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1237 if (validateArtifactType.isRight()) {
1238 return Either.right(validateArtifactType.right().value());
1240 if (artifactInfo.getApiUrl() != null) {
1241 artifactInfo.setApiUrl(null);
1242 log.error("Artifact URL cannot be set through this API - ignoring");
1245 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1246 artifactInfo.setServiceApi(false);
1247 log.error("Artifact service API flag cannot be changed - ignoring");
1251 return Either.left(artifactInfo);
1254 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1255 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1256 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1257 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1258 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1262 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1264 Either<ArtifactDefinition, ResponseFormat> result = null;
1265 ArtifactDefinition foundArtifact = null;
1266 if (StringUtils.isNotEmpty(artifactId)) {
1267 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1269 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1270 log.debug("Artifact {} already exist", artifactId);
1271 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1273 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1274 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1275 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1277 if (result == null) {
1278 result = Either.left(foundArtifact);
1283 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1284 ArtifactDefinition foundArtifact;
1285 if (parentComponent.getUniqueId().equals(parentId)) {
1286 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1289 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1290 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1292 return foundArtifact;
1295 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1296 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1297 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1298 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1299 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1300 if (artifactType == null) {
1301 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1302 .getArtifactType()));
1304 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1305 String artifactTypeName = artifactType.getType();
1306 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1307 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1309 .getResourceInformationalArtifacts();
1310 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1311 if (!validArtifactTypes.contains(artifactTypeName)) {
1312 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1315 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1316 .getValidForResourceTypes();
1317 if (!validResourceType.contains(parentResourceType.name())) {
1318 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1322 return validationResult;
1325 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1326 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1327 return NodeTypeEnum.Resource;
1329 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1330 return NodeTypeEnum.ResourceInstance;
1333 return NodeTypeEnum.Service;
1337 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1338 boolean shouldLock, boolean inTransaction) {
1340 NodeTypeEnum parentType = convertParentType(componentType);
1341 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1342 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1343 ArtifactDefinition foundArtifact = null;
1344 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1345 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1346 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1347 boolean isDuplicated = false;
1349 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1352 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1353 if (lockComponent.isRight()) {
1354 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1355 .value(), componentType, null);
1356 resultOp = Either.right(lockComponent.right().value());
1359 if (resultOp == null) {
1360 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1361 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1362 if (getContainerRes.isRight()) {
1363 log.debug("Failed to fetch the container component {}. ", parentId);
1364 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1366 .value()), artifactId);
1367 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1368 resultOp = Either.right(responseFormat);
1371 if (resultOp == null) {
1372 fetchedContainerComponent = getContainerRes.left().value();
1373 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1374 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1375 if (getArtifactRes.isRight()) {
1376 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1378 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1379 .value(), artifactId);
1380 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1381 resultOp = Either.right(responseFormat);
1384 foundArtifact = getArtifactRes.left().value().getLeft();
1385 esId = foundArtifact.getEsId();
1388 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1389 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1390 .getComponentType()));
1391 if (needCloneRes.isRight()) {
1392 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1393 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1395 .value()), foundArtifact.getArtifactDisplayName());
1396 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1397 resultOp = Either.right(responseFormat);
1400 boolean isNeedToDeleteArtifactFromDB = true;
1401 if (resultOp == null) {
1403 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1404 String instanceId = parentId;
1405 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1407 if (isOnlyResourceInstanceArtifact.isRight()) {
1408 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1409 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1410 .value(), foundArtifact
1411 .getArtifactDisplayName());
1412 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1413 return Either.right(responseFormat);
1415 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1418 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1421 if (updatedArtifactRes.isRight()) {
1422 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1423 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1425 .value()), foundArtifact.getArtifactDisplayName());
1426 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1427 resultOp = Either.right(responseFormat);
1430 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1434 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1435 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1436 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1437 if (cassandraStatus != CassandraOperationStatus.OK) {
1438 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1439 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1440 .getArtifactDisplayName());
1441 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1442 resultOp = Either.right(responseFormat);
1445 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1447 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1451 .getGroupInstances());
1452 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1453 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1454 if (status.isRight()) {
1455 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1456 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1458 .value()), foundArtifact.getArtifactDisplayName());
1459 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1460 resultOp = Either.right(responseFormat);
1464 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1465 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1466 if (status != StorageOperationStatus.OK) {
1467 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1468 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1469 .getArtifactDisplayName());
1470 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1471 resultOp = Either.right(responseFormat);
1474 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1475 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1477 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1478 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1479 if (status.isRight()) {
1480 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1481 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1483 .value()), foundArtifact.getArtifactDisplayName());
1484 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1485 resultOp = Either.right(responseFormat);
1489 if (resultOp == null) {
1490 resultOp = Either.left(Either.left(foundArtifact));
1491 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1497 unlockComponent(resultOp, parent, inTransaction);
1502 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1503 Either<Boolean, ActionStatus> result = Either.left(true);
1504 ComponentInstance foundInstance = null;
1505 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1507 .filter(i -> i.getUniqueId().equals(instanceId))
1509 if (!componentInstanceOpt.isPresent()) {
1510 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1513 foundInstance = componentInstanceOpt.get();
1514 String componentUid = foundInstance.getComponentUid();
1515 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1516 if (getContainerRes.isRight()) {
1517 log.debug("Failed to fetch the container component {}. ", componentUid);
1518 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1520 Component origComponent = getContainerRes.left().value();
1521 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1522 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1523 Optional<String> op = deploymentArtifacts.keySet()
1525 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1527 if (op.isPresent()) {
1528 return Either.left(false);
1531 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1532 if (artifacts != null && !artifacts.isEmpty()) {
1533 Optional<String> op = artifacts.keySet()
1535 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1537 if (op.isPresent()) {
1538 return Either.left(false);
1546 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1547 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1548 boolean isUpdated = false;
1549 if (groups != null) {
1550 for (GroupDefinition group : groups) {
1552 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1553 group.getArtifacts().remove(artifactId);
1556 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1557 .contains(foundArtifact.getArtifactUUID())) {
1558 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1562 updatedGroups.add(group);
1566 return updatedGroups;
1569 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1570 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1571 if (CollectionUtils.isNotEmpty(groupInstances)) {
1572 boolean isUpdated = false;
1573 for (GroupInstance groupInstance : groupInstances) {
1575 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1576 .contains(artifactId)) {
1577 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1580 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1581 .contains(foundArtifact
1582 .getArtifactUUID())) {
1583 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1587 updatedGroupInstances.add(groupInstance);
1591 return updatedGroupInstances;
1594 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1596 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1597 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1598 String componentId = component.getUniqueId();
1599 String instanceId = componentId.equals(parentId) ? null : parentId;
1601 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1602 resetMandatoryArtifactFields(foundArtifact);
1603 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1605 else if (cloneIsNeeded) {
1606 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1607 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1610 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1611 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1616 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1618 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1619 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1620 ComponentInstance foundInstance = null;
1621 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1622 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1624 .filter(i -> i.getUniqueId()
1627 if (!componentInstanceOpt.isPresent()) {
1628 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1631 foundInstance = componentInstanceOpt.get();
1632 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1636 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1638 if (result == null) {
1639 if (artifacts.containsKey(artifactId)) {
1640 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1643 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1649 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1650 Map<String, ArtifactDefinition> currArtifacts;
1651 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1652 currArtifacts = component.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(component.getArtifacts())) {
1661 currArtifacts = component.getArtifacts()
1664 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1665 if (MapUtils.isNotEmpty(currArtifacts)) {
1666 artifacts.putAll(currArtifacts);
1669 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1670 currArtifacts = component.getToscaArtifacts()
1673 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1674 if (MapUtils.isNotEmpty(currArtifacts)) {
1675 artifacts.putAll(currArtifacts);
1680 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1681 Map<String, ArtifactDefinition> currArtifacts;
1682 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1683 currArtifacts = instance.getDeploymentArtifacts()
1686 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1687 if (MapUtils.isNotEmpty(currArtifacts)) {
1688 artifacts.putAll(currArtifacts);
1691 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1692 currArtifacts = instance.getArtifacts()
1695 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1696 if (MapUtils.isNotEmpty(currArtifacts)) {
1697 artifacts.putAll(currArtifacts);
1702 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1703 if (fetchedArtifact != null) {
1704 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1705 fetchedArtifact.setEsId(null);
1706 fetchedArtifact.setArtifactName(null);
1707 fetchedArtifact.setDescription(null);
1708 fetchedArtifact.setApiUrl(null);
1709 fetchedArtifact.setArtifactChecksum(null);
1710 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1711 fetchedArtifact.setArtifactUUID(null);
1712 long time = System.currentTimeMillis();
1713 fetchedArtifact.setPayloadUpdateDate(time);
1714 fetchedArtifact.setHeatParameters(null);
1715 fetchedArtifact.setHeatParamsUpdateDate(null);
1719 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1720 StorageOperationStatus error = StorageOperationStatus.OK;
1721 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1722 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1723 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1728 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1730 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1732 if (artifactById.isRight()) {
1733 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1734 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1735 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1736 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1737 return Either.right(responseFormat);
1739 ArtifactDefinition artifactDefinition = artifactById.left().value();
1740 if (artifactDefinition == null) {
1741 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1742 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1743 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1744 return Either.right(responseFormat);
1747 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1748 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1749 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1750 return Either.left(insideEither);
1753 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1754 ComponentTypeEnum componentType) {
1756 String artifactLabel = artifactInfo.getArtifactLabel();
1757 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1759 BeEcompErrorManager.getInstance()
1760 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1761 log.debug("missing artifact logical name for component {}", componentId);
1762 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1764 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1766 if (operationName != null) {
1767 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1768 log.debug("artifact label cannot be set {}", artifactLabel);
1769 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1772 artifactLabel = operationName;
1775 String displayName = artifactInfo.getArtifactDisplayName();
1776 if (displayName == null || displayName.isEmpty()) {
1777 displayName = artifactLabel;
1779 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1780 artifactInfo.setArtifactDisplayName(displayName);
1782 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1783 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1784 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1786 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1788 if (artifactLabel.isEmpty()) {
1789 log.debug("missing normalized artifact logical name for component {}", componentId);
1790 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1793 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1794 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1795 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1796 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1798 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1799 log.debug("Non unique Artifact label : {}", artifactLabel);
1800 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1803 artifactInfo.setArtifactLabel(artifactLabel);
1805 return Either.left(ActionStatus.OK);
1808 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1809 boolean isUnique = true;
1810 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1811 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1812 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1815 artifacts = artifactToscaOperation.getArtifacts(componentId);
1818 if (artifacts.isLeft()) {
1819 for (String label : artifacts.left().value().keySet()) {
1820 if (label.equals(artifactLabel)) {
1826 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1827 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1828 .getAllInterfacesOfResource(componentId, true, true);
1829 if (allInterfacesOfResource.isLeft()) {
1830 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1831 for (Operation operation : interace.getOperationsMap().values()) {
1832 if (operation.getImplementation() != null && operation.getImplementation()
1834 .equals(artifactLabel)) {
1845 // ***************************************************************
1847 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1848 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1849 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1850 Either<ArtifactDefinition, Operation> insideEither = null;
1851 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1852 String instanceId = null;
1853 String instanceName = null;
1854 if (foundInstance != null) {
1855 instanceId = foundInstance.getUniqueId();
1856 instanceName = foundInstance.getName();
1858 boolean isLeft = false;
1859 String artifactUniqueId = null;
1860 StorageOperationStatus error = null;
1861 // information/deployment/api aritfacts
1862 log.trace("Try to create entry on graph");
1863 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1864 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1865 .getUniqueId(), nodeType, true, instanceId);
1867 isLeft = result.isLeft();
1869 artifactUniqueId = result.left().value().getUniqueId();
1870 result.left().value();
1872 insideEither = Either.left(result.left().value());
1873 resultOp = Either.left(insideEither);
1875 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1876 if (error != StorageOperationStatus.OK) {
1882 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1883 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1887 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1888 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1889 .getArtifactDisplayName());
1890 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1891 resultOp = Either.right(responseFormat);
1897 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1898 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1900 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1901 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1902 Either<ArtifactDefinition, Operation> insideEither = null;
1903 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1904 String instanceId = null;
1905 String instanceName = null;
1906 if (foundInstance != null) {
1907 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1908 log.debug("Failed to create artifact, already exists");
1909 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1910 .getArtifactLabel());
1911 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1913 resultOp = Either.right(responseFormat);
1917 instanceId = foundInstance.getUniqueId();
1918 instanceName = foundInstance.getName();
1920 if (artifactData == null) {
1921 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1922 log.debug("Failed to create artifact object for ES.");
1923 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1924 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1925 resultOp = Either.right(responseFormat);
1929 // set on graph object id of artifact in ES!
1930 artifactInfo.setEsId(artifactData.getId());
1932 boolean isLeft = false;
1933 String artifactUniqueId = null;
1934 StorageOperationStatus error = null;
1935 if (interfaceType != null && operationName != null) {
1936 // lifecycle artifact
1937 Operation operation = convertToOperation(artifactInfo, operationName);
1939 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1941 isLeft = result.isLeft();
1943 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1944 result.left().value().getImplementation();
1946 insideEither = Either.right(result.left().value());
1947 resultOp = Either.left(insideEither);
1950 error = result.right().value();
1954 // information/deployment/api aritfacts
1955 log.trace("Try to create entry on graph");
1956 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1957 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1958 .getUniqueId(), nodeType, true, instanceId);
1960 isLeft = result.isLeft();
1962 artifactUniqueId = result.left().value().getUniqueId();
1963 artifactData.setId(result.left().value().getEsId());
1964 insideEither = Either.left(result.left().value());
1965 resultOp = Either.left(insideEither);
1967 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1968 if (error != StorageOperationStatus.OK) {
1974 error = result.right().value();
1978 boolean res = saveArtifacts(artifactData, parentId);
1981 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1983 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1984 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1988 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1989 log.debug("Failed to save the artifact.");
1990 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1991 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1993 resultOp = Either.right(responseFormat);
1998 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1999 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2000 .getArtifactDisplayName());
2001 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2002 resultOp = Either.right(responseFormat);
2008 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2009 ComponentInstance foundInstance = null;
2010 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2011 foundInstance = containerComponent.getComponentInstances()
2013 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2017 return foundInstance;
2020 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2022 Either<Boolean, ResponseFormat> result = Either.left(true);
2023 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
2025 validateArtifactTypeExists(responseWrapper, artifactInfo);
2027 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2029 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2031 if (responseWrapper.isEmpty()) {
2032 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2035 // Common code for all types
2036 // not allowed to change artifactType
2037 if (responseWrapper.isEmpty() && !isCreate) {
2038 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2039 if (validateServiceApiType.isRight()) {
2040 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2043 if (responseWrapper.isEmpty()) {
2044 if (parentType.equals(NodeTypeEnum.Resource)) {
2045 Resource resource = (Resource) parentComponent;
2046 ResourceTypeEnum resourceType = resource.getResourceType();
2047 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2048 if (config == null) {
2049 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2050 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2051 .getArtifactType()));
2054 List<String> myList = config.getValidForResourceTypes();
2055 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2056 if (either.isRight()) {
2057 responseWrapper.setInnerElement(either.right().value());
2062 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2065 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2066 String artifactName = artifactInfo.getArtifactName();
2067 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2068 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2072 if (responseWrapper.isEmpty()) {
2073 switch (artifactType) {
2077 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2080 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2081 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2083 case DCAE_INVENTORY_TOSCA:
2084 case DCAE_INVENTORY_JSON:
2085 case DCAE_INVENTORY_POLICY:
2086 // Validation is done in handle payload.
2087 case DCAE_INVENTORY_DOC:
2088 case DCAE_INVENTORY_BLUEPRINT:
2089 case DCAE_INVENTORY_EVENT:
2090 // No specific validation
2092 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2098 if (!responseWrapper.isEmpty()) {
2099 result = Either.right(responseWrapper.getInnerElement());
2104 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2105 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2106 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2107 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2108 .getArtifactType());
2109 responseWrapper.setInnerElement(responseFormat);
2110 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2114 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2115 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2116 if (parentType.equals(NodeTypeEnum.Resource)) {
2117 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2119 .getResourceDeploymentArtifacts();
2121 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2122 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2124 .getResourceInstanceDeploymentArtifacts();
2127 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2129 .getServiceDeploymentArtifacts();
2131 return resourceDeploymentArtifacts;
2134 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2135 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2136 if (artifactType == null) {
2137 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2138 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2139 .getArtifactType());
2140 responseWrapper.setInnerElement(responseFormat);
2141 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2145 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2146 ArtifactTypeConfig retConfig = null;
2147 String fileType = artifactType.getType();
2148 if (parentType.equals(NodeTypeEnum.Resource)) {
2149 retConfig = ConfigurationManager.getConfigurationManager()
2151 .getResourceDeploymentArtifacts()
2154 else if (parentType.equals(NodeTypeEnum.Service)) {
2155 retConfig = ConfigurationManager.getConfigurationManager()
2157 .getServiceDeploymentArtifacts()
2160 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2161 retConfig = ConfigurationManager.getConfigurationManager()
2163 .getResourceInstanceDeploymentArtifacts()
2169 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2170 // extract heat parameters
2171 if (artifactInfo.getPayloadData() != null) {
2172 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2173 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2174 .getArtifactType());
2175 if (heatParameters.isRight() && (!heatParameters.right()
2177 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2178 log.info("failed to parse heat parameters ");
2179 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2180 .getArtifactType());
2181 return Either.right(responseFormat);
2183 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2184 artifactInfo.setListHeatParameters(heatParameters.left().value());
2187 return Either.left(true);
2192 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2193 String fileType = artifactType.getType();
2194 List<String> acceptedTypes = null;
2195 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2196 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2197 log.debug("parent type of artifact can be either resource or service");
2198 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2202 if (deploymentAcceptedTypes == null) {
2203 log.debug("parent type of artifact can be either resource or service");
2204 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2205 .getArtifactType()));
2209 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2212 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2215 String artifactName = artifactInfo.getArtifactName();
2216 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2217 // Pavel - File extension validation is case-insensitive - Ella,
2219 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2220 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2221 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2226 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2228 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
2229 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
2230 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2232 if (errorWrapper.isEmpty()) {
2233 validateValidYaml(errorWrapper, artifactInfo);
2236 if (errorWrapper.isEmpty()) {
2237 // Validate Heat Exist
2238 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2239 .getComponentType());
2242 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2243 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2246 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2247 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2251 Either<Boolean, ResponseFormat> eitherResponse;
2252 if (errorWrapper.isEmpty()) {
2253 eitherResponse = Either.left(true);
2256 eitherResponse = Either.right(errorWrapper.getInnerElement());
2258 return eitherResponse;
2261 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2262 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2263 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2264 if (fillArtifactPayload.isRight()) {
2265 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2266 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2270 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2274 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2275 Either<Boolean, ResponseFormat> result = Either.left(true);
2276 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2278 if (eitherArtifactData.isLeft()) {
2279 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2280 data = Base64.encodeBase64(data);
2281 payloadWrapper.setInnerElement(data);
2284 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2287 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2288 result = Either.right(responseFormat);
2294 @SuppressWarnings("unchecked")
2295 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2296 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2297 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2298 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2299 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2301 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2302 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2303 if (eitherHeatEnvProperties.isRight()) {
2304 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2305 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2306 errorWrapper.setInnerElement(responseFormat);
2307 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2309 else if (eitherHeatProperties.isRight()) {
2310 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2311 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2312 .getArtifactName(), heatArtifact.getArtifactName());
2313 errorWrapper.setInnerElement(responseFormat);
2314 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2315 .getArtifactName());
2318 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2319 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2320 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2321 if (!heatEnvPropertiesKeys.isEmpty()) {
2322 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2323 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2324 .getArtifactName(), heatArtifact.getArtifactName());
2325 errorWrapper.setInnerElement(responseFormat);
2330 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2331 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2332 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2334 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2335 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2336 .getArtifactType());
2337 errorWrapper.setInnerElement(responseFormat);
2338 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2342 private boolean isValidXml(byte[] xmlToParse) {
2343 boolean isXmlValid = true;
2345 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2346 setFeatures(reader);
2347 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2349 catch (ParserConfigurationException | IOException | SAXException e) {
2350 log.debug("Xml is invalid : {}", e.getMessage(), e);
2356 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2358 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2359 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2361 catch (SAXNotRecognizedException e) {
2362 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2366 private boolean isValidJson(byte[] jsonToParse) {
2367 String parsed = new String(jsonToParse);
2369 gson.fromJson(parsed, Object.class);
2371 catch (Exception e) {
2372 log.debug("Json is invalid : {}", e.getMessage(), e);
2378 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2379 boolean artifactNameFound = false;
2380 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2383 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2384 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2386 if (artifactNameFound) {
2387 String parentName = parentComponent.getName();
2388 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2389 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2390 .name(), parentName, artifactName);
2392 errorWrapper.setInnerElement(responseFormat);
2393 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2398 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2399 ComponentTypeEnum componentType) {
2400 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2401 if (res.isRight()) {
2402 ResponseFormat responseFormat;
2403 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2404 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2407 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2409 errorWrapper.setInnerElement(responseFormat);
2412 ArtifactDefinition heatArtifact = res.left().value();
2413 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2416 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2417 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2418 // timeout > 0 for HEAT artifacts
2419 Integer timeout = artifactInfo.getTimeout();
2420 if (timeout == null) {
2421 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2422 artifactInfo.setTimeout(defaultTimeout);
2423 // HEAT artifact but timeout is invalid
2425 else if (timeout < 1) {
2426 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2429 // US649856 - Allow several HEAT files on Resource
2430 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2431 return Either.left(true);
2434 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2435 String listToString = (typeList != null) ? typeList.toString() : "";
2436 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2437 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2438 .getArtifactName(), listToString, resourceType.getValue());
2439 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2440 String resourceTypeName = resourceType.name();
2441 if (typeList != null && typeList.contains(resourceTypeName)) {
2442 either = Either.left(true);
2447 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2448 if (artifactInfo.getHeatParameters() != null) {
2449 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2450 String parameterType = heatParam.getType();
2451 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2452 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2453 if (heatParameterType == null) {
2454 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2456 return Either.right(responseFormat);
2459 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2460 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2461 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2462 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2463 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2464 .getType(), heatParam.getName());
2465 return Either.right(responseFormat);
2469 return Either.left(artifactInfo);
2472 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2473 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2474 if (parentComponent.getDeploymentArtifacts() != null) {
2475 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2476 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2477 if (getRI.isRight()) {
2478 return deploymentArtifacts;
2480 ComponentInstance ri = getRI.left().value();
2481 if (ri.getDeploymentArtifacts() != null) {
2482 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2485 else if (parentComponent.getDeploymentArtifacts() != null) {
2486 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2489 return deploymentArtifacts;
2492 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2493 // on create if null add informational to current
2494 if (artifactInfo.getArtifactGroupType() == null) {
2495 artifactInfo.setArtifactGroupType(type);
2497 if (artifactInfo.getUniqueId() != null) {
2498 log.error("artifact uniqid cannot be set ignoring");
2500 artifactInfo.setUniqueId(null);
2502 if (artifactInfo.getArtifactRef() != null) {
2503 log.error("artifact ref cannot be set ignoring");
2505 artifactInfo.setArtifactRef(null);
2507 if (artifactInfo.getArtifactRepository() != null) {
2508 log.error("artifact repository cannot be set ignoring");
2510 artifactInfo.setArtifactRepository(null);
2512 if (artifactInfo.getUserIdCreator() != null) {
2513 log.error("creator uuid cannot be set ignoring");
2515 artifactInfo.setArtifactCreator(user.getUserId());
2517 if (artifactInfo.getUserIdLastUpdater() != null) {
2518 log.error("userId of last updater cannot be set ignoring");
2520 artifactInfo.setUserIdLastUpdater(user.getUserId());
2522 if (artifactInfo.getCreatorFullName() != null) {
2523 log.error("creator Full name cannot be set ignoring");
2525 String fullName = user.getFirstName() + " " + user.getLastName();
2526 artifactInfo.setUpdaterFullName(fullName);
2528 if (artifactInfo.getUpdaterFullName() != null) {
2529 log.error("updater Full name cannot be set ignoring");
2531 artifactInfo.setUpdaterFullName(fullName);
2533 if (artifactInfo.getCreationDate() != null) {
2534 log.error("Creation Date cannot be set ignoring");
2536 long time = System.currentTimeMillis();
2537 artifactInfo.setCreationDate(time);
2539 if (artifactInfo.getLastUpdateDate() != null) {
2540 log.error("Last Update Date cannot be set ignoring");
2542 artifactInfo.setLastUpdateDate(time);
2544 if (artifactInfo.getEsId() != null) {
2545 log.error("es id cannot be set ignoring");
2547 artifactInfo.setEsId(null);
2552 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2553 String id = artifactId;
2554 if (artifactId == null || artifactId.isEmpty()) {
2555 String uniqueId = null;
2556 if (interfaceName != null && operationName != null) {
2557 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2558 .getArtifactLabel());
2561 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2563 artifactInfo.setUniqueId(uniqueId);
2564 artifactInfo.setEsId(uniqueId);
2568 artifactInfo.setUniqueId(artifactId);
2569 artifactInfo.setEsId(artifactId);
2574 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2575 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2576 BeEcompErrorManager.getInstance()
2577 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2578 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2579 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2582 boolean artifactTypeExist = false;
2583 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2584 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2586 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2587 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2591 allArtifactTypes = elementOperation.getAllArtifactTypes();
2593 if (allArtifactTypes.isRight()) {
2594 BeEcompErrorManager.getInstance()
2595 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2599 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2601 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2604 for (ArtifactType type : allArtifactTypes.left().value()) {
2605 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2606 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2607 artifactTypeExist = true;
2612 if (!artifactTypeExist) {
2613 BeEcompErrorManager.getInstance()
2614 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2615 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2616 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2617 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2618 .getArtifactType()));
2621 return Either.left(ActionStatus.OK);
2624 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2626 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2627 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2629 if (parentType.equals(NodeTypeEnum.Service)) {
2630 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2632 .getServiceDeploymentArtifacts();
2634 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2635 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2637 .getResourceInstanceDeploymentArtifacts();
2640 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2642 .getResourceDeploymentArtifacts();
2644 if (deploymentArtifacts != null) {
2645 for (String artifactType : deploymentArtifacts.keySet()) {
2646 ArtifactType artifactT = new ArtifactType();
2647 artifactT.setName(artifactType);
2648 artifactTypes.add(artifactT);
2650 return Either.left(artifactTypes);
2653 return Either.right(ActionStatus.GENERAL_ERROR);
2658 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2659 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2660 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2662 return Either.left(true);
2666 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2667 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2668 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2671 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2672 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2673 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2675 artifactInfo.setArtifactName(normalizeFileName);
2677 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2678 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2681 return Either.left(true);
2684 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2685 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2686 log.info("artifact type is missing operation ignored");
2687 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2690 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2691 log.info("artifact type cannot be changed operation ignored");
2692 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2694 return Either.left(true);
2697 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2698 if (artifactInfo.getArtifactGroupType() == null) {
2699 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2702 else if (!currentArtifact.getArtifactGroupType()
2704 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2705 log.info("artifact group type cannot be changed. operation failed");
2706 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2708 return Either.left(artifactInfo);
2711 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2713 // on update if null add informational to current
2714 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2715 currentArtifact.setArtifactGroupType(type);
2718 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2719 log.error("artifact uniqid cannot be set ignoring");
2721 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2723 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2724 .equals(artifactInfo.getArtifactRef())) {
2725 log.error("artifact ref cannot be set ignoring");
2727 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2729 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2730 .equals(artifactInfo.getArtifactRepository())) {
2731 log.error("artifact repository cannot be set ignoring");
2733 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2735 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2736 .equals(artifactInfo.getUserIdCreator())) {
2737 log.error("creator uuid cannot be set ignoring");
2739 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2741 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2742 .equals(artifactInfo.getArtifactCreator())) {
2743 log.error("artifact creator cannot be set ignoring");
2745 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2747 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2748 .equals(artifactInfo.getUserIdLastUpdater())) {
2749 log.error("userId of last updater cannot be set ignoring");
2751 artifactInfo.setUserIdLastUpdater(user.getUserId());
2753 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2754 .equals(artifactInfo.getCreatorFullName())) {
2755 log.error("creator Full name cannot be set ignoring");
2757 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2759 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2760 .equals(artifactInfo.getUpdaterFullName())) {
2761 log.error("updater Full name cannot be set ignoring");
2763 String fullName = user.getFirstName() + " " + user.getLastName();
2764 artifactInfo.setUpdaterFullName(fullName);
2766 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2767 .equals(artifactInfo.getCreationDate())) {
2768 log.error("Creation Date cannot be set ignoring");
2770 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2772 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2773 .equals(artifactInfo.getLastUpdateDate())) {
2774 log.error("Last Update Date cannot be set ignoring");
2776 long time = System.currentTimeMillis();
2777 artifactInfo.setLastUpdateDate(time);
2779 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2780 log.error("es id cannot be set ignoring");
2782 artifactInfo.setEsId(currentArtifact.getUniqueId());
2784 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2785 .equals(artifactInfo.getArtifactDisplayName())) {
2786 log.error(" Artifact Display Name cannot be set ignoring");
2788 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2790 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2791 .equals(artifactInfo.getServiceApi())) {
2792 log.debug("serviceApi cannot be set. ignoring.");
2794 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2796 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2797 .equals(artifactInfo.getArtifactGroupType())) {
2798 log.debug("artifact group cannot be set. ignoring.");
2800 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2802 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2804 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2805 .isEmpty() && !currentArtifact.getArtifactUUID()
2806 .equals(artifactInfo.getArtifactUUID())) {
2807 log.debug("artifact UUID cannot be set. ignoring.");
2809 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2811 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2812 .getHeatParameters()
2813 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2814 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2818 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2820 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2821 for (HeatParameterDefinition parameter : heatParameters) {
2822 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2824 if (currentParam != null) {
2826 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2827 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2828 parameter.setName(currentParam.getName());
2830 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2831 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2832 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2833 parameter.setDefaultValue(currentParam.getDefaultValue());
2835 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2836 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2837 parameter.setType(currentParam.getType());
2839 if (parameter.getDescription() != null && !parameter.getDescription()
2840 .equalsIgnoreCase(currentParam.getDescription())) {
2841 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2842 parameter.setDescription(currentParam.getDescription());
2845 // check and set current value
2846 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2847 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2848 parameter.setCurrentValue(currentParam.getDefaultValue());
2854 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2856 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2857 for (HeatParameterDefinition param : currentParameters) {
2858 currentParamsMap.put(param.getUniqueId(), param);
2860 return currentParamsMap;
2863 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2864 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2865 log.debug("Artifact url cannot be empty.");
2866 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2868 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2870 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2871 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2873 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2874 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2877 return Either.left(true);
2880 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2881 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2882 log.debug("Artifact description cannot be empty.");
2883 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2885 String description = artifactInfo.getDescription();
2886 description = ValidationUtils.removeNoneUtf8Chars(description);
2887 description = ValidationUtils.normaliseWhitespace(description);
2888 description = ValidationUtils.stripOctets(description);
2889 description = ValidationUtils.removeHtmlTagsOnly(description);
2890 if (!ValidationUtils.validateIsEnglish(description)) {
2891 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2893 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2894 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2895 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2897 artifactInfo.setDescription(description);
2898 return Either.left(true);
2901 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2902 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2903 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2904 String prevArtifactId = null;
2905 String currArtifactId = artifactId;
2907 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2908 Either<ArtifactDefinition, Operation> insideEither = null;
2910 log.trace("Try to update entry on graph");
2911 String artifactUniqueId = null;
2912 ArtifactDefinition artifactDefinition = artifactInfo;
2913 StorageOperationStatus error;
2916 if (interfaceType == null || operationUuid == null) {
2917 log.debug("Entity on graph is updated. Update artifact in ES");
2919 // Changing previous and current artifactId for auditing
2920 prevArtifactId = currArtifactId;
2921 currArtifactId = artifactDefinition.getUniqueId();
2924 if (decodedPayload == null) {
2925 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2926 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2928 if (artifactFromCassandra.isRight()) {
2929 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2930 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2932 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2933 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2934 resultOp = Either.right(responseFormat);
2937 // clone data to new artifact
2938 artifactData.setData(artifactFromCassandra.left().value().getData());
2939 artifactData.setId(artifactFromCassandra.left().value().getId());
2942 if (artifactDefinition.getEsId() == null) {
2943 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2944 artifactData.setId(artifactDefinition.getUniqueId());
2948 NodeTypeEnum convertParentType = convertParentType(componentType);
2949 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
2950 .getUniqueId(), artifactId, convertParentType, parentId);
2951 isLeft = result.isLeft();
2953 artifactUniqueId = result.left().value().getUniqueId();
2954 artifactDefinition = result.left().value();
2955 String artifactType = artifactInfo.getArtifactType();
2956 if (NodeTypeEnum.Resource == convertParentType
2957 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
2958 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
2959 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
2960 && !artifactUniqueId.equals(artifactId)) {
2961 // need to update the generated id in heat env
2962 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2963 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
2965 .filter(a -> a.getValue()
2966 .getGeneratedFromId() != null && a
2968 .getGeneratedFromId()
2969 .equals(artifactId))
2971 if (findFirst.isPresent()) {
2972 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2973 artifactEnvInfo.setArtifactChecksum(null);
2974 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2977 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2979 insideEither = Either.left(result.left().value());
2980 resultOp = Either.left(insideEither);
2981 if (error != StorageOperationStatus.OK) {
2986 error = result.right().value();
2990 // create new entry in ES
2992 if (artifactData.getData() != null) {
2993 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
2994 artifactData.setId(artifactDefinition.getEsId());
2996 res = saveArtifacts(artifactData, parentId);
3002 log.debug("Artifact saved into ES - {}", artifactUniqueId);
3003 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3004 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3006 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3007 log.debug("Failed to save the artifact.");
3008 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3009 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3010 resultOp = Either.right(responseFormat);
3013 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3014 decodedPayload, componentType, auditingAction, operationUuid, artifactData, prevArtifactId,
3015 currArtifactId, artifactDefinition);
3021 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3022 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3023 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction,
3024 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3025 ArtifactDefinition artifactDefinition) {
3026 StorageOperationStatus error;
3027 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3028 if (decodedPayload == null) {
3029 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3030 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3032 if (artifactFromCassandra.isRight()) {
3033 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3034 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3036 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3037 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3038 resultOp = Either.right(responseFormat);
3041 // clone data to new artifact
3042 artifactData.setData(artifactFromCassandra.left().value().getData());
3043 artifactData.setId(artifactFromCassandra.left().value().getId());
3045 // todo if not exist(first time)
3049 if (artifactDefinition.getEsId() == null) {
3050 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3051 artifactData.setId(artifactDefinition.getUniqueId());
3054 NodeTypeEnum convertParentType = convertParentType(componentType);
3055 // fetch the resource from storage
3056 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
3057 toscaOperationFacade.getToscaElement(parentId);
3058 if (resourceStorageOperationStatusEither.isRight()) {
3059 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
3060 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
3061 return Either.right(componentsUtils
3062 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
3064 Resource storedResource = resourceStorageOperationStatusEither.left().value();
3066 String interfaceToscaName = InterfaceUtils.createInterfaceToscaResourceName(
3067 storedResource.getName());
3068 //fetch the interface from storage
3069 Optional<InterfaceDefinition> interfaceDefinition = storedResource.getInterfaces().values()
3071 .filter(interfaceDef -> interfaceDef.getToscaResourceName()
3072 .equals(interfaceToscaName))
3074 if (!interfaceDefinition.isPresent()) {
3075 log.debug("Failed to get resource interface for resource Id {}", parentId);
3076 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3077 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3078 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3079 currArtifactId, responseFormat, componentType, null);
3080 return Either.right(responseFormat);
3083 //fetch the operation from storage
3084 InterfaceDefinition gotInterface = interfaceDefinition.get();
3085 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
3086 Optional<Operation> optionalOperation = operationsMap.values()
3088 .filter(o -> o.getUniqueId().equals(operationUuid))
3090 if (!optionalOperation.isPresent()) {
3091 log.debug("Failed to get resource interface operation for resource Id {} " +
3092 " and operationId {}", parentId, operationUuid);
3093 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3094 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3095 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3096 currArtifactId, responseFormat, componentType, null);
3097 return Either.right(responseFormat);
3100 Operation operation = optionalOperation.get();
3101 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
3102 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
3103 implementationArtifact.setDescription(artifactInfo.getDescription());
3104 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
3105 operation.setImplementation(implementationArtifact);
3106 gotInterface.setOperationsMap(operationsMap);
3107 Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
3108 interfaceOperation.updateInterface(storedResource.getUniqueId(), gotInterface);
3109 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
3110 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
3111 ActionStatus actionStatus =
3112 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
3113 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3116 String uniqueId = implementationArtifact.getUniqueId();
3117 artifactData.setId(uniqueId);
3118 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3119 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3120 log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
3121 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3122 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3123 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3125 return Either.left(Either.left(implementationArtifact));
3128 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3129 log.trace("Starting payload handling");
3130 byte[] payload = artifactInfo.getPayloadData();
3131 byte[] decodedPayload = null;
3133 if (payload != null && payload.length != 0) {
3134 // the generated artifacts were already decoded by the handler
3135 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3136 if (decodedPayload.length == 0) {
3137 log.debug("Failed to decode the payload.");
3138 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3139 return Either.right(responseFormat);
3142 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3143 artifactInfo.setArtifactChecksum(checkSum);
3144 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3146 // Specific payload validations of different types
3147 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3148 if (isDeploymentArtifact(artifactInfo)) {
3149 log.trace("Starting deployment artifacts payload validation");
3150 String artifactType = artifactInfo.getArtifactType();
3151 if (ArtifactTypeEnum.HEAT.getType()
3152 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3153 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3155 .equalsIgnoreCase(artifactType)
3156 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3157 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3158 if (isValidPayload.isLeft()) {
3159 isValidPayload = extractHeatParameters(artifactInfo);
3162 else if (ArtifactTypeEnum.YANG_XML.getType()
3163 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3164 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3166 .equalsIgnoreCase(artifactType)
3167 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3168 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3170 .equalsIgnoreCase(artifactType)
3171 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3172 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3174 .equalsIgnoreCase(artifactType)) {
3175 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3177 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3178 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3180 .equalsIgnoreCase(artifactType)
3181 || ArtifactTypeEnum.VES_EVENTS.getType()
3182 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3184 .equalsIgnoreCase(artifactType)) {
3185 String artifactFileName = artifactInfo.getArtifactName();
3186 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3187 switch (fileExtension) {
3189 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3192 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3196 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3203 if (isValidPayload.isRight()) {
3204 ResponseFormat responseFormat = isValidPayload.right().value();
3205 return Either.right(responseFormat);
3208 } // null/empty payload is normal if called from metadata update ONLY.
3209 // The validation of whether this is metadata/payload update case is
3210 // currently done separately
3212 if (!isArtifactMetadataUpdate) {
3213 log.debug("Payload is missing.");
3214 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3215 return Either.right(responseFormat);
3218 log.trace("Ended payload handling");
3219 return Either.left(decodedPayload);
3222 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3223 // Basic YAML validation
3224 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3225 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3226 log.debug("Invalid YAML format");
3227 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3228 return Either.right(responseFormat);
3230 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3231 // HEAT specific YAML validation
3232 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3233 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3234 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3235 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3236 return Either.right(responseFormat);
3240 return Either.left(true);
3243 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3244 Either<Boolean, ResponseFormat> res = Either.left(true);
3245 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3246 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3247 log.debug("Invalid YAML format");
3248 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3249 res = Either.right(responseFormat);
3255 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3256 boolean isXmlValid = isValidXml(payload);
3258 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3259 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3260 log.debug("Invalid XML content");
3261 return Either.right(responseFormat);
3263 return Either.left(true);
3266 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3267 boolean isJsonValid = isValidJson(payload);
3269 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3270 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3271 log.debug("Invalid JSON content");
3272 return Either.right(responseFormat);
3274 return Either.left(true);
3277 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3278 boolean inTransaction) {
3279 User user = new User();
3280 user.setUserId(userUserId);
3281 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3282 if (parent.isRight()) {
3283 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3286 return Either.right(responseFormat);
3288 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3291 false, inTransaction);
3292 if (handleDelete.isRight()) {
3293 return Either.right(handleDelete.right().value());
3295 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3296 return Either.left(result.right().value());
3300 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3301 Operation op = new Operation();
3302 long time = System.currentTimeMillis();
3303 op.setCreationDate(time);
3305 String artifactName = artifactInfo.getArtifactName();
3306 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3308 op.setImplementation(artifactInfo);
3309 op.setLastUpdateDate(time);
3313 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3314 String newArtifactName = operationName + "_" + artifactName;
3315 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3316 return newArtifactName;
3320 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3322 // General validation
3323 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3324 log.debug("One of the function parameteres is null");
3325 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3328 // Normalizing artifact name
3329 artifactName = ValidationUtils.normalizeFileName(artifactName);
3331 // Resource validation
3332 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3333 if (validateResourceNameAndVersion.isRight()) {
3334 return Either.right(validateResourceNameAndVersion.right().value());
3337 Resource resource = validateResourceNameAndVersion.left().value();
3338 String resourceId = resource.getUniqueId();
3340 // Service validation
3341 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3342 if (validateServiceNameAndVersion.isRight()) {
3343 return Either.right(validateServiceNameAndVersion.right().value());
3346 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3347 if (artifacts == null || artifacts.isEmpty()) {
3348 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3349 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3352 ArtifactDefinition deploymentArtifact = null;
3354 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3355 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3356 .equals(artifactName)) {
3357 log.debug("Found deployment artifact {}", artifactName);
3358 deploymentArtifact = artifactDefinition;
3363 if (deploymentArtifact == null) {
3364 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3365 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3368 // Downloading the artifact
3369 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3370 if (downloadArtifactEither.isRight()) {
3371 log.debug("Download artifact {} failed", artifactName);
3372 return Either.right(downloadArtifactEither.right().value());
3374 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3375 return Either.left(downloadArtifactEither.left().value().getRight());
3379 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3381 // General validation
3382 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3383 log.debug("One of the function parameteres is null");
3384 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3387 // Normalizing artifact name
3388 artifactName = ValidationUtils.normalizeFileName(artifactName);
3390 // Service validation
3391 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3392 if (validateServiceNameAndVersion.isRight()) {
3393 return Either.right(validateServiceNameAndVersion.right().value());
3396 Service service = validateServiceNameAndVersion.left().value();
3398 // ResourceInstance validation
3399 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3400 if (validateResourceInstance.isRight()) {
3401 return Either.right(validateResourceInstance.right().value());
3404 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3406 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3408 final String finalArtifactName = artifactName;
3409 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3411 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3413 .anyMatch(filterArtifactByName);
3414 ArtifactDefinition deployableArtifact;
3416 if (!hasDeploymentArtifacts) {
3417 log.debug("Deployment artifact with name {} not found", artifactName);
3418 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3421 log.debug("Found deployment artifact {}", artifactName);
3422 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3423 // Downloading the artifact
3424 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3426 if (downloadArtifactEither.isRight()) {
3427 log.debug("Download artifact {} failed", artifactName);
3428 return Either.right(downloadArtifactEither.right().value());
3430 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3431 return Either.left(downloadArtifactEither.left().value().getRight());
3434 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3436 List<ComponentInstance> riList = service.getComponentInstances();
3437 for (ComponentInstance ri : riList) {
3438 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3439 return Either.left(ri);
3443 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3446 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3448 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3449 if (serviceListBySystemName.isRight()) {
3450 log.debug("Couldn't fetch any service with name {}", serviceName);
3451 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3453 .value(), ComponentTypeEnum.SERVICE), serviceName));
3455 List<Service> serviceList = serviceListBySystemName.left().value();
3456 if (serviceList == null || serviceList.isEmpty()) {
3457 log.debug("Couldn't fetch any service with name {}", serviceName);
3458 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3461 Service foundService = null;
3462 for (Service service : serviceList) {
3463 if (service.getVersion().equals(serviceVersion)) {
3464 log.trace("Found service with version {}", serviceVersion);
3465 foundService = service;
3470 if (foundService == null) {
3471 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3472 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3473 .getValue(), serviceVersion));
3475 return Either.left(foundService);
3478 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3480 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3481 if (resourceListBySystemName.isRight()) {
3482 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3483 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3485 .value()), resourceName));
3487 return Either.left(resourceListBySystemName.left().value());
3490 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3492 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3493 if (serviceName == null || serviceVersion == null || artifactName == null) {
3494 log.debug("One of the function parameteres is null");
3495 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3498 // Normalizing artifact name
3499 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3501 // Service validation
3502 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3503 if (validateServiceNameAndVersion.isRight()) {
3504 return Either.right(validateServiceNameAndVersion.right().value());
3507 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3509 // Looking for deployment or tosca artifacts
3510 Service service = validateServiceNameAndVersion.left().value();
3512 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3513 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3514 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3517 Optional<ArtifactDefinition> foundArtifactOptl = null;
3519 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3520 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3521 // filters artifact by name
3522 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3524 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3525 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3526 // filters TOSCA artifact by name
3527 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3529 if (!foundArtifactOptl.isPresent()) {
3530 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3531 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3533 log.debug("Found deployment artifact {}", normalizedArtifactName);
3534 // Downloading the artifact
3535 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3537 if (downloadArtifactEither.isRight()) {
3538 log.debug("Download artifact {} failed", normalizedArtifactName);
3539 return Either.right(downloadArtifactEither.right().value());
3541 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3542 return Either.left(downloadArtifactEither.left().value().getRight());
3545 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3546 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3547 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3548 if (artifactById.isRight()) {
3549 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3550 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3551 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3553 ArtifactDefinition artifactDefinition = artifactById.left().value();
3554 if (artifactDefinition == null) {
3555 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3556 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3559 return downloadArtifact(artifactDefinition);
3562 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3563 boolean found = false;
3564 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3565 if (artifactsS != null) {
3566 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3567 if (entry.getValue().getUniqueId().equals(artifactId)) {
3573 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3574 if (!found && deploymentArtifactsS != null) {
3575 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3576 if (entry.getValue().getUniqueId().equals(artifactId)) {
3582 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3583 if (!found && toscaArtifactsS != null) {
3584 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3585 if (entry.getValue().getUniqueId().equals(artifactId)) {
3591 switch (component.getComponentType()) {
3593 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3594 if (!found && interfaces != null) {
3595 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3596 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3597 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3598 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3599 .getImplementation()
3601 .equals(artifactId)) {
3610 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3611 if (!found && apiArtifacts != null) {
3612 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3613 if (entry.getValue().getUniqueId().equals(artifactId)) {
3627 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3629 boolean found = false;
3630 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3631 ComponentInstance resourceInstance = null;
3632 for (ComponentInstance ri : resourceInstances) {
3633 if (ri.getUniqueId().equals(resourceInstanceId)) {
3634 resourceInstance = ri;
3638 if (resourceInstance != null) {
3639 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3640 if (artifacts != null) {
3641 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3642 if (entry.getValue().getUniqueId().equals(artifactId)) {
3649 artifacts = resourceInstance.getArtifacts();
3650 if (artifacts != null) {
3651 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3652 if (entry.getValue().getUniqueId().equals(artifactId)) {
3663 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3664 String containerComponentType) {
3666 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3667 componentForAudit.getNodeType();
3669 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3670 .getToscaFullElement(componentId);
3672 if (componentResult.isRight()) {
3673 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3674 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3675 log.debug("Service not found, serviceId {}", componentId);
3676 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3677 return Either.right(responseFormat);
3679 return Either.left(componentResult.left().value());
3682 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3683 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3684 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3685 if (canWork.isRight()) {
3686 String uniqueId = component.getUniqueId();
3687 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3688 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3690 .getComponentType(), null);
3691 return Either.right(canWork.right().value());
3694 return Either.left(true);
3697 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3699 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3700 String role = user.getRole();
3701 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3702 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3703 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3704 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3705 return Either.right(responseFormat);
3708 return Either.left(true);
3711 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3712 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3714 if (validateUserExists.isRight()) {
3715 User user = new User();
3716 user.setUserId(userId);
3717 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right()
3718 .value(), componentType, null);
3719 return Either.right(validateUserExists.right().value());
3721 return Either.left(validateUserExists.left().value());
3724 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3725 AuditingActionEnum auditingAction = null;
3726 switch (operation.getArtifactOperationEnum()) {
3728 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3731 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3734 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3737 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3742 return auditingAction;
3745 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3746 String esArtifactId = artifactDefinition.getEsId();
3747 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3748 if (artifactfromES.isRight()) {
3749 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3750 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3751 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3752 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3753 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3754 .getArtifactDisplayName());
3756 return Either.right(responseFormat);
3759 ESArtifactData esArtifactData = artifactfromES.left().value();
3760 byte[] data = esArtifactData.getDataAsArray();
3762 log.debug("Artifact data from ES is null");
3763 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3765 String artifactName = artifactDefinition.getArtifactName();
3766 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3767 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3770 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3771 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3774 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3775 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3777 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3778 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3781 log.info("Failed to save artifact {}.", artifactData.getId());
3787 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3788 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3791 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3792 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3795 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3796 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3797 if (user.isRight()) {
3798 ResponseFormat responseFormat;
3799 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3800 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3801 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3804 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3805 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3807 return Either.right(responseFormat);
3810 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3812 .value(), groupType);
3813 return Either.left(artifactDefinition);
3816 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3817 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3819 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3820 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3821 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3823 artifactInfo.setArtifactDisplayName(artifactName);
3824 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3825 artifactInfo.setArtifactType(artifactType);
3826 artifactInfo.setDescription(artifactDescription);
3827 artifactInfo.setArtifactGroupType(groupType);
3828 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3830 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3832 return artifactInfo;
3835 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3836 String uniqueId = null;
3838 if (resourceId != null) {
3839 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3841 artifactInfo.setUniqueId(uniqueId);
3843 artifactInfo.setUserIdCreator(user.getUserId());
3844 String fullName = user.getFullName();
3845 artifactInfo.setUpdaterFullName(fullName);
3847 long time = System.currentTimeMillis();
3849 artifactInfo.setCreatorFullName(fullName);
3850 artifactInfo.setCreationDate(time);
3852 artifactInfo.setLastUpdateDate(time);
3853 artifactInfo.setUserIdLastUpdater(user.getUserId());
3855 artifactInfo.setMandatory(true);
3858 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3859 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3862 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3863 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3866 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3868 byte[] payload = payloadStr.getBytes();
3870 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3871 return Either.left(artifactData);
3875 * @param artifactDefinition
3878 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3879 String instanceId, boolean shouldLock, boolean inTransaction) {
3880 String payload = generateHeatEnvPayload(artifactDefinition);
3881 String prevUUID = artifactDefinition.getArtifactUUID();
3882 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3883 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3885 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3888 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3889 boolean shouldLock, boolean inTransaction, String instanceId) {
3890 String payload = generateHeatEnvPayload(artifactDefinition);
3891 String prevUUID = artifactDefinition.getArtifactUUID();
3892 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3893 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3895 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3898 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3899 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3900 List<ComponentInstance> componentInstances = component.getComponentInstances();
3901 if (componentInstances != null) {
3902 Optional<ComponentInstance> findFirst = componentInstances.stream()
3903 .filter(ci -> ci.getUniqueId()
3904 .equals(instanceId))
3906 if (findFirst.isPresent()) {
3907 ComponentInstance relevantInst = findFirst.get();
3908 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3909 .getGroupInstances());
3911 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3912 updatedGroupInstances.forEach(gi -> {
3913 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3914 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3916 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3917 if (status.isRight()) {
3918 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3919 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3920 .convertFromStorageResponse(status.right()
3921 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3922 return Either.right(responseFormat);
3928 return Either.left(updatedArtDef);
3931 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3932 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3933 StringBuilder sb = new StringBuilder();
3934 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3935 sb.append("parameters:\n");
3936 if (heatParameters != null) {
3937 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3939 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3941 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3943 String heatValue = heatParameterDefinition.getCurrentValue();
3944 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3945 heatValue = heatParameterDefinition.getDefaultValue();
3946 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3947 empltyHeatValues.add(heatParameterDefinition);
3951 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3956 .append(heatParameterDefinition.getName())
3959 .append(Boolean.parseBoolean(heatValue))
3964 .append(heatParameterDefinition.getName())
3967 .append(new BigDecimal(heatValue).toPlainString())
3970 case COMMA_DELIMITED_LIST:
3973 .append(heatParameterDefinition.getName())
3980 String value = heatValue;
3981 boolean starts = value.startsWith("\"");
3982 boolean ends = value.endsWith("\"");
3983 if (!(starts && ends)) {
3984 starts = value.startsWith("'");
3985 ends = value.endsWith("'");
3986 if (!(starts && ends)) {
3987 value = "\"" + value + "\"";
3991 .append(heatParameterDefinition.getName())
4001 if (!empltyHeatValues.isEmpty()) {
4002 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
4003 empltyHeatValues.forEach(hv -> {
4004 sb.append(" ").append(hv.getName()).append(":");
4005 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
4006 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
4007 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
4008 sb.append(" \"\"").append("\n");
4011 sb.append(" ").append("\n");
4016 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
4019 return sb.toString().replaceAll("\\\\n", "\n");
4023 * @param artifactDefinition
4027 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4028 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4029 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
4030 .getHeatParamsUpdateDate(),
4031 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4035 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4036 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4037 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
4038 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4042 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
4043 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
4045 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
4047 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
4048 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
4050 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
4051 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
4052 ESArtifactData artifactData = null;
4054 if (artifactDataRes.isLeft()) {
4055 artifactData = artifactDataRes.left().value();
4058 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4059 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4060 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4061 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4063 return Either.right(artifactDataRes.right().value());
4065 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4067 String esArtifactId = artifactDefinition.getEsId();
4068 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4069 ESArtifactData esArtifactData;
4070 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4071 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4072 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4073 if (artifactfromES.isRight()) {
4074 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4075 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4076 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4077 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4078 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4080 esArtifactData = artifactfromES.left().value();
4081 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4084 oldCheckSum = artifactDefinition.getArtifactChecksum();
4087 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4090 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4091 if (lockComponent.isRight()) {
4092 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4093 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4094 return Either.right(lockComponent.right().value());
4098 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4100 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4101 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4102 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4103 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4104 .getArtifactType(), artifactDefinition.getEsId());
4105 if (updateArifactDefinitionStatus.isRight()) {
4106 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4108 .value()), artifactDefinition.getArtifactDisplayName());
4109 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4110 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4111 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4112 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4114 return Either.right(responseFormat);
4119 oldCheckSum = artifactDefinition.getArtifactChecksum();
4120 artifactDefinition.setArtifactChecksum(newCheckSum);
4121 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4122 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4123 .getArtifactType(), artifactDefinition.getEsId());
4124 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4125 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4127 log.trace("Update Payload ", artifactDefinition.getEsId());
4129 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4131 artifactDefinition = updateArifactDefinitionStatus.left().value();
4132 artifactData.setId(artifactDefinition.getUniqueId());
4133 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4135 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4136 if (!inTransaction) {
4139 log.debug("Artifact Saved In ES {}", artifactData.getId());
4140 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4141 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4142 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4143 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4147 if (!inTransaction) {
4148 titanDao.rollback();
4150 log.info("Failed to save artifact {}.", artifactData.getId());
4151 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4152 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4153 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4154 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4156 return Either.right(responseFormat);
4160 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4162 .value()), artifactDefinition.getArtifactDisplayName());
4163 log.debug("Failed To update artifact {}", artifactData.getId());
4164 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4165 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4166 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4168 return Either.right(responseFormat);
4174 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4180 return Either.left(artifactDefinition);
4184 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4185 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4186 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4187 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4191 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4192 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4194 Map<String, Object> json = new HashMap<String, Object>();
4195 if (artifactId != null && !artifactId.isEmpty()) {
4196 json.put(Constants.ARTIFACT_ID, artifactId);
4199 json.put(Constants.ARTIFACT_NAME, artifactName);
4200 json.put(Constants.ARTIFACT_TYPE, artifactType);
4201 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4203 if (artifactContent != null) {
4204 log.debug("payload is encoded. perform decode");
4205 String encodedPayload = Base64.encodeBase64String(artifactContent);
4206 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4208 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4209 json.put(Constants.ARTIFACT_LABEL, label);
4210 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4211 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4212 : updatedRequiredArtifacts.stream()
4213 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4215 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4216 .map(e -> e.getFileName())
4217 .collect(Collectors.toList()));
4218 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4223 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4225 String jsonStr = gson.toJson(json);
4226 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4227 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4228 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4229 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4230 if (uploadArtifactToService.isRight()) {
4231 return Either.right(uploadArtifactToService.right().value());
4234 return Either.left(uploadArtifactToService.left().value());
4237 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4238 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4239 convertParentType(componentType);
4240 String parentId = parent.getUniqueId();
4241 ArtifactDefinition currArtifact = artifactInfo;
4243 if (origMd5 != null) {
4244 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4245 if (validateMd5.isRight()) {
4246 ResponseFormat responseFormat = validateMd5.right().value();
4247 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4248 return Either.right(responseFormat);
4251 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4252 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4253 if (deploymentValidationResult.isRight()) {
4254 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4255 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4256 return Either.right(responseFormat);
4259 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4260 if (payloadEither.isRight()) {
4261 ResponseFormat responseFormat = payloadEither.right().value();
4262 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4263 return Either.right(responseFormat);
4267 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4268 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4269 return Either.right(responseFormat);
4275 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
4276 if (lockComponent.isRight()) {
4277 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4278 .value(), componentType, null);
4279 return Either.right(lockComponent.right().value());
4282 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4284 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4290 if (resultOp == null || resultOp.isRight()) {
4291 log.debug("all changes rollback");
4292 if (!inTransaction) {
4293 titanDao.rollback();
4297 log.debug("all changes committed");
4298 if (!inTransaction) {
4303 componentType = parent.getComponentType();
4305 NodeTypeEnum nodeType = componentType.getNodeType();
4306 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4310 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4311 ComponentTypeEnum componentType, String origMd5) {
4313 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4314 Either<ArtifactDefinition, Operation> insideEither = null;
4315 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4316 if (getRI.isRight()) {
4317 return Either.right(getRI.right().value());
4319 ComponentInstance ri = getRI.left().value();
4320 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4321 if (getArtifactRes.isRight()) {
4322 return Either.right(getArtifactRes.right().value());
4324 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4326 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4327 .equals(ArtifactTypeEnum.HEAT_VOL
4328 .getType()) || currArtifact
4330 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4331 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4332 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4334 return Either.right(responseFormat);
4336 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4337 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4338 new ArrayList<HeatParameterDefinition>();
4341 if (origMd5 != null) {
4342 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4343 .getName(), currentHeatEnvParams,
4344 updatedHeatEnvParams, currArtifact.getArtifactName());
4345 if (uploadParamsValidationResult.isRight()) {
4346 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4347 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4349 return Either.right(responseFormat);
4351 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4354 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4356 if (validateAndConvertHeatParamers.isRight()) {
4357 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4358 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4360 return Either.right(responseFormat);
4363 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4364 // fill reduced heat env parameters List for updating
4365 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4366 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4367 currArtifact.setListHeatParameters(currentHeatEnvParams);
4369 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4370 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4371 if (updateArifactRes.isRight()) {
4372 log.debug("Failed to update artifact on graph - {}", artifactId);
4373 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4376 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4378 return Either.right(responseFormat);
4380 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4381 if (error != StorageOperationStatus.OK) {
4382 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4383 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4385 return Either.right(responseFormat);
4388 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4390 .getUniqueId(), parent.getUniqueId());
4391 if (error != StorageOperationStatus.OK) {
4392 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4393 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4395 return Either.right(responseFormat);
4399 insideEither = Either.left(currArtifact);
4400 resultOp = Either.left(insideEither);
4401 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4402 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4407 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4408 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4409 String paramName = heatEnvParam.getName();
4410 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4411 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4412 String updatedParamValue = heatEnvParam.getCurrentValue();
4413 currHeatParam.setCurrentValue(updatedParamValue);
4419 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4420 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4422 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4423 Either<ArtifactDefinition, Operation> insideEither = null;
4424 String currentHeatId = currHeatArtifact.getUniqueId();
4426 String esArtifactId = currHeatArtifact.getEsId();
4427 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4428 if (artifactFromES.isRight()) {
4429 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4430 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4431 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4432 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4433 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4436 ESArtifactData esArtifactData = artifactFromES.left().value();
4438 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4440 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4441 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4442 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4444 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4448 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4450 paramName = heatEnvParam.getName();
4451 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4452 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4454 String updatedParamValue = heatEnvParam.getCurrentValue();
4455 if (updatedParamValue == null) {
4456 updatedParamValue = heatEnvParam.getDefaultValue();
4458 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4459 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4460 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4461 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4462 .getType(), paramType.getType(), paramName);
4463 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4464 return Either.right(responseFormat);
4467 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4468 newHeatEnvParams.add(currHeatParam);
4473 if (!newHeatEnvParams.isEmpty()) {
4474 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4475 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4476 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4478 if (operationStatus.isRight()) {
4479 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4481 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4484 return Either.right(responseFormat);
4487 updatedHeatArt = operationStatus.left().value();
4489 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4490 esArtifactData.setId(updatedHeatArt.getEsId());
4492 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4495 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
4496 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4497 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4498 .getUniqueId(), responseFormat, componentType, null);
4501 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
4502 log.debug("Failed to save the artifact.");
4503 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4504 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4505 .getUniqueId(), responseFormat, componentType, null);
4506 resultOp = Either.right(responseFormat);
4509 insideEither = Either.left(updatedHeatArt);
4512 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4513 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4514 artifactEnvInfo.setArtifactChecksum(null);
4515 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4516 .getUniqueId(), componentType.getNodeType(), componentId);
4519 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4523 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4524 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4526 .value(), parent, componentType);
4527 if (result != ActionStatus.OK) {
4528 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4529 return Either.right(responseFormat);
4533 if (updatedHeatEnvParams.isEmpty()) {
4534 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4536 resultOp = Either.left(insideEither);
4537 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4538 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4543 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4544 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4545 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4546 return Either.right(responseFormat);
4550 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4551 StorageOperationStatus error = StorageOperationStatus.OK;
4552 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4553 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4554 List<String> groupInstancesId = null;
4555 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4556 groupInstancesId = groupsInstances.stream()
4557 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4558 .contains(artifactId))
4559 .map(GroupInstanceDataDefinition::getUniqueId)
4560 .collect(Collectors.toList());
4562 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4563 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4569 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4570 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4572 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4573 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4574 .getArtifactName(), currArtifactName);
4575 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4576 return Either.right(responseFormat);
4579 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4580 String paramName = uploadedHeatParam.getName();
4581 boolean isExistsInHeat = false;
4582 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4583 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4585 isExistsInHeat = true;
4586 uploadedHeatParam.setType(currHeatParam.getType());
4587 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4588 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4589 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4593 if (!isExistsInHeat) {
4594 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4595 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4596 return Either.right(responseFormat);
4599 return Either.left(updatedHeatEnvParams);
4602 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4603 ResponseFormat responseFormat = null;
4604 List<ComponentInstance> ris = component.getComponentInstances();
4605 for (ComponentInstance ri : ris) {
4606 if (riID.equals(ri.getUniqueId())) {
4607 return Either.left(ri);
4610 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4611 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4612 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4613 return Either.right(responseFormat);
4616 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4617 ResponseFormat responseFormat = null;
4618 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4619 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4620 if (artifactId.equals(artifact.getUniqueId())) {
4621 return Either.left(artifact);
4624 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4625 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4627 return Either.right(responseFormat);
4630 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4631 ArtifactDefinition ret;
4632 if (eitherArtifact.isLeft()) {
4633 ret = eitherArtifact.left().value();
4636 ret = eitherArtifact.right().value().getImplementationArtifact();
4642 * downloads artifact of component by UUIDs
4644 * @param componentType
4645 * @param componentUuid
4646 * @param artifactUUID
4647 * @param auditAdditionalParam
4650 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4651 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4652 Either<byte[], ResponseFormat> result;
4653 byte[] downloadedArtifact = null;
4654 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4655 if (errorWrapper.isEmpty()) {
4656 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4657 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4659 if (errorWrapper.isEmpty()) {
4660 result = Either.left(downloadedArtifact);
4663 result = Either.right(errorWrapper.getInnerElement());
4669 * downloads an artifact of resource instance of component by UUIDs
4671 * @param componentType
4672 * @param componentUuid
4673 * @param resourceInstanceName
4674 * @param artifactUUID
4675 * @param auditAdditionalParam
4678 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4679 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4680 Either<byte[], ResponseFormat> result;
4681 byte[] downloadedArtifact = null;
4682 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4683 if (errorWrapper.isEmpty()) {
4684 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4687 if (errorWrapper.isEmpty()) {
4688 result = Either.left(downloadedArtifact);
4691 result = Either.right(errorWrapper.getInnerElement());
4697 * uploads an artifact to a component by UUID
4701 * @param componentType
4702 * @param componentUuid
4703 * @param additionalParams
4707 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4708 ArtifactOperationInfo operation) {
4709 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4710 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4711 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4712 ArtifactDefinition uploadArtifact = null;
4713 Component component = null;
4714 String componentId = null;
4715 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4716 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4717 String userId = request.getHeader(Constants.USER_ID_HEADER);
4719 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4720 if (getComponentRes.isRight()) {
4721 StorageOperationStatus status = getComponentRes.right().value();
4722 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4723 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4725 if (errorWrapper.isEmpty()) {
4726 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4727 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4729 if (!getComponentRes.left()
4731 .getMetadataDataDefinition()
4733 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4734 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4735 if (component != null) {
4736 componentId = component.getUniqueId();
4737 componentName = component.getName();
4740 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4742 if (errorWrapper.isEmpty()) {
4743 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4744 if (actionResult.isRight()) {
4745 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4748 errorWrapper.setInnerElement(actionResult.right().value());
4751 if (errorWrapper.isEmpty()) {
4752 uploadArtifact = actionResult.left().value().left().value();
4753 uploadArtifactResult = Either.left(uploadArtifact);
4756 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4758 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4759 return uploadArtifactResult;
4763 * upload an artifact to a resource instance by UUID
4767 * @param componentType
4768 * @param componentUuid
4769 * @param resourceInstanceName
4770 * @param additionalParams
4774 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4775 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4776 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4777 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4778 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4779 ArtifactDefinition uploadArtifact = null;
4780 Component component = null;
4781 String componentInstanceId;
4783 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4784 String userId = request.getHeader(Constants.USER_ID_HEADER);
4786 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4787 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4788 if (getComponentRes.isRight()) {
4789 StorageOperationStatus status = getComponentRes.right().value();
4790 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4791 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4793 if (errorWrapper.isEmpty() && !getComponentRes.left()
4795 .getMetadataDataDefinition()
4797 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4798 component = checkoutParentComponent(componentType, getComponentRes.left()
4800 .getMetadataDataDefinition()
4801 .getUniqueId(), userId, errorWrapper);
4803 if (errorWrapper.isEmpty()) {
4804 if (component == null) {
4805 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4808 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4811 if (errorWrapper.isEmpty()) {
4812 componentInstanceId = componentRiPair.getRight().getUniqueId();
4813 componentId = componentRiPair.getLeft().getUniqueId();
4814 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4816 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4817 .findParamByType(componentType));
4818 if (actionResult.isRight()) {
4819 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4822 errorWrapper.setInnerElement(actionResult.right().value());
4825 if (errorWrapper.isEmpty()) {
4826 uploadArtifact = actionResult.left().value().left().value();
4827 uploadArtifactResult = Either.left(uploadArtifact);
4830 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4832 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4833 return uploadArtifactResult;
4837 * updates an artifact on a component by UUID
4841 * @param componentType
4842 * @param componentUuid
4843 * @param artifactUUID
4844 * @param additionalParams
4845 * @param operation TODO
4848 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4849 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4850 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4851 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4852 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4853 ArtifactDefinition updateArtifact = null;
4854 Component component = null;
4855 String componentId = null;
4856 String artifactId = null;
4857 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4858 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4859 String userId = request.getHeader(Constants.USER_ID_HEADER);
4861 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4862 if (getComponentRes.isRight()) {
4863 StorageOperationStatus status = getComponentRes.right().value();
4864 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4865 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4867 if (errorWrapper.isEmpty()) {
4868 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4869 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4871 if (!getComponentRes.left()
4873 .getMetadataDataDefinition()
4875 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4876 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4877 if (component != null) {
4878 componentId = component.getUniqueId();
4879 componentName = component.getName();
4882 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4884 if (errorWrapper.isEmpty()) {
4885 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4887 if (errorWrapper.isEmpty()) {
4888 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4889 if (actionResult.isRight()) {
4890 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4893 errorWrapper.setInnerElement(actionResult.right().value());
4896 if (errorWrapper.isEmpty()) {
4897 updateArtifact = actionResult.left().value().left().value();
4898 updateArtifactResult = Either.left(updateArtifact);
4902 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4904 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4905 return updateArtifactResult;
4909 * updates an artifact on a resource instance by UUID
4913 * @param componentType
4914 * @param componentUuid
4915 * @param resourceInstanceName
4916 * @param artifactUUID
4917 * @param additionalParams
4918 * @param operation TODO
4921 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4922 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4924 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4925 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4926 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4927 ArtifactDefinition updateArtifact = null;
4928 Component component = null;
4929 String componentInstanceId = null;
4930 String componentId = null;
4931 String artifactId = null;
4932 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4933 String userId = request.getHeader(Constants.USER_ID_HEADER);
4935 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4936 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4937 if (getComponentRes.isRight()) {
4938 StorageOperationStatus status = getComponentRes.right().value();
4939 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4940 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4942 if (errorWrapper.isEmpty() && !getComponentRes.left()
4944 .getMetadataDataDefinition()
4946 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4947 component = checkoutParentComponent(componentType, getComponentRes.left()
4949 .getMetadataDataDefinition()
4950 .getUniqueId(), userId, errorWrapper);
4952 if (errorWrapper.isEmpty()) {
4953 if (component == null) {
4954 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4957 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4960 if (errorWrapper.isEmpty()) {
4961 componentInstanceId = componentRiPair.getRight().getUniqueId();
4962 componentId = componentRiPair.getLeft().getUniqueId();
4963 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4965 if (errorWrapper.isEmpty()) {
4966 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4968 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4969 .findParamByType(componentType));
4970 if (actionResult.isRight()) {
4971 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4974 errorWrapper.setInnerElement(actionResult.right().value());
4977 if (errorWrapper.isEmpty()) {
4978 updateArtifact = actionResult.left().value().left().value();
4979 updateArtifactResult = Either.left(updateArtifact);
4982 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4984 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4985 return updateArtifactResult;
4989 * updates an artifact on a component by UUID
4993 * @param componentType
4994 * @param componentUuid
4995 * @param artifactUUID
4996 * @param additionalParams
4997 * @param operation TODO
5000 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
5001 String data, HttpServletRequest request, ComponentTypeEnum componentType,
5002 String componentUuid, String artifactUUID, String operationUUID,
5003 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
5004 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5005 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
5006 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5007 ArtifactDefinition updateArtifact = null;
5008 String componentId = null;
5009 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
5010 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5011 String userId = request.getHeader(Constants.USER_ID_HEADER);
5013 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5014 if (getComponentRes.isRight()) {
5015 StorageOperationStatus status = getComponentRes.right().value();
5016 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5017 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5019 if (errorWrapper.isEmpty()) {
5020 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5021 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5022 if (!getComponentRes.left()
5024 .getMetadataDataDefinition()
5026 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5027 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5028 if (component != null) {
5029 componentId = component.getUniqueId();
5030 componentName = component.getName();
5032 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
5035 if (errorWrapper.isEmpty()) {
5036 Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId);
5037 if (interfaceName.isRight()) {
5038 errorWrapper.setInnerElement(interfaceName.right().value());
5040 if (errorWrapper.isEmpty()) {
5041 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5042 artifactUUID, artifactInfo, origMd5, data, interfaceName.left().value(),
5043 operationUUID, null, null);
5044 if (actionResult.isRight()) {
5045 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
5048 errorWrapper.setInnerElement(actionResult.right().value());
5052 if (errorWrapper.isEmpty()) {
5053 updateArtifact = actionResult.left().value().left().value();
5054 updateArtifactResult = Either.left(updateArtifact);
5058 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5060 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
5061 return updateArtifactResult;
5064 private Either<String, ResponseFormat> fetchInterfaceName(String componentId) {
5065 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
5066 toscaOperationFacade.getToscaElement(componentId);
5067 if (resourceStorageOperationStatusEither.isRight()) {
5068 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
5069 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
5070 return Either.right(componentsUtils
5071 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5073 Resource storedResource = resourceStorageOperationStatusEither.left().value();
5075 return Either.left(InterfaceUtils.createInterfaceToscaResourceName(
5076 storedResource.getName()));
5081 * deletes an artifact on a component by UUID
5084 * @param componentType
5085 * @param componentUuid
5086 * @param artifactUUID
5087 * @param additionalParams
5088 * @param operation TODO
5091 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
5092 ArtifactOperationInfo operation) {
5094 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5095 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5096 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5097 ArtifactDefinition deleteArtifact = null;
5098 Component component = null;
5099 String componentId = null;
5100 String artifactId = null;
5101 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5102 String userId = request.getHeader(Constants.USER_ID_HEADER);
5104 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5105 if (getComponentRes.isRight()) {
5106 StorageOperationStatus status = getComponentRes.right().value();
5107 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5108 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5110 if (errorWrapper.isEmpty()) {
5111 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5112 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5113 if (!getComponentRes.left()
5115 .getMetadataDataDefinition()
5117 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5118 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5119 if (component != null) {
5120 componentId = component.getUniqueId();
5121 componentName = component.getName();
5124 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
5126 if (errorWrapper.isEmpty()) {
5127 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5129 if (errorWrapper.isEmpty()) {
5130 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5131 if (actionResult.isRight()) {
5132 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
5135 errorWrapper.setInnerElement(actionResult.right().value());
5138 if (errorWrapper.isEmpty()) {
5139 deleteArtifact = actionResult.left().value().left().value();
5140 deleteArtifactResult = Either.left(deleteArtifact);
5143 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5145 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5146 return deleteArtifactResult;
5150 * deletes an artifact from a resource instance by UUID
5153 * @param componentType
5154 * @param componentUuid
5155 * @param resourceInstanceName
5156 * @param artifactUUID
5157 * @param additionalParams
5158 * @param operation TODO
5161 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5162 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
5164 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5165 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5166 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5167 ArtifactDefinition deleteArtifact = null;
5168 Component component = null;
5169 String componentInstanceId = null;
5170 String componentId = null;
5171 String artifactId = null;
5172 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5173 String userId = request.getHeader(Constants.USER_ID_HEADER);
5174 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5175 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5176 if (getComponentRes.isRight()) {
5177 StorageOperationStatus status = getComponentRes.right().value();
5178 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5179 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5181 if (errorWrapper.isEmpty() && !getComponentRes.left()
5183 .getMetadataDataDefinition()
5185 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5186 component = checkoutParentComponent(componentType, getComponentRes.left()
5188 .getMetadataDataDefinition()
5189 .getUniqueId(), userId, errorWrapper);
5191 if (errorWrapper.isEmpty()) {
5192 if (component == null) {
5193 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5196 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5199 if (errorWrapper.isEmpty()) {
5200 componentInstanceId = componentRiPair.getRight().getUniqueId();
5201 componentId = componentRiPair.getLeft().getUniqueId();
5202 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5204 if (errorWrapper.isEmpty()) {
5206 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5207 .findParamByType(componentType));
5209 if (actionResult.isRight()) {
5210 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
5213 errorWrapper.setInnerElement(actionResult.right().value());
5216 if (errorWrapper.isEmpty()) {
5217 deleteArtifact = actionResult.left().value().left().value();
5218 deleteArtifactResult = Either.left(deleteArtifact);
5221 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5223 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5224 return deleteArtifactResult;
5227 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5228 String artifactId = null;
5229 ArtifactDefinition foundArtifact = null;
5230 if (instance.getDeploymentArtifacts() != null) {
5231 foundArtifact = instance.getDeploymentArtifacts()
5234 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5235 .equals(artifactUUID))
5239 if (foundArtifact == null && instance.getArtifacts() != null) {
5240 foundArtifact = instance.getArtifacts()
5243 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5244 .equals(artifactUUID))
5248 if (foundArtifact == null) {
5249 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5250 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5253 artifactId = foundArtifact.getUniqueId();
5258 @SuppressWarnings("unchecked")
5259 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5260 Map<String, String> existingEnvVersions) {
5261 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5263 .getDeploymentResourceInstanceArtifacts();
5264 if (deploymentResourceArtifacts == null) {
5265 log.debug("no deployment artifacts are configured for generated artifacts");
5266 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5268 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5269 if (placeHolderData == null) {
5270 log.debug("no env type {} are configured for generated artifacts", envType);
5271 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5274 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5275 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5276 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5277 if (createArtifactPlaceHolder.isRight()) {
5278 return Either.right(createArtifactPlaceHolder.right().value());
5280 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5281 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5282 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5283 artifactHeatEnv.setTimeout(0);
5284 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5285 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5286 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5287 ArtifactDefinition heatEnvPlaceholder;
5288 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5289 if (parentType != NodeTypeEnum.ResourceInstance) {
5290 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5291 .getUniqueId(), parentType, parentId);
5292 if (addHeatEnvArtifact.isRight()) {
5293 log.debug("failed to create heat env artifact on resource instance");
5294 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5296 .value(), false), "", null));
5298 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5301 heatEnvPlaceholder = artifactHeatEnv;
5302 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5303 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5305 String artifactData = buildAuditingArtifactData(heatEnvPlaceholder);
5306 ComponentTypeEnum componentType = component.getComponentType();
5307 if (parentType == NodeTypeEnum.ResourceInstance) {
5308 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5310 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType,
5311 ResourceAuditData.newBuilder().build(),
5312 ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5313 parentName, null, artifactData, null);
5314 return Either.left(heatEnvPlaceholder);
5317 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5318 if (artifact.getListHeatParameters() == null) {
5321 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5322 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5323 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5324 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5325 heatEnvParameter.setCurrentValue(null);
5326 heatEnvParameters.add(heatEnvParameter);
5328 artifactDefinition.setListHeatParameters(heatEnvParameters);
5331 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5332 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5333 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5334 String name = heatArtifact.getArtifactName();
5337 name = heatArtifact.getArtifactLabel();
5338 fileName = name + "." + envExtension;
5341 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5343 heatEnvArtifact.setArtifactName(fileName);
5346 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5347 if (null != existingEnvVersions) {
5348 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5349 if (null != prevVersion) {
5350 heatEnvArtifact.setArtifactVersion(prevVersion);
5356 * Handles Artifacts Request For Inner Component
5358 * @param artifactsToHandle
5361 * @param vfcsNewCreatedArtifacts
5364 * @param inTransaction
5367 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5368 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5370 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5371 ComponentTypeEnum componentType = component.getComponentType();
5372 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5373 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5374 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5378 for (ArtifactDefinition artifact : artifactsToHandle) {
5379 originData = buildJsonStringForCsarVfcArtifact(artifact);
5380 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5381 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5382 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5383 if (actionResult.isRight()) {
5384 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5385 .getName(), actionResult.right().value());
5386 errorWrapper.setInnerElement(actionResult.right().value());
5387 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5388 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5392 uploadedArtifacts.add(actionResult.left().value().left().value());
5394 if (errorWrapper.isEmpty()) {
5395 handleArtifactsResult = Either.left(uploadedArtifacts);
5398 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5401 catch (Exception e) {
5402 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5403 handleArtifactsResult = Either.right(responseFormat);
5404 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5406 return handleArtifactsResult;
5409 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5410 ComponentInstance componentInstance = null;
5411 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5412 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5413 if (errorWrapper.isEmpty()) {
5414 componentInstance = component.getComponentInstances()
5416 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5417 .equals(normalizedName))
5420 if (componentInstance == null) {
5421 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5423 .getValue(), component.getName()));
5424 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5427 return componentInstance;
5430 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5432 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5433 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5434 ComponentInstance componentInstance = component.getComponentInstances()
5436 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5437 .equals(normalizedName))
5440 if (componentInstance == null) {
5441 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5443 .getValue(), component.getName()));
5444 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5447 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5449 return relatedComponentComponentInstancePair;
5452 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5453 ComponentInstance componentInstance;
5454 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5455 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5456 if (errorWrapper.isEmpty()) {
5457 componentInstance = component.getComponentInstances()
5459 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
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 {} was not found for component {}", resourceInstanceName, component.getName());
5469 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5472 return relatedComponentComponentInstancePair;
5475 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5477 byte[] downloadedArtifact = null;
5478 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5479 List<ArtifactDefinition> artifactsList = null;
5480 ArtifactDefinition deploymentArtifact = null;
5481 if (artifacts != null && !artifacts.isEmpty()) {
5482 artifactsList = artifacts.values()
5484 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5485 .equals(artifactUUID))
5486 .collect(Collectors.toList());
5488 if (artifactsList == null || artifactsList.isEmpty()) {
5489 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5490 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5492 if (errorWrapper.isEmpty()) {
5493 deploymentArtifact = artifactsList.get(0);
5494 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5495 if (downloadArtifactEither.isRight()) {
5496 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5497 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5500 if (errorWrapper.isEmpty()) {
5501 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5502 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5504 return downloadedArtifact;
5507 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5508 Component component = null;
5509 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5510 if (getComponentRes.isRight()) {
5511 StorageOperationStatus status = getComponentRes.right().value();
5512 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5513 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5516 component = getComponentRes.left().value();
5521 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5522 Component component = null;
5523 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5524 if (getComponentRes.isRight()) {
5525 StorageOperationStatus status = getComponentRes.right().value();
5526 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5527 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5530 List<Component> value = getComponentRes.left().value();
5531 if (value.isEmpty()) {
5532 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5533 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5534 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5537 component = value.get(0);
5543 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5544 String artifactId = null;
5545 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5546 StorageOperationStatus storageStatus;
5547 ArtifactDefinition latestArtifact = null;
5548 List<ArtifactDefinition> artifacts = null;
5549 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5550 if (getArtifactsRes.isRight()) {
5551 storageStatus = getArtifactsRes.right().value();
5552 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5553 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5554 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5556 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5558 if (errorWrapper.isEmpty()) {
5559 artifacts = getArtifactsRes.left()
5563 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5564 .equals(artifactUUID))
5565 .collect(Collectors.toList());
5566 if (artifacts == null || artifacts.isEmpty()) {
5567 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5568 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5571 if (errorWrapper.isEmpty()) {
5572 latestArtifact = artifacts.stream().max((a1, a2) -> {
5573 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5574 if (compareRes == 0) {
5575 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5576 .getLastUpdateDate());
5580 if (latestArtifact == null) {
5581 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5582 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5585 if (errorWrapper.isEmpty()) {
5586 artifactId = latestArtifact.getUniqueId();
5591 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5593 Component component = null;
5594 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5595 if (getUserRes.isRight()) {
5596 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5599 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5601 if (errorWrapper.isEmpty()) {
5602 User modifier = getUserRes.left().value();
5603 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5604 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5605 if (checkoutRes.isRight()) {
5606 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5607 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5608 errorWrapper.setInnerElement(checkoutRes.right().value());
5611 component = checkoutRes.left().value();
5617 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
5618 if (artifact == null) {
5619 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
5620 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
5621 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
5622 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
5626 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
5627 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
5628 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
5632 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5633 Map<String, Object> json = new HashMap<>();
5634 String artifactName = artifact.getArtifactName();
5635 json.put(Constants.ARTIFACT_NAME, artifactName);
5636 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5637 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5638 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5639 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5640 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5641 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5642 return gson.toJson(json);
5646 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5647 this.nodeTemplateOperation = nodeTemplateOperation;