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 switch (operation.getArtifactOperationEnum()) {
426 if (artifactGenerationRequired(parent, artifactInfo)) {
427 return generateNotSavedArtifact(parent, artifactInfo);
429 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
431 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
433 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
434 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
435 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
436 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
437 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
438 if (needUpdateGroup && result.isLeft()) {
439 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
440 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
441 .value(), parent, componentType, componentId);
442 if (error != ActionStatus.OK) {
443 result = Either.right(componentsUtils.getResponseFormat(error));
448 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
449 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
452 if (result == null) {
453 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
454 if (needUpdateGroup && result.isLeft()) {
455 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
457 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
458 .value(), parent, componentType);
459 if (error != ActionStatus.OK) {
460 result = Either.right(componentsUtils.getResponseFormat(error));
466 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
468 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
473 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
474 List<GroupDefinition> groups = parent.getGroups();
475 if (groups != null && !groups.isEmpty()) {
476 List<GroupDataDefinition> groupToUpdate = groups.stream()
477 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
478 .contains(artifactInfo
480 .collect(Collectors.toList());
481 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
482 groupToUpdate.forEach(g -> {
483 g.getArtifacts().remove(artifactInfo.getUniqueId());
484 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
485 g.getArtifacts().add(artAfterUpdate.getUniqueId());
486 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
488 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
489 if (status.isRight()) {
490 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
491 return componentsUtils.convertFromStorageResponse(status.right().value());
495 return ActionStatus.OK;
498 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
499 List<GroupDefinition> groups = parent.getGroups();
500 if (groups != null && !groups.isEmpty()) {
501 List<GroupDataDefinition> groupToUpdate = groups.stream()
502 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
503 .contains(artifactInfoHeat
505 .collect(Collectors.toList());
506 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
507 groupToUpdate.forEach(g -> {
508 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
509 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
510 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
511 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
512 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
513 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
515 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
516 if (status.isRight()) {
517 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
518 return componentsUtils.convertFromStorageResponse(status.right().value());
522 return ActionStatus.OK;
525 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
526 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
527 List<GroupInstance> groupInstances = null;
528 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
530 .filter(ci -> ci.getUniqueId().equals(parentId))
532 if (componentInstOp.isPresent()) {
533 groupInstances = componentInstOp.get().getGroupInstances();
535 if (CollectionUtils.isNotEmpty(groupInstances)) {
536 boolean isUpdated = false;
537 for (GroupInstance groupInstance : groupInstances) {
539 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
540 .contains(artifactInfo
542 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
543 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
546 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
547 .contains(artifactInfo
548 .getArtifactUUID())) {
549 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
550 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
554 updatedGroupInstances.add(groupInstance);
558 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
559 if (status.isRight()) {
560 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
561 return componentsUtils.convertFromStorageResponse(status.right().value());
563 return ActionStatus.OK;
566 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
567 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
568 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
569 result = generateToscaArtifact(parent, artifactInfo, false, false);
572 String heatArtifactId = artifactInfo.getGeneratedFromId();
573 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
574 if (heatRes.isRight()) {
575 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
577 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
580 return Either.right(responseFormat);
582 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
583 artifactInfo.setPayloadData(generatedPayload);
584 result = Either.left(Either.left(artifactInfo));
589 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
590 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
591 convertParentType(componentType);
592 String parentId = parent.getUniqueId();
593 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
594 .getGeneratedFromId());
595 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
597 if (origMd5 != null) {
598 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
599 if (validateMd5.isRight()) {
600 ResponseFormat responseFormat = validateMd5.right().value();
601 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
602 return Either.right(responseFormat);
605 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
607 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
608 if (payloadEither.isRight()) {
609 ResponseFormat responseFormat = payloadEither.right().value();
610 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
611 return Either.right(responseFormat);
615 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
616 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
617 return Either.right(responseFormat);
623 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
624 if (lockComponent.isRight()) {
625 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
626 .value(), componentType, null);
627 return Either.right(lockComponent.right().value());
630 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
632 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
638 if (resultOp == null || resultOp.isRight()) {
639 log.debug("all changes rollback");
640 if (!inTransaction) {
645 log.debug("all changes committed");
646 if (!inTransaction) {
651 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
656 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
657 if (artifactGenerationRequired(component, csarArtifact)) {
658 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
660 if (generated.isRight()) {
661 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
664 return Either.right(generated.right().value());
666 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
669 return downloadArtifact(csarArtifact);
672 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
673 // perform all validation in common flow
674 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
675 null, parentId, containerComponentType);
676 if (result.isRight()) {
677 return Either.right(result.right().value());
679 ArtifactDefinition artifactDefinition;
680 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
681 if (insideValue.isLeft()) {
682 artifactDefinition = insideValue.left().value();
685 artifactDefinition = insideValue.right().value().getImplementationArtifact();
687 // for tosca artifacts and heat env on VF level generated on download without saving
688 if (artifactDefinition.getPayloadData() != null) {
689 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
692 return downloadArtifact(artifactDefinition);
695 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
697 // detect auditing type
698 Map<String, ArtifactDefinition> resMap = null;
699 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
704 if (userId == null) {
705 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
706 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
708 resultOp = Either.right(responseFormat);
712 // check user existence
716 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
717 if (userResult.isRight()) {
719 resultOp = Either.right(userResult.right().value());
723 userResult.left().value();
726 // 5. check service/resource existence
727 // 6. check service/resource check out
728 // 7. user is owner of checkout state
729 org.openecomp.sdc.be.model.Component component = null;
730 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
731 ComponentParametersView componentFilter = new ComponentParametersView();
732 componentFilter.disableAll();
733 componentFilter.setIgnoreArtifacts(false);
734 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
735 componentFilter.setIgnoreComponentInstances(false);
738 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
739 .findByParamName(containerComponentType), componentFilter);
741 if (validateComponent.isRight()) {
742 resultOp = Either.right(validateComponent.right().value());
745 component = validateComponent.left().value();
746 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
747 if (lockComponent.isRight()) {
749 resultOp = Either.right(lockComponent.right().value());
754 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
756 if (groupType == null) {
757 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
758 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
760 resultOp = Either.right(responseFormat);
764 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
765 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
766 if (list != null && !list.isEmpty()) {
767 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
770 resMap = new HashMap<>();
772 resultOp = Either.left(resMap);
777 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
778 .getNodeType(), groupType, componentId);
779 if (artifactsMapStatus.isRight()) {
780 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
781 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
782 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
783 resultOp = Either.right(responseFormat);
786 resMap = new HashMap<>();
787 resultOp = Either.left(resMap);
791 resMap = artifactsMapStatus.left().value();
792 resultOp = Either.left(resMap);
799 if (resultOp == null || resultOp.isRight()) {
800 log.debug("all changes rollback");
804 log.debug("all changes committed");
808 componentType = component.getComponentType();
809 NodeTypeEnum nodeType = componentType.getNodeType();
810 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
815 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
817 // check artifact existence
818 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
820 if (artifactResult.isRight()) {
821 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
822 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
823 log.debug("addArtifact - artifact {} not found", artifactId);
824 return Either.right(responseFormat);
828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
831 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
833 return Either.right(responseFormat);
837 // check artifact belong to component
838 boolean found = false;
839 switch (componentType) {
842 found = checkArtifactInComponent(component, artifactId);
844 case RESOURCE_INSTANCE:
845 found = checkArtifactInResourceInstance(component, componentId, artifactId);
851 String componentName = componentType.name().toLowerCase();
852 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
853 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
854 return Either.right(responseFormat);
856 return Either.left(artifactResult.left().value());
859 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
860 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
862 String artifactId = null;
865 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
866 if (payloadEither.isRight()) {
867 return Either.right(payloadEither.right().value());
869 byte[] decodedPayload = payloadEither.left().value();
870 convertParentType(componentType);
873 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
874 if (lockComponent.isRight()) {
875 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
876 .value(), componentType, null);
877 return Either.right(lockComponent.right().value());
880 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
883 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
888 unlockComponent(resultOp, parent, inTransaction);
895 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
896 Component parent, boolean shouldLock, boolean inTransaction) {
899 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
900 if (lockComponent.isRight()) {
901 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
902 .value(), componentType, null);
903 return Either.right(lockComponent.right().value());
906 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
909 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
914 unlockComponent(resultOp, parent, inTransaction);
921 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
922 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
924 convertParentType(componentType);
928 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
930 if (lockComponent.isRight()) {
931 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
932 .value(), componentType, null);
933 return Either.right(lockComponent.right().value());
937 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
939 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
945 unlockComponent(resultOp, parent, inTransaction);
950 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
951 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
953 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
955 if (payloadEither.isRight()) {
956 return Either.right(payloadEither.right().value());
958 byte[] decodedPayload = payloadEither.left().value();
960 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
963 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
964 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
966 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
967 if (validateMd5.isRight()) {
968 ResponseFormat responseFormat = validateMd5.right().value();
969 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
970 return Either.right(responseFormat);
974 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
975 if (validateResult.isRight()) {
976 ResponseFormat responseFormat = validateResult.right().value();
977 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
978 return Either.right(validateResult.right().value());
981 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
982 if (payloadEither.isRight()) {
983 ResponseFormat responseFormat = payloadEither.right().value();
984 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
985 log.debug("Error during handle payload");
986 return Either.right(responseFormat);
989 // validate heat parameters. this part must be after the parameters are
990 // extracted in "handlePayload"
991 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
993 if (validateAndConvertHeatParamers.isRight()) {
994 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
995 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
996 log.debug("Error during handle payload");
997 return Either.right(responseFormat);
999 return payloadEither;
1002 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1003 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1005 if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType()
1006 .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
1009 String artifactData = buildAuditingArtifactData(artifactDefinition);
1013 user.setUserId("UNKNOWN");
1015 switch (componentTypeEnum) {
1017 Resource resource = (Resource) component;
1018 if (resource == null) {
1019 // In that case, component ID should be instead of name
1020 resource = new Resource();
1021 resource.setName(componentId);
1023 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1024 ResourceAuditData.newBuilder()
1025 .artifactUuid(prevArtifactUuid)
1026 .build(), currentArtifactUuid, artifactData);
1030 Service service = (Service) component;
1031 if (service == null) {
1032 // In that case, component ID should be instead of name
1033 service = new Service();
1034 service.setName(componentId);
1036 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE,
1037 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1038 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1039 null, null, artifactData, null);
1042 case RESOURCE_INSTANCE:
1043 if (resourceInstanceName == null) {
1044 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1046 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE,
1047 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1048 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1049 resourceInstanceName, null, artifactData, null);
1056 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1057 ComponentInstance resourceInstance = component.getComponentInstances()
1059 .filter(p -> p.getUniqueId().equals(componentId))
1062 String resourceInstanceName = null;
1063 if (resourceInstance != null) {
1064 resourceInstanceName = resourceInstance.getName();
1066 return resourceInstanceName;
1069 public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
1070 Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1071 // Putting together artifact info
1072 String artifactData = buildAuditingArtifactData(artifactDefinition);
1073 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
1074 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
1075 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
1076 return auditingFields;
1081 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1082 StringBuilder sb = new StringBuilder();
1083 if (artifactDefinition != null) {
1084 sb.append(artifactDefinition.getArtifactGroupType().getType())
1087 .append(artifactDefinition.getArtifactLabel())
1090 .append(artifactDefinition.getArtifactType())
1092 .append(artifactDefinition.getArtifactName())
1094 .append(artifactDefinition.getTimeout())
1096 .append(artifactDefinition.getEsId());
1099 if (artifactDefinition.getArtifactVersion() != null) {
1101 sb.append(artifactDefinition.getArtifactVersion());
1107 if (artifactDefinition.getArtifactUUID() != null) {
1108 sb.append(artifactDefinition.getArtifactUUID());
1114 return sb.toString();
1117 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1119 if (origMd5 != null) {
1120 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1121 if (!encodeBase64Str.equals(origMd5)) {
1122 log.debug("The calculated md5 is different then the received one");
1123 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1127 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1128 log.debug("Missing md5 header during artifact create");
1129 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1132 if (payload != null && payload.length != 0) {
1133 log.debug("Cannot have payload while md5 header is missing");
1134 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1137 return Either.left(true);
1140 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1141 ComponentTypeEnum componentType, Component parentComponent) {
1143 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1144 if (artifactById.isRight()) {
1145 return Either.right(artifactById.right().value());
1147 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1149 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1150 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1151 if (validateInformationalArtifactRes.isRight()) {
1152 return Either.right(validateInformationalArtifactRes.right().value());
1154 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1155 if (validateAndSetArtifactname.isRight()) {
1156 return Either.right(validateAndSetArtifactname.right().value());
1158 if (operationName != null && interfaceName != null) {
1159 operationName = operationName.toLowerCase();
1160 interfaceName = interfaceName.toLowerCase();
1162 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1163 if (logicalNameStatus.isRight()) {
1164 return Either.right(logicalNameStatus.right().value());
1166 // This is a patch to block possibility of updating service api fields
1167 // through other artifacts flow
1169 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1170 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1171 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1174 checkCreateFields(user, artifactInfo, artifactGroupType);
1177 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1178 if (currentArtifactInfo != null) {
1179 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1182 // artifactGroupType is not allowed to be updated
1183 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1184 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1185 if (validateGroupType.isRight()) {
1186 return Either.right(validateGroupType.right().value());
1189 NodeTypeEnum parentType = convertParentType(componentType);
1191 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1193 if (isDeploymentArtifact(artifactInfo)) {
1194 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1195 if (deploymentValidationResult.isRight()) {
1196 return Either.right(deploymentValidationResult.right().value());
1200 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1203 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1204 if (descriptionResult.isRight()) {
1205 return Either.right(descriptionResult.right().value());
1208 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1209 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1210 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1211 if (validateServiceApiType.isRight()) {
1212 return Either.right(validateServiceApiType.right().value());
1214 // Change of type is not allowed and should be ignored
1216 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1218 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1219 if (validateUrl.isRight()) {
1220 return Either.right(validateUrl.right().value());
1223 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1224 if (validateUpdate.isRight()) {
1225 log.debug("serviceApi first update cnnot be without payload.");
1226 return Either.right(validateUpdate.right().value());
1230 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1231 if (validateArtifactType.isRight()) {
1232 return Either.right(validateArtifactType.right().value());
1234 if (artifactInfo.getApiUrl() != null) {
1235 artifactInfo.setApiUrl(null);
1236 log.error("Artifact URL cannot be set through this API - ignoring");
1239 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1240 artifactInfo.setServiceApi(false);
1241 log.error("Artifact service API flag cannot be changed - ignoring");
1245 return Either.left(artifactInfo);
1248 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1249 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1250 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1251 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1252 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1256 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1258 Either<ArtifactDefinition, ResponseFormat> result = null;
1259 ArtifactDefinition foundArtifact = null;
1260 if (StringUtils.isNotEmpty(artifactId)) {
1261 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1263 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1264 log.debug("Artifact {} already exist", artifactId);
1265 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1267 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1268 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1269 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1271 if (result == null) {
1272 result = Either.left(foundArtifact);
1277 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1278 ArtifactDefinition foundArtifact;
1279 if (parentComponent.getUniqueId().equals(parentId)) {
1280 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1283 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1284 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1286 return foundArtifact;
1289 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1290 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1291 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1292 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1293 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1294 if (artifactType == null) {
1295 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1296 .getArtifactType()));
1298 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1299 String artifactTypeName = artifactType.getType();
1300 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1301 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1303 .getResourceInformationalArtifacts();
1304 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1305 if (!validArtifactTypes.contains(artifactTypeName)) {
1306 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1309 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1310 .getValidForResourceTypes();
1311 if (!validResourceType.contains(parentResourceType.name())) {
1312 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1316 return validationResult;
1319 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1320 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1321 return NodeTypeEnum.Resource;
1323 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1324 return NodeTypeEnum.ResourceInstance;
1327 return NodeTypeEnum.Service;
1331 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1332 boolean shouldLock, boolean inTransaction) {
1334 NodeTypeEnum parentType = convertParentType(componentType);
1335 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1336 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1337 ArtifactDefinition foundArtifact = null;
1338 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1339 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1340 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1341 boolean isDuplicated = false;
1343 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1346 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1347 if (lockComponent.isRight()) {
1348 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1349 .value(), componentType, null);
1350 resultOp = Either.right(lockComponent.right().value());
1353 if (resultOp == null) {
1354 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1355 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1356 if (getContainerRes.isRight()) {
1357 log.debug("Failed to fetch the container component {}. ", parentId);
1358 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1360 .value()), artifactId);
1361 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1362 resultOp = Either.right(responseFormat);
1365 if (resultOp == null) {
1366 fetchedContainerComponent = getContainerRes.left().value();
1367 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1368 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1369 if (getArtifactRes.isRight()) {
1370 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1372 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1373 .value(), artifactId);
1374 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1375 resultOp = Either.right(responseFormat);
1378 foundArtifact = getArtifactRes.left().value().getLeft();
1379 esId = foundArtifact.getEsId();
1382 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1383 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1384 .getComponentType()));
1385 if (needCloneRes.isRight()) {
1386 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1387 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1389 .value()), foundArtifact.getArtifactDisplayName());
1390 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1391 resultOp = Either.right(responseFormat);
1394 boolean isNeedToDeleteArtifactFromDB = true;
1395 if (resultOp == null) {
1397 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1398 String instanceId = parentId;
1399 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1401 if (isOnlyResourceInstanceArtifact.isRight()) {
1402 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1403 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1404 .value(), foundArtifact
1405 .getArtifactDisplayName());
1406 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1407 return Either.right(responseFormat);
1409 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1412 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1415 if (updatedArtifactRes.isRight()) {
1416 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1417 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1419 .value()), foundArtifact.getArtifactDisplayName());
1420 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1421 resultOp = Either.right(responseFormat);
1424 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1428 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1429 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1430 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1431 if (cassandraStatus != CassandraOperationStatus.OK) {
1432 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1433 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1434 .getArtifactDisplayName());
1435 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1436 resultOp = Either.right(responseFormat);
1439 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1441 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1445 .getGroupInstances());
1446 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1447 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1448 if (status.isRight()) {
1449 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1450 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1452 .value()), foundArtifact.getArtifactDisplayName());
1453 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1454 resultOp = Either.right(responseFormat);
1458 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1459 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1460 if (status != StorageOperationStatus.OK) {
1461 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1462 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1463 .getArtifactDisplayName());
1464 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1465 resultOp = Either.right(responseFormat);
1468 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1469 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1471 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1472 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1473 if (status.isRight()) {
1474 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1475 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1477 .value()), foundArtifact.getArtifactDisplayName());
1478 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1479 resultOp = Either.right(responseFormat);
1483 if (resultOp == null) {
1484 resultOp = Either.left(Either.left(foundArtifact));
1485 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1491 unlockComponent(resultOp, parent, inTransaction);
1496 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1497 Either<Boolean, ActionStatus> result = Either.left(true);
1498 ComponentInstance foundInstance = null;
1499 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1501 .filter(i -> i.getUniqueId().equals(instanceId))
1503 if (!componentInstanceOpt.isPresent()) {
1504 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1507 foundInstance = componentInstanceOpt.get();
1508 String componentUid = foundInstance.getComponentUid();
1509 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1510 if (getContainerRes.isRight()) {
1511 log.debug("Failed to fetch the container component {}. ", componentUid);
1512 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1514 Component origComponent = getContainerRes.left().value();
1515 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1516 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1517 Optional<String> op = deploymentArtifacts.keySet()
1519 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1521 if (op.isPresent()) {
1522 return Either.left(false);
1525 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1526 if (artifacts != null && !artifacts.isEmpty()) {
1527 Optional<String> op = artifacts.keySet()
1529 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1531 if (op.isPresent()) {
1532 return Either.left(false);
1540 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1541 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1542 boolean isUpdated = false;
1543 if (groups != null) {
1544 for (GroupDefinition group : groups) {
1546 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1547 group.getArtifacts().remove(artifactId);
1550 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1551 .contains(foundArtifact.getArtifactUUID())) {
1552 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1556 updatedGroups.add(group);
1560 return updatedGroups;
1563 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1564 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1565 if (CollectionUtils.isNotEmpty(groupInstances)) {
1566 boolean isUpdated = false;
1567 for (GroupInstance groupInstance : groupInstances) {
1569 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1570 .contains(artifactId)) {
1571 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1574 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1575 .contains(foundArtifact
1576 .getArtifactUUID())) {
1577 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1581 updatedGroupInstances.add(groupInstance);
1585 return updatedGroupInstances;
1588 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1590 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1591 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1592 String componentId = component.getUniqueId();
1593 String instanceId = componentId.equals(parentId) ? null : parentId;
1595 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1596 resetMandatoryArtifactFields(foundArtifact);
1597 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1599 else if (cloneIsNeeded) {
1600 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1601 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1604 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1605 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1610 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1612 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1613 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1614 ComponentInstance foundInstance = null;
1615 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1616 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1618 .filter(i -> i.getUniqueId()
1621 if (!componentInstanceOpt.isPresent()) {
1622 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1625 foundInstance = componentInstanceOpt.get();
1626 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1630 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1632 if (result == null) {
1633 if (artifacts.containsKey(artifactId)) {
1634 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1637 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1643 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1644 Map<String, ArtifactDefinition> currArtifacts;
1645 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1646 currArtifacts = component.getDeploymentArtifacts()
1649 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1650 if (MapUtils.isNotEmpty(currArtifacts)) {
1651 artifacts.putAll(currArtifacts);
1654 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1655 currArtifacts = component.getArtifacts()
1658 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1659 if (MapUtils.isNotEmpty(currArtifacts)) {
1660 artifacts.putAll(currArtifacts);
1663 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1664 currArtifacts = component.getToscaArtifacts()
1667 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1668 if (MapUtils.isNotEmpty(currArtifacts)) {
1669 artifacts.putAll(currArtifacts);
1674 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1675 Map<String, ArtifactDefinition> currArtifacts;
1676 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1677 currArtifacts = instance.getDeploymentArtifacts()
1680 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1681 if (MapUtils.isNotEmpty(currArtifacts)) {
1682 artifacts.putAll(currArtifacts);
1685 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1686 currArtifacts = instance.getArtifacts()
1689 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1690 if (MapUtils.isNotEmpty(currArtifacts)) {
1691 artifacts.putAll(currArtifacts);
1696 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1697 if (fetchedArtifact != null) {
1698 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1699 fetchedArtifact.setEsId(null);
1700 fetchedArtifact.setArtifactName(null);
1701 fetchedArtifact.setDescription(null);
1702 fetchedArtifact.setApiUrl(null);
1703 fetchedArtifact.setArtifactChecksum(null);
1704 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1705 fetchedArtifact.setArtifactUUID(null);
1706 long time = System.currentTimeMillis();
1707 fetchedArtifact.setPayloadUpdateDate(time);
1708 fetchedArtifact.setHeatParameters(null);
1709 fetchedArtifact.setHeatParamsUpdateDate(null);
1713 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1714 StorageOperationStatus error = StorageOperationStatus.OK;
1715 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1716 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1717 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1722 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1724 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1726 if (artifactById.isRight()) {
1727 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1728 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1729 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1730 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1731 return Either.right(responseFormat);
1733 ArtifactDefinition artifactDefinition = artifactById.left().value();
1734 if (artifactDefinition == null) {
1735 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1736 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1737 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1738 return Either.right(responseFormat);
1741 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1742 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1743 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1744 return Either.left(insideEither);
1747 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1748 ComponentTypeEnum componentType) {
1750 String artifactLabel = artifactInfo.getArtifactLabel();
1751 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1753 BeEcompErrorManager.getInstance()
1754 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1755 log.debug("missing artifact logical name for component {}", componentId);
1756 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1758 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1760 if (operationName != null) {
1761 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1762 log.debug("artifact label cannot be set {}", artifactLabel);
1763 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1766 artifactLabel = operationName;
1769 String displayName = artifactInfo.getArtifactDisplayName();
1770 if (displayName == null || displayName.isEmpty()) {
1771 displayName = artifactLabel;
1773 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1774 artifactInfo.setArtifactDisplayName(displayName);
1776 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1777 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1778 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1780 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1782 if (artifactLabel.isEmpty()) {
1783 log.debug("missing normalized artifact logical name for component {}", componentId);
1784 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1787 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1788 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1789 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1790 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1792 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1793 log.debug("Non unique Artifact label : {}", artifactLabel);
1794 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1797 artifactInfo.setArtifactLabel(artifactLabel);
1799 return Either.left(ActionStatus.OK);
1802 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1803 boolean isUnique = true;
1804 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1805 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1806 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1809 artifacts = artifactToscaOperation.getArtifacts(componentId);
1812 if (artifacts.isLeft()) {
1813 for (String label : artifacts.left().value().keySet()) {
1814 if (label.equals(artifactLabel)) {
1820 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1821 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1822 .getAllInterfacesOfResource(componentId, true, true);
1823 if (allInterfacesOfResource.isLeft()) {
1824 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1825 for (Operation operation : interace.getOperationsMap().values()) {
1826 if (operation.getImplementation() != null && operation.getImplementation()
1828 .equals(artifactLabel)) {
1839 // ***************************************************************
1841 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1842 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1843 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1844 Either<ArtifactDefinition, Operation> insideEither = null;
1845 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1846 String instanceId = null;
1847 String instanceName = null;
1848 if (foundInstance != null) {
1849 instanceId = foundInstance.getUniqueId();
1850 instanceName = foundInstance.getName();
1852 boolean isLeft = false;
1853 String artifactUniqueId = null;
1854 StorageOperationStatus error = null;
1855 // information/deployment/api aritfacts
1856 log.trace("Try to create entry on graph");
1857 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1858 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1859 .getUniqueId(), nodeType, true, instanceId);
1861 isLeft = result.isLeft();
1863 artifactUniqueId = result.left().value().getUniqueId();
1864 result.left().value();
1866 insideEither = Either.left(result.left().value());
1867 resultOp = Either.left(insideEither);
1869 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1870 if (error != StorageOperationStatus.OK) {
1876 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1877 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1881 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1882 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1883 .getArtifactDisplayName());
1884 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1885 resultOp = Either.right(responseFormat);
1891 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1892 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1894 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1895 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1896 Either<ArtifactDefinition, Operation> insideEither = null;
1897 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1898 String instanceId = null;
1899 String instanceName = null;
1900 if (foundInstance != null) {
1901 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1902 log.debug("Failed to create artifact, already exists");
1903 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1904 .getArtifactLabel());
1905 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1907 resultOp = Either.right(responseFormat);
1911 instanceId = foundInstance.getUniqueId();
1912 instanceName = foundInstance.getName();
1914 if (artifactData == null) {
1915 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1916 log.debug("Failed to create artifact object for ES.");
1917 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1918 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1919 resultOp = Either.right(responseFormat);
1923 // set on graph object id of artifact in ES!
1924 artifactInfo.setEsId(artifactData.getId());
1926 boolean isLeft = false;
1927 String artifactUniqueId = null;
1928 StorageOperationStatus error = null;
1929 if (interfaceType != null && operationName != null) {
1930 // lifecycle artifact
1931 Operation operation = convertToOperation(artifactInfo, operationName);
1933 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1935 isLeft = result.isLeft();
1937 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1938 result.left().value().getImplementation();
1940 insideEither = Either.right(result.left().value());
1941 resultOp = Either.left(insideEither);
1944 error = result.right().value();
1948 // information/deployment/api aritfacts
1949 log.trace("Try to create entry on graph");
1950 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1951 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1952 .getUniqueId(), nodeType, true, instanceId);
1954 isLeft = result.isLeft();
1956 artifactUniqueId = result.left().value().getUniqueId();
1957 artifactData.setId(result.left().value().getEsId());
1958 insideEither = Either.left(result.left().value());
1959 resultOp = Either.left(insideEither);
1961 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1962 if (error != StorageOperationStatus.OK) {
1968 error = result.right().value();
1972 boolean res = saveArtifacts(artifactData, parentId);
1975 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1977 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1978 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1982 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1983 log.debug("Failed to save the artifact.");
1984 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1985 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1987 resultOp = Either.right(responseFormat);
1992 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1993 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1994 .getArtifactDisplayName());
1995 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1996 resultOp = Either.right(responseFormat);
2002 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2003 ComponentInstance foundInstance = null;
2004 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2005 foundInstance = containerComponent.getComponentInstances()
2007 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2011 return foundInstance;
2014 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2016 Either<Boolean, ResponseFormat> result = Either.left(true);
2017 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
2019 validateArtifactTypeExists(responseWrapper, artifactInfo);
2021 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2023 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2025 if (responseWrapper.isEmpty()) {
2026 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2029 // Common code for all types
2030 // not allowed to change artifactType
2031 if (responseWrapper.isEmpty() && !isCreate) {
2032 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2033 if (validateServiceApiType.isRight()) {
2034 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2037 if (responseWrapper.isEmpty()) {
2038 if (parentType.equals(NodeTypeEnum.Resource)) {
2039 Resource resource = (Resource) parentComponent;
2040 ResourceTypeEnum resourceType = resource.getResourceType();
2041 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2042 if (config == null) {
2043 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2044 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2045 .getArtifactType()));
2048 List<String> myList = config.getValidForResourceTypes();
2049 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2050 if (either.isRight()) {
2051 responseWrapper.setInnerElement(either.right().value());
2056 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2059 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2060 String artifactName = artifactInfo.getArtifactName();
2061 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2062 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2066 if (responseWrapper.isEmpty()) {
2067 switch (artifactType) {
2071 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2074 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2075 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2077 case DCAE_INVENTORY_TOSCA:
2078 case DCAE_INVENTORY_JSON:
2079 case DCAE_INVENTORY_POLICY:
2080 // Validation is done in handle payload.
2081 case DCAE_INVENTORY_DOC:
2082 case DCAE_INVENTORY_BLUEPRINT:
2083 case DCAE_INVENTORY_EVENT:
2084 // No specific validation
2086 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2092 if (!responseWrapper.isEmpty()) {
2093 result = Either.right(responseWrapper.getInnerElement());
2098 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2099 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2100 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2101 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2102 .getArtifactType());
2103 responseWrapper.setInnerElement(responseFormat);
2104 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2108 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2109 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2110 if (parentType.equals(NodeTypeEnum.Resource)) {
2111 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2113 .getResourceDeploymentArtifacts();
2115 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2116 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2118 .getResourceInstanceDeploymentArtifacts();
2121 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2123 .getServiceDeploymentArtifacts();
2125 return resourceDeploymentArtifacts;
2128 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2129 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2130 if (artifactType == null) {
2131 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2132 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2133 .getArtifactType());
2134 responseWrapper.setInnerElement(responseFormat);
2135 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2139 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2140 ArtifactTypeConfig retConfig = null;
2141 String fileType = artifactType.getType();
2142 if (parentType.equals(NodeTypeEnum.Resource)) {
2143 retConfig = ConfigurationManager.getConfigurationManager()
2145 .getResourceDeploymentArtifacts()
2148 else if (parentType.equals(NodeTypeEnum.Service)) {
2149 retConfig = ConfigurationManager.getConfigurationManager()
2151 .getServiceDeploymentArtifacts()
2154 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2155 retConfig = ConfigurationManager.getConfigurationManager()
2157 .getResourceInstanceDeploymentArtifacts()
2163 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2164 // extract heat parameters
2165 if (artifactInfo.getPayloadData() != null) {
2166 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2167 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2168 .getArtifactType());
2169 if (heatParameters.isRight() && (!heatParameters.right()
2171 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2172 log.info("failed to parse heat parameters ");
2173 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2174 .getArtifactType());
2175 return Either.right(responseFormat);
2177 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2178 artifactInfo.setListHeatParameters(heatParameters.left().value());
2181 return Either.left(true);
2186 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2187 String fileType = artifactType.getType();
2188 List<String> acceptedTypes = null;
2189 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2190 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2191 log.debug("parent type of artifact can be either resource or service");
2192 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2196 if (deploymentAcceptedTypes == null) {
2197 log.debug("parent type of artifact can be either resource or service");
2198 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2199 .getArtifactType()));
2203 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2206 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2209 String artifactName = artifactInfo.getArtifactName();
2210 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2211 // Pavel - File extension validation is case-insensitive - Ella,
2213 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2214 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2215 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2220 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2222 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
2223 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
2224 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2226 if (errorWrapper.isEmpty()) {
2227 validateValidYaml(errorWrapper, artifactInfo);
2230 if (errorWrapper.isEmpty()) {
2231 // Validate Heat Exist
2232 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2233 .getComponentType());
2236 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2237 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2240 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2241 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2245 Either<Boolean, ResponseFormat> eitherResponse;
2246 if (errorWrapper.isEmpty()) {
2247 eitherResponse = Either.left(true);
2250 eitherResponse = Either.right(errorWrapper.getInnerElement());
2252 return eitherResponse;
2255 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2256 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2257 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2258 if (fillArtifactPayload.isRight()) {
2259 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2260 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2264 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2268 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2269 Either<Boolean, ResponseFormat> result = Either.left(true);
2270 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2272 if (eitherArtifactData.isLeft()) {
2273 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2274 data = Base64.encodeBase64(data);
2275 payloadWrapper.setInnerElement(data);
2278 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2281 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2282 result = Either.right(responseFormat);
2288 @SuppressWarnings("unchecked")
2289 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2290 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2291 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2292 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2293 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2295 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2296 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2297 if (eitherHeatEnvProperties.isRight()) {
2298 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2299 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2300 errorWrapper.setInnerElement(responseFormat);
2301 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2303 else if (eitherHeatProperties.isRight()) {
2304 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2305 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2306 .getArtifactName(), heatArtifact.getArtifactName());
2307 errorWrapper.setInnerElement(responseFormat);
2308 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2309 .getArtifactName());
2312 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2313 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2314 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2315 if (!heatEnvPropertiesKeys.isEmpty()) {
2316 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2317 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2318 .getArtifactName(), heatArtifact.getArtifactName());
2319 errorWrapper.setInnerElement(responseFormat);
2324 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2325 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2326 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2328 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2329 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2330 .getArtifactType());
2331 errorWrapper.setInnerElement(responseFormat);
2332 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2336 private boolean isValidXml(byte[] xmlToParse) {
2337 boolean isXmlValid = true;
2339 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2340 setFeatures(reader);
2341 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2343 catch (ParserConfigurationException | IOException | SAXException e) {
2344 log.debug("Xml is invalid : {}", e.getMessage(), e);
2350 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2352 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2353 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2355 catch (SAXNotRecognizedException e) {
2356 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2360 private boolean isValidJson(byte[] jsonToParse) {
2361 String parsed = new String(jsonToParse);
2363 gson.fromJson(parsed, Object.class);
2365 catch (Exception e) {
2366 log.debug("Json is invalid : {}", e.getMessage(), e);
2372 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2373 boolean artifactNameFound = false;
2374 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2377 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2378 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2380 if (artifactNameFound) {
2381 String parentName = parentComponent.getName();
2382 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2383 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2384 .name(), parentName, artifactName);
2386 errorWrapper.setInnerElement(responseFormat);
2387 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2392 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2393 ComponentTypeEnum componentType) {
2394 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2395 if (res.isRight()) {
2396 ResponseFormat responseFormat;
2397 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2398 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2401 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2403 errorWrapper.setInnerElement(responseFormat);
2406 ArtifactDefinition heatArtifact = res.left().value();
2407 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2410 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2411 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2412 // timeout > 0 for HEAT artifacts
2413 Integer timeout = artifactInfo.getTimeout();
2414 if (timeout == null) {
2415 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2416 artifactInfo.setTimeout(defaultTimeout);
2417 // HEAT artifact but timeout is invalid
2419 else if (timeout < 1) {
2420 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2423 // US649856 - Allow several HEAT files on Resource
2424 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2425 return Either.left(true);
2428 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2429 String listToString = (typeList != null) ? typeList.toString() : "";
2430 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2431 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2432 .getArtifactName(), listToString, resourceType.getValue());
2433 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2434 String resourceTypeName = resourceType.name();
2435 if (typeList != null && typeList.contains(resourceTypeName)) {
2436 either = Either.left(true);
2441 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2442 if (artifactInfo.getHeatParameters() != null) {
2443 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2444 String parameterType = heatParam.getType();
2445 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2446 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2447 if (heatParameterType == null) {
2448 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2450 return Either.right(responseFormat);
2453 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2454 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2455 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2456 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2457 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2458 .getType(), heatParam.getName());
2459 return Either.right(responseFormat);
2463 return Either.left(artifactInfo);
2466 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2467 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2468 if (parentComponent.getDeploymentArtifacts() != null) {
2469 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2470 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2471 if (getRI.isRight()) {
2472 return deploymentArtifacts;
2474 ComponentInstance ri = getRI.left().value();
2475 if (ri.getDeploymentArtifacts() != null) {
2476 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2479 else if (parentComponent.getDeploymentArtifacts() != null) {
2480 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2483 return deploymentArtifacts;
2486 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2487 // on create if null add informational to current
2488 if (artifactInfo.getArtifactGroupType() == null) {
2489 artifactInfo.setArtifactGroupType(type);
2491 if (artifactInfo.getUniqueId() != null) {
2492 log.error("artifact uniqid cannot be set ignoring");
2494 artifactInfo.setUniqueId(null);
2496 if (artifactInfo.getArtifactRef() != null) {
2497 log.error("artifact ref cannot be set ignoring");
2499 artifactInfo.setArtifactRef(null);
2501 if (artifactInfo.getArtifactRepository() != null) {
2502 log.error("artifact repository cannot be set ignoring");
2504 artifactInfo.setArtifactRepository(null);
2506 if (artifactInfo.getUserIdCreator() != null) {
2507 log.error("creator uuid cannot be set ignoring");
2509 artifactInfo.setArtifactCreator(user.getUserId());
2511 if (artifactInfo.getUserIdLastUpdater() != null) {
2512 log.error("userId of last updater cannot be set ignoring");
2514 artifactInfo.setUserIdLastUpdater(user.getUserId());
2516 if (artifactInfo.getCreatorFullName() != null) {
2517 log.error("creator Full name cannot be set ignoring");
2519 String fullName = user.getFirstName() + " " + user.getLastName();
2520 artifactInfo.setUpdaterFullName(fullName);
2522 if (artifactInfo.getUpdaterFullName() != null) {
2523 log.error("updater Full name cannot be set ignoring");
2525 artifactInfo.setUpdaterFullName(fullName);
2527 if (artifactInfo.getCreationDate() != null) {
2528 log.error("Creation Date cannot be set ignoring");
2530 long time = System.currentTimeMillis();
2531 artifactInfo.setCreationDate(time);
2533 if (artifactInfo.getLastUpdateDate() != null) {
2534 log.error("Last Update Date cannot be set ignoring");
2536 artifactInfo.setLastUpdateDate(time);
2538 if (artifactInfo.getEsId() != null) {
2539 log.error("es id cannot be set ignoring");
2541 artifactInfo.setEsId(null);
2546 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2547 String id = artifactId;
2548 if (artifactId == null || artifactId.isEmpty()) {
2549 String uniqueId = null;
2550 if (interfaceName != null && operationName != null) {
2551 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2552 .getArtifactLabel());
2555 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2557 artifactInfo.setUniqueId(uniqueId);
2558 artifactInfo.setEsId(uniqueId);
2562 artifactInfo.setUniqueId(artifactId);
2563 artifactInfo.setEsId(artifactId);
2568 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2569 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2570 BeEcompErrorManager.getInstance()
2571 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2572 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2573 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2576 boolean artifactTypeExist = false;
2577 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2578 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2580 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2581 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2585 allArtifactTypes = elementOperation.getAllArtifactTypes();
2587 if (allArtifactTypes.isRight()) {
2588 BeEcompErrorManager.getInstance()
2589 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2593 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2595 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2598 for (ArtifactType type : allArtifactTypes.left().value()) {
2599 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2600 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2601 artifactTypeExist = true;
2606 if (!artifactTypeExist) {
2607 BeEcompErrorManager.getInstance()
2608 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2609 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2610 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2611 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2612 .getArtifactType()));
2615 return Either.left(ActionStatus.OK);
2618 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2620 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2621 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2623 if (parentType.equals(NodeTypeEnum.Service)) {
2624 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2626 .getServiceDeploymentArtifacts();
2628 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2629 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2631 .getResourceInstanceDeploymentArtifacts();
2634 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2636 .getResourceDeploymentArtifacts();
2638 if (deploymentArtifacts != null) {
2639 for (String artifactType : deploymentArtifacts.keySet()) {
2640 ArtifactType artifactT = new ArtifactType();
2641 artifactT.setName(artifactType);
2642 artifactTypes.add(artifactT);
2644 return Either.left(artifactTypes);
2647 return Either.right(ActionStatus.GENERAL_ERROR);
2652 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2653 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2654 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2656 return Either.left(true);
2660 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2661 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2662 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2665 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2666 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2667 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2669 artifactInfo.setArtifactName(normalizeFileName);
2671 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2672 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2675 return Either.left(true);
2678 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2679 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2680 log.info("artifact type is missing operation ignored");
2681 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2684 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2685 log.info("artifact type cannot be changed operation ignored");
2686 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2688 return Either.left(true);
2691 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2692 if (artifactInfo.getArtifactGroupType() == null) {
2693 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2696 else if (!currentArtifact.getArtifactGroupType()
2698 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2699 log.info("artifact group type cannot be changed. operation failed");
2700 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2702 return Either.left(artifactInfo);
2705 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2707 // on update if null add informational to current
2708 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2709 currentArtifact.setArtifactGroupType(type);
2712 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2713 log.error("artifact uniqid cannot be set ignoring");
2715 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2717 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2718 .equals(artifactInfo.getArtifactRef())) {
2719 log.error("artifact ref cannot be set ignoring");
2721 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2723 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2724 .equals(artifactInfo.getArtifactRepository())) {
2725 log.error("artifact repository cannot be set ignoring");
2727 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2729 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2730 .equals(artifactInfo.getUserIdCreator())) {
2731 log.error("creator uuid cannot be set ignoring");
2733 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2735 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2736 .equals(artifactInfo.getArtifactCreator())) {
2737 log.error("artifact creator cannot be set ignoring");
2739 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2741 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2742 .equals(artifactInfo.getUserIdLastUpdater())) {
2743 log.error("userId of last updater cannot be set ignoring");
2745 artifactInfo.setUserIdLastUpdater(user.getUserId());
2747 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2748 .equals(artifactInfo.getCreatorFullName())) {
2749 log.error("creator Full name cannot be set ignoring");
2751 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2753 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2754 .equals(artifactInfo.getUpdaterFullName())) {
2755 log.error("updater Full name cannot be set ignoring");
2757 String fullName = user.getFirstName() + " " + user.getLastName();
2758 artifactInfo.setUpdaterFullName(fullName);
2760 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2761 .equals(artifactInfo.getCreationDate())) {
2762 log.error("Creation Date cannot be set ignoring");
2764 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2766 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2767 .equals(artifactInfo.getLastUpdateDate())) {
2768 log.error("Last Update Date cannot be set ignoring");
2770 long time = System.currentTimeMillis();
2771 artifactInfo.setLastUpdateDate(time);
2773 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2774 log.error("es id cannot be set ignoring");
2776 artifactInfo.setEsId(currentArtifact.getUniqueId());
2778 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2779 .equals(artifactInfo.getArtifactDisplayName())) {
2780 log.error(" Artifact Display Name cannot be set ignoring");
2782 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2784 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2785 .equals(artifactInfo.getServiceApi())) {
2786 log.debug("serviceApi cannot be set. ignoring.");
2788 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2790 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2791 .equals(artifactInfo.getArtifactGroupType())) {
2792 log.debug("artifact group cannot be set. ignoring.");
2794 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2796 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2798 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2799 .isEmpty() && !currentArtifact.getArtifactUUID()
2800 .equals(artifactInfo.getArtifactUUID())) {
2801 log.debug("artifact UUID cannot be set. ignoring.");
2803 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2805 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2806 .getHeatParameters()
2807 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2808 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2812 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2814 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2815 for (HeatParameterDefinition parameter : heatParameters) {
2816 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2818 if (currentParam != null) {
2820 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2821 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2822 parameter.setName(currentParam.getName());
2824 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2825 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2826 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2827 parameter.setDefaultValue(currentParam.getDefaultValue());
2829 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2830 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2831 parameter.setType(currentParam.getType());
2833 if (parameter.getDescription() != null && !parameter.getDescription()
2834 .equalsIgnoreCase(currentParam.getDescription())) {
2835 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2836 parameter.setDescription(currentParam.getDescription());
2839 // check and set current value
2840 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2841 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2842 parameter.setCurrentValue(currentParam.getDefaultValue());
2848 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2850 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2851 for (HeatParameterDefinition param : currentParameters) {
2852 currentParamsMap.put(param.getUniqueId(), param);
2854 return currentParamsMap;
2857 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2858 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2859 log.debug("Artifact url cannot be empty.");
2860 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2862 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2864 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2865 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2867 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2868 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2871 return Either.left(true);
2874 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2875 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2876 log.debug("Artifact description cannot be empty.");
2877 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2879 String description = artifactInfo.getDescription();
2880 description = ValidationUtils.removeNoneUtf8Chars(description);
2881 description = ValidationUtils.normaliseWhitespace(description);
2882 description = ValidationUtils.stripOctets(description);
2883 description = ValidationUtils.removeHtmlTagsOnly(description);
2884 if (!ValidationUtils.validateIsEnglish(description)) {
2885 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2887 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2888 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2889 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2891 artifactInfo.setDescription(description);
2892 return Either.left(true);
2895 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2896 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2897 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2898 String prevArtifactId = null;
2899 String currArtifactId = artifactId;
2901 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2902 Either<ArtifactDefinition, Operation> insideEither = null;
2904 log.trace("Try to update entry on graph");
2905 String artifactUniqueId = null;
2906 ArtifactDefinition artifactDefinition = artifactInfo;
2907 StorageOperationStatus error;
2910 if (interfaceType == null || operationUuid == null) {
2911 log.debug("Entity on graph is updated. Update artifact in ES");
2913 // Changing previous and current artifactId for auditing
2914 prevArtifactId = currArtifactId;
2915 currArtifactId = artifactDefinition.getUniqueId();
2918 if (decodedPayload == null) {
2919 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2920 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2922 if (artifactFromCassandra.isRight()) {
2923 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2924 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2926 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2927 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2928 resultOp = Either.right(responseFormat);
2931 // clone data to new artifact
2932 artifactData.setData(artifactFromCassandra.left().value().getData());
2933 artifactData.setId(artifactFromCassandra.left().value().getId());
2936 if (artifactDefinition.getEsId() == null) {
2937 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2938 artifactData.setId(artifactDefinition.getUniqueId());
2942 NodeTypeEnum convertParentType = convertParentType(componentType);
2943 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
2944 .getUniqueId(), artifactId, convertParentType, parentId);
2945 isLeft = result.isLeft();
2947 artifactUniqueId = result.left().value().getUniqueId();
2948 artifactDefinition = result.left().value();
2949 String artifactType = artifactInfo.getArtifactType();
2950 if (NodeTypeEnum.Resource == convertParentType
2951 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
2952 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
2953 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
2954 && !artifactUniqueId.equals(artifactId)) {
2955 // need to update the generated id in heat env
2956 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2957 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
2959 .filter(a -> a.getValue()
2960 .getGeneratedFromId() != null && a
2962 .getGeneratedFromId()
2963 .equals(artifactId))
2965 if (findFirst.isPresent()) {
2966 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2967 artifactEnvInfo.setArtifactChecksum(null);
2968 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2971 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2973 insideEither = Either.left(result.left().value());
2974 resultOp = Either.left(insideEither);
2975 if (error != StorageOperationStatus.OK) {
2980 error = result.right().value();
2984 // create new entry in ES
2986 if (artifactData.getData() != null) {
2987 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
2988 artifactData.setId(artifactDefinition.getEsId());
2990 res = saveArtifacts(artifactData, parentId);
2996 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2997 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2998 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3000 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3001 log.debug("Failed to save the artifact.");
3002 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3003 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3004 resultOp = Either.right(responseFormat);
3007 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3008 decodedPayload, componentType, auditingAction, operationUuid, artifactData, prevArtifactId,
3009 currArtifactId, artifactDefinition);
3015 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3016 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3017 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction,
3018 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3019 ArtifactDefinition artifactDefinition) {
3020 StorageOperationStatus error;
3021 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3022 if (decodedPayload == null) {
3023 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3024 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3026 if (artifactFromCassandra.isRight()) {
3027 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3028 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3030 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3031 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3032 resultOp = Either.right(responseFormat);
3035 // clone data to new artifact
3036 artifactData.setData(artifactFromCassandra.left().value().getData());
3037 artifactData.setId(artifactFromCassandra.left().value().getId());
3039 // todo if not exist(first time)
3043 if (artifactDefinition.getEsId() == null) {
3044 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3045 artifactData.setId(artifactDefinition.getUniqueId());
3048 NodeTypeEnum convertParentType = convertParentType(componentType);
3049 // fetch the resource from storage
3050 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
3051 toscaOperationFacade.getToscaElement(parentId);
3052 if (resourceStorageOperationStatusEither.isRight()) {
3053 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
3054 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
3055 return Either.right(componentsUtils
3056 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
3058 Resource storedResource = resourceStorageOperationStatusEither.left().value();
3060 String interfaceToscaName = InterfaceUtils.createInterfaceToscaResourceName(
3061 storedResource.getName());
3062 //fetch the interface from storage
3063 Optional<InterfaceDefinition> interfaceDefinition = storedResource.getInterfaces().values()
3065 .filter(interfaceDef -> interfaceDef.getToscaResourceName()
3066 .equals(interfaceToscaName))
3068 if (!interfaceDefinition.isPresent()) {
3069 log.debug("Failed to get resource interface for resource Id {}", parentId);
3070 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3071 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3072 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3073 currArtifactId, responseFormat, componentType, null);
3074 return Either.right(responseFormat);
3077 //fetch the operation from storage
3078 InterfaceDefinition gotInterface = interfaceDefinition.get();
3079 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
3080 Optional<Operation> optionalOperation = operationsMap.values()
3082 .filter(o -> o.getUniqueId().equals(operationUuid))
3084 if (!optionalOperation.isPresent()) {
3085 log.debug("Failed to get resource interface operation for resource Id {} " +
3086 " and operationId {}", parentId, operationUuid);
3087 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3088 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3089 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3090 currArtifactId, responseFormat, componentType, null);
3091 return Either.right(responseFormat);
3094 Operation operation = optionalOperation.get();
3095 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
3096 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
3097 implementationArtifact.setDescription(artifactInfo.getDescription());
3098 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
3099 operation.setImplementation(implementationArtifact);
3100 gotInterface.setOperationsMap(operationsMap);
3101 Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
3102 interfaceOperation.updateInterface(storedResource.getUniqueId(), gotInterface);
3103 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
3104 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
3105 ActionStatus actionStatus =
3106 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
3107 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3110 String uniqueId = implementationArtifact.getUniqueId();
3111 artifactData.setId(uniqueId);
3112 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3113 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3114 log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
3115 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3116 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3117 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3119 return Either.left(Either.left(implementationArtifact));
3122 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3123 log.trace("Starting payload handling");
3124 byte[] payload = artifactInfo.getPayloadData();
3125 byte[] decodedPayload = null;
3127 if (payload != null && payload.length != 0) {
3128 // the generated artifacts were already decoded by the handler
3129 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3130 if (decodedPayload.length == 0) {
3131 log.debug("Failed to decode the payload.");
3132 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3133 return Either.right(responseFormat);
3136 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3137 artifactInfo.setArtifactChecksum(checkSum);
3138 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3140 // Specific payload validations of different types
3141 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3142 if (isDeploymentArtifact(artifactInfo)) {
3143 log.trace("Starting deployment artifacts payload validation");
3144 String artifactType = artifactInfo.getArtifactType();
3145 if (ArtifactTypeEnum.HEAT.getType()
3146 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3147 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3149 .equalsIgnoreCase(artifactType)
3150 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3151 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3152 if (isValidPayload.isLeft()) {
3153 isValidPayload = extractHeatParameters(artifactInfo);
3156 else if (ArtifactTypeEnum.YANG_XML.getType()
3157 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3158 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3160 .equalsIgnoreCase(artifactType)
3161 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3162 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3164 .equalsIgnoreCase(artifactType)
3165 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3166 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3168 .equalsIgnoreCase(artifactType)) {
3169 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3171 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3172 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3174 .equalsIgnoreCase(artifactType)
3175 || ArtifactTypeEnum.VES_EVENTS.getType()
3176 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3178 .equalsIgnoreCase(artifactType)) {
3179 String artifactFileName = artifactInfo.getArtifactName();
3180 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3181 switch (fileExtension) {
3183 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3186 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3190 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3197 if (isValidPayload.isRight()) {
3198 ResponseFormat responseFormat = isValidPayload.right().value();
3199 return Either.right(responseFormat);
3202 } // null/empty payload is normal if called from metadata update ONLY.
3203 // The validation of whether this is metadata/payload update case is
3204 // currently done separately
3206 if (!isArtifactMetadataUpdate) {
3207 log.debug("Payload is missing.");
3208 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3209 return Either.right(responseFormat);
3212 log.trace("Ended payload handling");
3213 return Either.left(decodedPayload);
3216 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3217 // Basic YAML validation
3218 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3219 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3220 log.debug("Invalid YAML format");
3221 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3222 return Either.right(responseFormat);
3224 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3225 // HEAT specific YAML validation
3226 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3227 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3228 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3229 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3230 return Either.right(responseFormat);
3234 return Either.left(true);
3237 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3238 Either<Boolean, ResponseFormat> res = Either.left(true);
3239 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3240 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3241 log.debug("Invalid YAML format");
3242 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3243 res = Either.right(responseFormat);
3249 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3250 boolean isXmlValid = isValidXml(payload);
3252 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3253 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3254 log.debug("Invalid XML content");
3255 return Either.right(responseFormat);
3257 return Either.left(true);
3260 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3261 boolean isJsonValid = isValidJson(payload);
3263 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3264 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3265 log.debug("Invalid JSON content");
3266 return Either.right(responseFormat);
3268 return Either.left(true);
3271 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3272 boolean inTransaction) {
3273 User user = new User();
3274 user.setUserId(userUserId);
3275 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3276 if (parent.isRight()) {
3277 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3280 return Either.right(responseFormat);
3282 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3285 false, inTransaction);
3286 if (handleDelete.isRight()) {
3287 return Either.right(handleDelete.right().value());
3289 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3290 return Either.left(result.right().value());
3294 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3295 Operation op = new Operation();
3296 long time = System.currentTimeMillis();
3297 op.setCreationDate(time);
3299 String artifactName = artifactInfo.getArtifactName();
3300 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3302 op.setImplementation(artifactInfo);
3303 op.setLastUpdateDate(time);
3307 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3308 String newArtifactName = operationName + "_" + artifactName;
3309 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3310 return newArtifactName;
3314 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3316 // General validation
3317 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3318 log.debug("One of the function parameteres is null");
3319 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3322 // Normalizing artifact name
3323 artifactName = ValidationUtils.normalizeFileName(artifactName);
3325 // Resource validation
3326 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3327 if (validateResourceNameAndVersion.isRight()) {
3328 return Either.right(validateResourceNameAndVersion.right().value());
3331 Resource resource = validateResourceNameAndVersion.left().value();
3332 String resourceId = resource.getUniqueId();
3334 // Service validation
3335 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3336 if (validateServiceNameAndVersion.isRight()) {
3337 return Either.right(validateServiceNameAndVersion.right().value());
3340 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3341 if (artifacts == null || artifacts.isEmpty()) {
3342 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3343 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3346 ArtifactDefinition deploymentArtifact = null;
3348 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3349 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3350 .equals(artifactName)) {
3351 log.debug("Found deployment artifact {}", artifactName);
3352 deploymentArtifact = artifactDefinition;
3357 if (deploymentArtifact == null) {
3358 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3359 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3362 // Downloading the artifact
3363 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3364 if (downloadArtifactEither.isRight()) {
3365 log.debug("Download artifact {} failed", artifactName);
3366 return Either.right(downloadArtifactEither.right().value());
3368 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3369 return Either.left(downloadArtifactEither.left().value().getRight());
3373 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3375 // General validation
3376 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3377 log.debug("One of the function parameteres is null");
3378 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3381 // Normalizing artifact name
3382 artifactName = ValidationUtils.normalizeFileName(artifactName);
3384 // Service validation
3385 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3386 if (validateServiceNameAndVersion.isRight()) {
3387 return Either.right(validateServiceNameAndVersion.right().value());
3390 Service service = validateServiceNameAndVersion.left().value();
3392 // ResourceInstance validation
3393 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3394 if (validateResourceInstance.isRight()) {
3395 return Either.right(validateResourceInstance.right().value());
3398 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3400 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3402 final String finalArtifactName = artifactName;
3403 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3405 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3407 .anyMatch(filterArtifactByName);
3408 ArtifactDefinition deployableArtifact;
3410 if (!hasDeploymentArtifacts) {
3411 log.debug("Deployment artifact with name {} not found", artifactName);
3412 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3415 log.debug("Found deployment artifact {}", artifactName);
3416 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3417 // Downloading the artifact
3418 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3420 if (downloadArtifactEither.isRight()) {
3421 log.debug("Download artifact {} failed", artifactName);
3422 return Either.right(downloadArtifactEither.right().value());
3424 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3425 return Either.left(downloadArtifactEither.left().value().getRight());
3428 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3430 List<ComponentInstance> riList = service.getComponentInstances();
3431 for (ComponentInstance ri : riList) {
3432 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3433 return Either.left(ri);
3437 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3440 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3442 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3443 if (serviceListBySystemName.isRight()) {
3444 log.debug("Couldn't fetch any service with name {}", serviceName);
3445 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3447 .value(), ComponentTypeEnum.SERVICE), serviceName));
3449 List<Service> serviceList = serviceListBySystemName.left().value();
3450 if (serviceList == null || serviceList.isEmpty()) {
3451 log.debug("Couldn't fetch any service with name {}", serviceName);
3452 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3455 Service foundService = null;
3456 for (Service service : serviceList) {
3457 if (service.getVersion().equals(serviceVersion)) {
3458 log.trace("Found service with version {}", serviceVersion);
3459 foundService = service;
3464 if (foundService == null) {
3465 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3466 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3467 .getValue(), serviceVersion));
3469 return Either.left(foundService);
3472 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3474 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3475 if (resourceListBySystemName.isRight()) {
3476 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3477 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3479 .value()), resourceName));
3481 return Either.left(resourceListBySystemName.left().value());
3484 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3486 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3487 if (serviceName == null || serviceVersion == null || artifactName == null) {
3488 log.debug("One of the function parameteres is null");
3489 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3492 // Normalizing artifact name
3493 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3495 // Service validation
3496 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3497 if (validateServiceNameAndVersion.isRight()) {
3498 return Either.right(validateServiceNameAndVersion.right().value());
3501 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3503 // Looking for deployment or tosca artifacts
3504 Service service = validateServiceNameAndVersion.left().value();
3506 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3507 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3508 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3511 Optional<ArtifactDefinition> foundArtifactOptl = null;
3513 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3514 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3515 // filters artifact by name
3516 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3518 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3519 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3520 // filters TOSCA artifact by name
3521 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3523 if (!foundArtifactOptl.isPresent()) {
3524 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3525 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3527 log.debug("Found deployment artifact {}", normalizedArtifactName);
3528 // Downloading the artifact
3529 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3531 if (downloadArtifactEither.isRight()) {
3532 log.debug("Download artifact {} failed", normalizedArtifactName);
3533 return Either.right(downloadArtifactEither.right().value());
3535 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3536 return Either.left(downloadArtifactEither.left().value().getRight());
3539 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3540 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3541 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3542 if (artifactById.isRight()) {
3543 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3544 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3545 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3547 ArtifactDefinition artifactDefinition = artifactById.left().value();
3548 if (artifactDefinition == null) {
3549 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3550 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3553 return downloadArtifact(artifactDefinition);
3556 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3557 boolean found = false;
3558 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3559 if (artifactsS != null) {
3560 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3561 if (entry.getValue().getUniqueId().equals(artifactId)) {
3567 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3568 if (!found && deploymentArtifactsS != null) {
3569 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3570 if (entry.getValue().getUniqueId().equals(artifactId)) {
3576 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3577 if (!found && toscaArtifactsS != null) {
3578 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3579 if (entry.getValue().getUniqueId().equals(artifactId)) {
3585 switch (component.getComponentType()) {
3587 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3588 if (!found && interfaces != null) {
3589 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3590 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3591 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3592 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3593 .getImplementation()
3595 .equals(artifactId)) {
3604 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3605 if (!found && apiArtifacts != null) {
3606 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3607 if (entry.getValue().getUniqueId().equals(artifactId)) {
3621 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3623 boolean found = false;
3624 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3625 ComponentInstance resourceInstance = null;
3626 for (ComponentInstance ri : resourceInstances) {
3627 if (ri.getUniqueId().equals(resourceInstanceId)) {
3628 resourceInstance = ri;
3632 if (resourceInstance != null) {
3633 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3634 if (artifacts != null) {
3635 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3636 if (entry.getValue().getUniqueId().equals(artifactId)) {
3643 artifacts = resourceInstance.getArtifacts();
3644 if (artifacts != null) {
3645 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3646 if (entry.getValue().getUniqueId().equals(artifactId)) {
3657 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3658 String containerComponentType) {
3660 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3661 componentForAudit.getNodeType();
3663 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3664 .getToscaFullElement(componentId);
3666 if (componentResult.isRight()) {
3667 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3668 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3669 log.debug("Service not found, serviceId {}", componentId);
3670 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3671 return Either.right(responseFormat);
3673 return Either.left(componentResult.left().value());
3676 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3677 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3678 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3679 if (canWork.isRight()) {
3680 String uniqueId = component.getUniqueId();
3681 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3682 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3684 .getComponentType(), null);
3685 return Either.right(canWork.right().value());
3688 return Either.left(true);
3691 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3693 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3694 String role = user.getRole();
3695 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3696 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3697 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3698 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3699 return Either.right(responseFormat);
3702 return Either.left(true);
3705 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3706 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3708 if (validateUserExists.isRight()) {
3709 User user = new User();
3710 user.setUserId(userId);
3711 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right()
3712 .value(), componentType, null);
3713 return Either.right(validateUserExists.right().value());
3715 return Either.left(validateUserExists.left().value());
3718 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3719 AuditingActionEnum auditingAction = null;
3720 switch (operation.getArtifactOperationEnum()) {
3722 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3725 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3728 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3731 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3736 return auditingAction;
3739 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3740 String esArtifactId = artifactDefinition.getEsId();
3741 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3742 if (artifactfromES.isRight()) {
3743 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3744 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3745 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3746 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3747 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3748 .getArtifactDisplayName());
3750 return Either.right(responseFormat);
3753 ESArtifactData esArtifactData = artifactfromES.left().value();
3754 byte[] data = esArtifactData.getDataAsArray();
3756 log.debug("Artifact data from ES is null");
3757 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3759 String artifactName = artifactDefinition.getArtifactName();
3760 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3761 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3764 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3765 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3768 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3769 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3771 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3772 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3775 log.info("Failed to save artifact {}.", artifactData.getId());
3781 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3782 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3785 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3786 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3789 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3790 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3791 if (user.isRight()) {
3792 ResponseFormat responseFormat;
3793 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3794 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3795 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3798 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3799 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3801 return Either.right(responseFormat);
3804 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3806 .value(), groupType);
3807 return Either.left(artifactDefinition);
3810 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3811 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3813 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3814 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3815 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3817 artifactInfo.setArtifactDisplayName(artifactName);
3818 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3819 artifactInfo.setArtifactType(artifactType);
3820 artifactInfo.setDescription(artifactDescription);
3821 artifactInfo.setArtifactGroupType(groupType);
3822 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3824 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3826 return artifactInfo;
3829 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3830 String uniqueId = null;
3832 if (resourceId != null) {
3833 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3835 artifactInfo.setUniqueId(uniqueId);
3837 artifactInfo.setUserIdCreator(user.getUserId());
3838 String fullName = user.getFullName();
3839 artifactInfo.setUpdaterFullName(fullName);
3841 long time = System.currentTimeMillis();
3843 artifactInfo.setCreatorFullName(fullName);
3844 artifactInfo.setCreationDate(time);
3846 artifactInfo.setLastUpdateDate(time);
3847 artifactInfo.setUserIdLastUpdater(user.getUserId());
3849 artifactInfo.setMandatory(true);
3852 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3853 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3856 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3857 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3860 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3862 byte[] payload = payloadStr.getBytes();
3864 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3865 return Either.left(artifactData);
3869 * @param artifactDefinition
3872 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3873 String instanceId, boolean shouldLock, boolean inTransaction) {
3874 String payload = generateHeatEnvPayload(artifactDefinition);
3875 String prevUUID = artifactDefinition.getArtifactUUID();
3876 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3877 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3879 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3882 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3883 boolean shouldLock, boolean inTransaction, String instanceId) {
3884 String payload = generateHeatEnvPayload(artifactDefinition);
3885 String prevUUID = artifactDefinition.getArtifactUUID();
3886 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3887 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3889 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3892 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3893 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3894 List<ComponentInstance> componentInstances = component.getComponentInstances();
3895 if (componentInstances != null) {
3896 Optional<ComponentInstance> findFirst = componentInstances.stream()
3897 .filter(ci -> ci.getUniqueId()
3898 .equals(instanceId))
3900 if (findFirst.isPresent()) {
3901 ComponentInstance relevantInst = findFirst.get();
3902 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3903 .getGroupInstances());
3905 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3906 updatedGroupInstances.forEach(gi -> {
3907 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3908 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3910 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3911 if (status.isRight()) {
3912 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3913 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3914 .convertFromStorageResponse(status.right()
3915 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3916 return Either.right(responseFormat);
3922 return Either.left(updatedArtDef);
3925 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3926 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3927 StringBuilder sb = new StringBuilder();
3928 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3929 sb.append("parameters:\n");
3930 if (heatParameters != null) {
3931 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3933 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3935 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3937 String heatValue = heatParameterDefinition.getCurrentValue();
3938 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3939 heatValue = heatParameterDefinition.getDefaultValue();
3940 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3941 empltyHeatValues.add(heatParameterDefinition);
3945 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3950 .append(heatParameterDefinition.getName())
3953 .append(Boolean.parseBoolean(heatValue))
3958 .append(heatParameterDefinition.getName())
3961 .append(new BigDecimal(heatValue).toPlainString())
3964 case COMMA_DELIMITED_LIST:
3967 .append(heatParameterDefinition.getName())
3974 String value = heatValue;
3975 boolean starts = value.startsWith("\"");
3976 boolean ends = value.endsWith("\"");
3977 if (!(starts && ends)) {
3978 starts = value.startsWith("'");
3979 ends = value.endsWith("'");
3980 if (!(starts && ends)) {
3981 value = "\"" + value + "\"";
3985 .append(heatParameterDefinition.getName())
3995 if (!empltyHeatValues.isEmpty()) {
3996 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3997 empltyHeatValues.forEach(hv -> {
3998 sb.append(" ").append(hv.getName()).append(":");
3999 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
4000 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
4001 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
4002 sb.append(" \"\"").append("\n");
4005 sb.append(" ").append("\n");
4010 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
4013 return sb.toString().replaceAll("\\\\n", "\n");
4017 * @param artifactDefinition
4021 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4022 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4023 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
4024 .getHeatParamsUpdateDate(),
4025 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4029 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4030 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4031 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
4032 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4036 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
4037 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
4039 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
4041 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
4042 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
4044 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
4045 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
4046 ESArtifactData artifactData = null;
4048 if (artifactDataRes.isLeft()) {
4049 artifactData = artifactDataRes.left().value();
4052 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4053 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4054 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4055 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4057 return Either.right(artifactDataRes.right().value());
4059 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4061 String esArtifactId = artifactDefinition.getEsId();
4062 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4063 ESArtifactData esArtifactData;
4064 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4065 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4066 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4067 if (artifactfromES.isRight()) {
4068 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4069 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4070 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4071 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4072 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4074 esArtifactData = artifactfromES.left().value();
4075 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4078 oldCheckSum = artifactDefinition.getArtifactChecksum();
4081 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4084 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4085 if (lockComponent.isRight()) {
4086 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4087 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4088 return Either.right(lockComponent.right().value());
4092 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4094 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4095 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4096 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4097 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4098 .getArtifactType(), artifactDefinition.getEsId());
4099 if (updateArifactDefinitionStatus.isRight()) {
4100 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4102 .value()), artifactDefinition.getArtifactDisplayName());
4103 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4104 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4105 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4106 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4108 return Either.right(responseFormat);
4113 oldCheckSum = artifactDefinition.getArtifactChecksum();
4114 artifactDefinition.setArtifactChecksum(newCheckSum);
4115 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4116 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4117 .getArtifactType(), artifactDefinition.getEsId());
4118 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4119 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4121 log.trace("Update Payload ", artifactDefinition.getEsId());
4123 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4125 artifactDefinition = updateArifactDefinitionStatus.left().value();
4126 artifactData.setId(artifactDefinition.getUniqueId());
4127 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4129 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4130 if (!inTransaction) {
4133 log.debug("Artifact Saved In ES {}", artifactData.getId());
4134 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4135 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4136 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4137 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4141 if (!inTransaction) {
4142 titanDao.rollback();
4144 log.info("Failed to save artifact {}.", artifactData.getId());
4145 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4146 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4147 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4148 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4150 return Either.right(responseFormat);
4154 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4156 .value()), artifactDefinition.getArtifactDisplayName());
4157 log.debug("Failed To update artifact {}", artifactData.getId());
4158 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4159 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4160 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4162 return Either.right(responseFormat);
4168 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4174 return Either.left(artifactDefinition);
4178 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4179 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4180 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4181 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4185 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4186 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4188 Map<String, Object> json = new HashMap<String, Object>();
4189 if (artifactId != null && !artifactId.isEmpty()) {
4190 json.put(Constants.ARTIFACT_ID, artifactId);
4193 json.put(Constants.ARTIFACT_NAME, artifactName);
4194 json.put(Constants.ARTIFACT_TYPE, artifactType);
4195 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4197 if (artifactContent != null) {
4198 log.debug("payload is encoded. perform decode");
4199 String encodedPayload = Base64.encodeBase64String(artifactContent);
4200 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4202 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4203 json.put(Constants.ARTIFACT_LABEL, label);
4204 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4205 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4206 : updatedRequiredArtifacts.stream()
4207 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4209 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4210 .map(e -> e.getFileName())
4211 .collect(Collectors.toList()));
4212 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4217 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4219 String jsonStr = gson.toJson(json);
4220 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4221 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4222 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4223 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4224 if (uploadArtifactToService.isRight()) {
4225 return Either.right(uploadArtifactToService.right().value());
4228 return Either.left(uploadArtifactToService.left().value());
4231 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4232 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4233 convertParentType(componentType);
4234 String parentId = parent.getUniqueId();
4235 ArtifactDefinition currArtifact = artifactInfo;
4237 if (origMd5 != null) {
4238 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4239 if (validateMd5.isRight()) {
4240 ResponseFormat responseFormat = validateMd5.right().value();
4241 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4242 return Either.right(responseFormat);
4245 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4246 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4247 if (deploymentValidationResult.isRight()) {
4248 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4249 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4250 return Either.right(responseFormat);
4253 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4254 if (payloadEither.isRight()) {
4255 ResponseFormat responseFormat = payloadEither.right().value();
4256 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4257 return Either.right(responseFormat);
4261 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4262 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4263 return Either.right(responseFormat);
4269 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
4270 if (lockComponent.isRight()) {
4271 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4272 .value(), componentType, null);
4273 return Either.right(lockComponent.right().value());
4276 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4278 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4284 if (resultOp == null || resultOp.isRight()) {
4285 log.debug("all changes rollback");
4286 if (!inTransaction) {
4287 titanDao.rollback();
4291 log.debug("all changes committed");
4292 if (!inTransaction) {
4297 componentType = parent.getComponentType();
4299 NodeTypeEnum nodeType = componentType.getNodeType();
4300 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4304 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4305 ComponentTypeEnum componentType, String origMd5) {
4307 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4308 Either<ArtifactDefinition, Operation> insideEither = null;
4309 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4310 if (getRI.isRight()) {
4311 return Either.right(getRI.right().value());
4313 ComponentInstance ri = getRI.left().value();
4314 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4315 if (getArtifactRes.isRight()) {
4316 return Either.right(getArtifactRes.right().value());
4318 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4320 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4321 .equals(ArtifactTypeEnum.HEAT_VOL
4322 .getType()) || currArtifact
4324 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4325 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4326 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4328 return Either.right(responseFormat);
4330 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4331 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4332 new ArrayList<HeatParameterDefinition>();
4335 if (origMd5 != null) {
4336 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4337 .getName(), currentHeatEnvParams,
4338 updatedHeatEnvParams, currArtifact.getArtifactName());
4339 if (uploadParamsValidationResult.isRight()) {
4340 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4341 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4343 return Either.right(responseFormat);
4345 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4348 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4350 if (validateAndConvertHeatParamers.isRight()) {
4351 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4352 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4354 return Either.right(responseFormat);
4357 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4358 // fill reduced heat env parameters List for updating
4359 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4360 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4361 currArtifact.setListHeatParameters(currentHeatEnvParams);
4363 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4364 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4365 if (updateArifactRes.isRight()) {
4366 log.debug("Failed to update artifact on graph - {}", artifactId);
4367 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4370 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4372 return Either.right(responseFormat);
4374 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4375 if (error != StorageOperationStatus.OK) {
4376 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4377 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4379 return Either.right(responseFormat);
4382 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4384 .getUniqueId(), parent.getUniqueId());
4385 if (error != StorageOperationStatus.OK) {
4386 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4387 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4389 return Either.right(responseFormat);
4393 insideEither = Either.left(currArtifact);
4394 resultOp = Either.left(insideEither);
4395 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4396 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4401 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4402 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4403 String paramName = heatEnvParam.getName();
4404 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4405 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4406 String updatedParamValue = heatEnvParam.getCurrentValue();
4407 currHeatParam.setCurrentValue(updatedParamValue);
4413 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4414 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4416 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4417 Either<ArtifactDefinition, Operation> insideEither = null;
4418 String currentHeatId = currHeatArtifact.getUniqueId();
4420 String esArtifactId = currHeatArtifact.getEsId();
4421 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4422 if (artifactFromES.isRight()) {
4423 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4424 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4425 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4426 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4427 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4430 ESArtifactData esArtifactData = artifactFromES.left().value();
4432 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4434 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4435 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4436 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4438 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4442 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4444 paramName = heatEnvParam.getName();
4445 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4446 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4448 String updatedParamValue = heatEnvParam.getCurrentValue();
4449 if (updatedParamValue == null) {
4450 updatedParamValue = heatEnvParam.getDefaultValue();
4452 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4453 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4454 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4455 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4456 .getType(), paramType.getType(), paramName);
4457 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4458 return Either.right(responseFormat);
4461 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4462 newHeatEnvParams.add(currHeatParam);
4467 if (!newHeatEnvParams.isEmpty()) {
4468 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4469 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4470 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4472 if (operationStatus.isRight()) {
4473 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4475 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4478 return Either.right(responseFormat);
4481 updatedHeatArt = operationStatus.left().value();
4483 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4484 esArtifactData.setId(updatedHeatArt.getEsId());
4486 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4489 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
4490 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4491 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4492 .getUniqueId(), responseFormat, componentType, null);
4495 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
4496 log.debug("Failed to save the artifact.");
4497 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4498 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4499 .getUniqueId(), responseFormat, componentType, null);
4500 resultOp = Either.right(responseFormat);
4503 insideEither = Either.left(updatedHeatArt);
4506 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4507 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4508 artifactEnvInfo.setArtifactChecksum(null);
4509 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4510 .getUniqueId(), componentType.getNodeType(), componentId);
4513 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4517 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4518 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4520 .value(), parent, componentType);
4521 if (result != ActionStatus.OK) {
4522 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4523 return Either.right(responseFormat);
4527 if (updatedHeatEnvParams.isEmpty()) {
4528 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4530 resultOp = Either.left(insideEither);
4531 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4532 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4537 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4538 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4539 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4540 return Either.right(responseFormat);
4544 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4545 StorageOperationStatus error = StorageOperationStatus.OK;
4546 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4547 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4548 List<String> groupInstancesId = null;
4549 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4550 groupInstancesId = groupsInstances.stream()
4551 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4552 .contains(artifactId))
4553 .map(GroupInstanceDataDefinition::getUniqueId)
4554 .collect(Collectors.toList());
4556 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4557 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4563 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4564 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4566 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4567 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4568 .getArtifactName(), currArtifactName);
4569 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4570 return Either.right(responseFormat);
4573 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4574 String paramName = uploadedHeatParam.getName();
4575 boolean isExistsInHeat = false;
4576 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4577 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4579 isExistsInHeat = true;
4580 uploadedHeatParam.setType(currHeatParam.getType());
4581 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4582 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4583 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4587 if (!isExistsInHeat) {
4588 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4589 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4590 return Either.right(responseFormat);
4593 return Either.left(updatedHeatEnvParams);
4596 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4597 ResponseFormat responseFormat = null;
4598 List<ComponentInstance> ris = component.getComponentInstances();
4599 for (ComponentInstance ri : ris) {
4600 if (riID.equals(ri.getUniqueId())) {
4601 return Either.left(ri);
4604 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4605 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4606 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4607 return Either.right(responseFormat);
4610 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4611 ResponseFormat responseFormat = null;
4612 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4613 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4614 if (artifactId.equals(artifact.getUniqueId())) {
4615 return Either.left(artifact);
4618 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4619 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4621 return Either.right(responseFormat);
4624 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4625 ArtifactDefinition ret;
4626 if (eitherArtifact.isLeft()) {
4627 ret = eitherArtifact.left().value();
4630 ret = eitherArtifact.right().value().getImplementationArtifact();
4636 * downloads artifact of component by UUIDs
4638 * @param componentType
4639 * @param componentUuid
4640 * @param artifactUUID
4641 * @param auditAdditionalParam
4644 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4645 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4646 Either<byte[], ResponseFormat> result;
4647 byte[] downloadedArtifact = null;
4648 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4649 if (errorWrapper.isEmpty()) {
4650 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4651 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4653 if (errorWrapper.isEmpty()) {
4654 result = Either.left(downloadedArtifact);
4657 result = Either.right(errorWrapper.getInnerElement());
4663 * downloads an artifact of resource instance of component by UUIDs
4665 * @param componentType
4666 * @param componentUuid
4667 * @param resourceInstanceName
4668 * @param artifactUUID
4669 * @param auditAdditionalParam
4672 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4673 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4674 Either<byte[], ResponseFormat> result;
4675 byte[] downloadedArtifact = null;
4676 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4677 if (errorWrapper.isEmpty()) {
4678 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4681 if (errorWrapper.isEmpty()) {
4682 result = Either.left(downloadedArtifact);
4685 result = Either.right(errorWrapper.getInnerElement());
4691 * uploads an artifact to a component by UUID
4695 * @param componentType
4696 * @param componentUuid
4697 * @param additionalParams
4701 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4702 ArtifactOperationInfo operation) {
4703 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4704 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4705 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4706 ArtifactDefinition uploadArtifact = null;
4707 Component component = null;
4708 String componentId = null;
4709 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4710 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4711 String userId = request.getHeader(Constants.USER_ID_HEADER);
4713 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4714 if (getComponentRes.isRight()) {
4715 StorageOperationStatus status = getComponentRes.right().value();
4716 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4717 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4719 if (errorWrapper.isEmpty()) {
4720 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4721 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4723 if (!getComponentRes.left()
4725 .getMetadataDataDefinition()
4727 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4728 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4729 if (component != null) {
4730 componentId = component.getUniqueId();
4731 componentName = component.getName();
4734 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4736 if (errorWrapper.isEmpty()) {
4737 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4738 if (actionResult.isRight()) {
4739 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4742 errorWrapper.setInnerElement(actionResult.right().value());
4745 if (errorWrapper.isEmpty()) {
4746 uploadArtifact = actionResult.left().value().left().value();
4747 uploadArtifactResult = Either.left(uploadArtifact);
4750 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4752 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4753 return uploadArtifactResult;
4757 * upload an artifact to a resource instance by UUID
4761 * @param componentType
4762 * @param componentUuid
4763 * @param resourceInstanceName
4764 * @param additionalParams
4768 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4769 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4770 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4771 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4772 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4773 ArtifactDefinition uploadArtifact = null;
4774 Component component = null;
4775 String componentInstanceId;
4777 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4778 String userId = request.getHeader(Constants.USER_ID_HEADER);
4780 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4781 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4782 if (getComponentRes.isRight()) {
4783 StorageOperationStatus status = getComponentRes.right().value();
4784 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4785 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4787 if (errorWrapper.isEmpty() && !getComponentRes.left()
4789 .getMetadataDataDefinition()
4791 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4792 component = checkoutParentComponent(componentType, getComponentRes.left()
4794 .getMetadataDataDefinition()
4795 .getUniqueId(), userId, errorWrapper);
4797 if (errorWrapper.isEmpty()) {
4798 if (component == null) {
4799 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4802 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4805 if (errorWrapper.isEmpty()) {
4806 componentInstanceId = componentRiPair.getRight().getUniqueId();
4807 componentId = componentRiPair.getLeft().getUniqueId();
4808 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4810 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4811 .findParamByType(componentType));
4812 if (actionResult.isRight()) {
4813 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4816 errorWrapper.setInnerElement(actionResult.right().value());
4819 if (errorWrapper.isEmpty()) {
4820 uploadArtifact = actionResult.left().value().left().value();
4821 uploadArtifactResult = Either.left(uploadArtifact);
4824 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4826 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4827 return uploadArtifactResult;
4831 * updates an artifact on a component by UUID
4835 * @param componentType
4836 * @param componentUuid
4837 * @param artifactUUID
4838 * @param additionalParams
4839 * @param operation TODO
4842 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4843 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4844 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4845 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4846 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4847 ArtifactDefinition updateArtifact = null;
4848 Component component = null;
4849 String componentId = null;
4850 String artifactId = null;
4851 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4852 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4853 String userId = request.getHeader(Constants.USER_ID_HEADER);
4855 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4856 if (getComponentRes.isRight()) {
4857 StorageOperationStatus status = getComponentRes.right().value();
4858 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4859 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4861 if (errorWrapper.isEmpty()) {
4862 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4863 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4865 if (!getComponentRes.left()
4867 .getMetadataDataDefinition()
4869 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4870 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4871 if (component != null) {
4872 componentId = component.getUniqueId();
4873 componentName = component.getName();
4876 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4878 if (errorWrapper.isEmpty()) {
4879 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4881 if (errorWrapper.isEmpty()) {
4882 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4883 if (actionResult.isRight()) {
4884 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4887 errorWrapper.setInnerElement(actionResult.right().value());
4890 if (errorWrapper.isEmpty()) {
4891 updateArtifact = actionResult.left().value().left().value();
4892 updateArtifactResult = Either.left(updateArtifact);
4896 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4898 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4899 return updateArtifactResult;
4903 * updates an artifact on a resource instance by UUID
4907 * @param componentType
4908 * @param componentUuid
4909 * @param resourceInstanceName
4910 * @param artifactUUID
4911 * @param additionalParams
4912 * @param operation TODO
4915 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4916 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4918 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4919 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4920 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4921 ArtifactDefinition updateArtifact = null;
4922 Component component = null;
4923 String componentInstanceId = null;
4924 String componentId = null;
4925 String artifactId = null;
4926 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4927 String userId = request.getHeader(Constants.USER_ID_HEADER);
4929 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4930 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4931 if (getComponentRes.isRight()) {
4932 StorageOperationStatus status = getComponentRes.right().value();
4933 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4934 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4936 if (errorWrapper.isEmpty() && !getComponentRes.left()
4938 .getMetadataDataDefinition()
4940 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4941 component = checkoutParentComponent(componentType, getComponentRes.left()
4943 .getMetadataDataDefinition()
4944 .getUniqueId(), userId, errorWrapper);
4946 if (errorWrapper.isEmpty()) {
4947 if (component == null) {
4948 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4951 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4954 if (errorWrapper.isEmpty()) {
4955 componentInstanceId = componentRiPair.getRight().getUniqueId();
4956 componentId = componentRiPair.getLeft().getUniqueId();
4957 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4959 if (errorWrapper.isEmpty()) {
4960 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4962 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4963 .findParamByType(componentType));
4964 if (actionResult.isRight()) {
4965 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4968 errorWrapper.setInnerElement(actionResult.right().value());
4971 if (errorWrapper.isEmpty()) {
4972 updateArtifact = actionResult.left().value().left().value();
4973 updateArtifactResult = Either.left(updateArtifact);
4976 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4978 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4979 return updateArtifactResult;
4983 * updates an artifact on a component by UUID
4987 * @param componentType
4988 * @param componentUuid
4989 * @param artifactUUID
4990 * @param additionalParams
4991 * @param operation TODO
4994 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4995 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4996 String componentUuid, String artifactUUID, String operationUUID,
4997 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4998 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4999 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
5000 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5001 ArtifactDefinition updateArtifact = null;
5002 String componentId = null;
5003 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
5004 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5005 String userId = request.getHeader(Constants.USER_ID_HEADER);
5007 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5008 if (getComponentRes.isRight()) {
5009 StorageOperationStatus status = getComponentRes.right().value();
5010 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5011 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5013 if (errorWrapper.isEmpty()) {
5014 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5015 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5016 if (!getComponentRes.left()
5018 .getMetadataDataDefinition()
5020 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5021 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5022 if (component != null) {
5023 componentId = component.getUniqueId();
5024 componentName = component.getName();
5026 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
5029 if (errorWrapper.isEmpty()) {
5030 Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId);
5031 if (interfaceName.isRight()) {
5032 errorWrapper.setInnerElement(interfaceName.right().value());
5034 if (errorWrapper.isEmpty()) {
5035 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5036 artifactUUID, artifactInfo, origMd5, data, interfaceName.left().value(),
5037 operationUUID, null, null);
5038 if (actionResult.isRight()) {
5039 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
5042 errorWrapper.setInnerElement(actionResult.right().value());
5046 if (errorWrapper.isEmpty()) {
5047 updateArtifact = actionResult.left().value().left().value();
5048 updateArtifactResult = Either.left(updateArtifact);
5052 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5054 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
5055 return updateArtifactResult;
5058 private Either<String, ResponseFormat> fetchInterfaceName(String componentId) {
5059 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
5060 toscaOperationFacade.getToscaElement(componentId);
5061 if (resourceStorageOperationStatusEither.isRight()) {
5062 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
5063 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
5064 return Either.right(componentsUtils
5065 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5067 Resource storedResource = resourceStorageOperationStatusEither.left().value();
5069 return Either.left(InterfaceUtils.createInterfaceToscaResourceName(
5070 storedResource.getName()));
5075 * deletes an artifact on a component by UUID
5078 * @param componentType
5079 * @param componentUuid
5080 * @param artifactUUID
5081 * @param additionalParams
5082 * @param operation TODO
5085 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
5086 ArtifactOperationInfo operation) {
5088 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5089 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5090 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5091 ArtifactDefinition deleteArtifact = null;
5092 Component component = null;
5093 String componentId = null;
5094 String artifactId = null;
5095 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5096 String userId = request.getHeader(Constants.USER_ID_HEADER);
5098 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5099 if (getComponentRes.isRight()) {
5100 StorageOperationStatus status = getComponentRes.right().value();
5101 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5102 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5104 if (errorWrapper.isEmpty()) {
5105 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5106 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5107 if (!getComponentRes.left()
5109 .getMetadataDataDefinition()
5111 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5112 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5113 if (component != null) {
5114 componentId = component.getUniqueId();
5115 componentName = component.getName();
5118 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
5120 if (errorWrapper.isEmpty()) {
5121 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5123 if (errorWrapper.isEmpty()) {
5124 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5125 if (actionResult.isRight()) {
5126 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
5129 errorWrapper.setInnerElement(actionResult.right().value());
5132 if (errorWrapper.isEmpty()) {
5133 deleteArtifact = actionResult.left().value().left().value();
5134 deleteArtifactResult = Either.left(deleteArtifact);
5137 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5139 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5140 return deleteArtifactResult;
5144 * deletes an artifact from a resource instance by UUID
5147 * @param componentType
5148 * @param componentUuid
5149 * @param resourceInstanceName
5150 * @param artifactUUID
5151 * @param additionalParams
5152 * @param operation TODO
5155 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5156 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
5158 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5159 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5160 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5161 ArtifactDefinition deleteArtifact = null;
5162 Component component = null;
5163 String componentInstanceId = null;
5164 String componentId = null;
5165 String artifactId = null;
5166 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5167 String userId = request.getHeader(Constants.USER_ID_HEADER);
5168 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5169 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5170 if (getComponentRes.isRight()) {
5171 StorageOperationStatus status = getComponentRes.right().value();
5172 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5173 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5175 if (errorWrapper.isEmpty() && !getComponentRes.left()
5177 .getMetadataDataDefinition()
5179 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5180 component = checkoutParentComponent(componentType, getComponentRes.left()
5182 .getMetadataDataDefinition()
5183 .getUniqueId(), userId, errorWrapper);
5185 if (errorWrapper.isEmpty()) {
5186 if (component == null) {
5187 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5190 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5193 if (errorWrapper.isEmpty()) {
5194 componentInstanceId = componentRiPair.getRight().getUniqueId();
5195 componentId = componentRiPair.getLeft().getUniqueId();
5196 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5198 if (errorWrapper.isEmpty()) {
5200 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5201 .findParamByType(componentType));
5203 if (actionResult.isRight()) {
5204 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
5207 errorWrapper.setInnerElement(actionResult.right().value());
5210 if (errorWrapper.isEmpty()) {
5211 deleteArtifact = actionResult.left().value().left().value();
5212 deleteArtifactResult = Either.left(deleteArtifact);
5215 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5217 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5218 return deleteArtifactResult;
5221 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5222 String artifactId = null;
5223 ArtifactDefinition foundArtifact = null;
5224 if (instance.getDeploymentArtifacts() != null) {
5225 foundArtifact = instance.getDeploymentArtifacts()
5228 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5229 .equals(artifactUUID))
5233 if (foundArtifact == null && instance.getArtifacts() != null) {
5234 foundArtifact = instance.getArtifacts()
5237 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5238 .equals(artifactUUID))
5242 if (foundArtifact == null) {
5243 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5244 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5247 artifactId = foundArtifact.getUniqueId();
5252 @SuppressWarnings("unchecked")
5253 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5254 Map<String, String> existingEnvVersions) {
5255 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5257 .getDeploymentResourceInstanceArtifacts();
5258 if (deploymentResourceArtifacts == null) {
5259 log.debug("no deployment artifacts are configured for generated artifacts");
5260 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5262 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5263 if (placeHolderData == null) {
5264 log.debug("no env type {} are configured for generated artifacts", envType);
5265 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5268 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5269 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5270 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5271 if (createArtifactPlaceHolder.isRight()) {
5272 return Either.right(createArtifactPlaceHolder.right().value());
5274 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5275 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5276 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5277 artifactHeatEnv.setTimeout(0);
5278 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5279 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5280 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5281 ArtifactDefinition heatEnvPlaceholder;
5282 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5283 if (parentType != NodeTypeEnum.ResourceInstance) {
5284 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5285 .getUniqueId(), parentType, parentId);
5286 if (addHeatEnvArtifact.isRight()) {
5287 log.debug("failed to create heat env artifact on resource instance");
5288 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5290 .value(), false), "", null));
5292 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5295 heatEnvPlaceholder = artifactHeatEnv;
5296 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5297 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5299 String artifactData = buildAuditingArtifactData(heatEnvPlaceholder);
5300 ComponentTypeEnum componentType = component.getComponentType();
5301 if (parentType == NodeTypeEnum.ResourceInstance) {
5302 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5304 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType,
5305 ResourceAuditData.newBuilder().build(),
5306 ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5307 parentName, null, artifactData, null);
5308 return Either.left(heatEnvPlaceholder);
5311 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5312 if (artifact.getListHeatParameters() == null) {
5315 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5316 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5317 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5318 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5319 heatEnvParameter.setCurrentValue(null);
5320 heatEnvParameters.add(heatEnvParameter);
5322 artifactDefinition.setListHeatParameters(heatEnvParameters);
5325 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5326 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5327 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5328 String name = heatArtifact.getArtifactName();
5331 name = heatArtifact.getArtifactLabel();
5332 fileName = name + "." + envExtension;
5335 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5337 heatEnvArtifact.setArtifactName(fileName);
5340 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5341 if (null != existingEnvVersions) {
5342 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5343 if (null != prevVersion) {
5344 heatEnvArtifact.setArtifactVersion(prevVersion);
5350 * Handles Artifacts Request For Inner Component
5352 * @param artifactsToHandle
5355 * @param vfcsNewCreatedArtifacts
5358 * @param inTransaction
5361 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5362 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5364 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5365 ComponentTypeEnum componentType = component.getComponentType();
5366 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5367 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5368 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5372 for (ArtifactDefinition artifact : artifactsToHandle) {
5373 originData = buildJsonStringForCsarVfcArtifact(artifact);
5374 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5375 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5376 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5377 if (actionResult.isRight()) {
5378 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5379 .getName(), actionResult.right().value());
5380 errorWrapper.setInnerElement(actionResult.right().value());
5381 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5382 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5386 uploadedArtifacts.add(actionResult.left().value().left().value());
5388 if (errorWrapper.isEmpty()) {
5389 handleArtifactsResult = Either.left(uploadedArtifacts);
5392 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5395 catch (Exception e) {
5396 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5397 handleArtifactsResult = Either.right(responseFormat);
5398 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5400 return handleArtifactsResult;
5403 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5404 ComponentInstance componentInstance = null;
5405 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5406 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5407 if (errorWrapper.isEmpty()) {
5408 componentInstance = component.getComponentInstances()
5410 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5411 .equals(normalizedName))
5414 if (componentInstance == null) {
5415 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5417 .getValue(), component.getName()));
5418 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5421 return componentInstance;
5424 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5426 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5427 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5428 ComponentInstance componentInstance = component.getComponentInstances()
5430 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5431 .equals(normalizedName))
5434 if (componentInstance == null) {
5435 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5437 .getValue(), component.getName()));
5438 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5441 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5443 return relatedComponentComponentInstancePair;
5446 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5447 ComponentInstance componentInstance;
5448 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5449 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5450 if (errorWrapper.isEmpty()) {
5451 componentInstance = component.getComponentInstances()
5453 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5456 if (componentInstance == null) {
5457 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5459 .getValue(), component.getName()));
5460 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5463 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5466 return relatedComponentComponentInstancePair;
5469 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5471 byte[] downloadedArtifact = null;
5472 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5473 List<ArtifactDefinition> artifactsList = null;
5474 ArtifactDefinition deploymentArtifact = null;
5475 if (artifacts != null && !artifacts.isEmpty()) {
5476 artifactsList = artifacts.values()
5478 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5479 .equals(artifactUUID))
5480 .collect(Collectors.toList());
5482 if (artifactsList == null || artifactsList.isEmpty()) {
5483 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5484 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5486 if (errorWrapper.isEmpty()) {
5487 deploymentArtifact = artifactsList.get(0);
5488 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5489 if (downloadArtifactEither.isRight()) {
5490 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5491 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5494 if (errorWrapper.isEmpty()) {
5495 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5496 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5498 return downloadedArtifact;
5501 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5502 Component component = null;
5503 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5504 if (getComponentRes.isRight()) {
5505 StorageOperationStatus status = getComponentRes.right().value();
5506 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5507 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5510 component = getComponentRes.left().value();
5515 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5516 Component component = null;
5517 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5518 if (getComponentRes.isRight()) {
5519 StorageOperationStatus status = getComponentRes.right().value();
5520 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5521 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5524 List<Component> value = getComponentRes.left().value();
5525 if (value.isEmpty()) {
5526 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5527 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5528 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5531 component = value.get(0);
5537 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5538 String artifactId = null;
5539 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5540 StorageOperationStatus storageStatus;
5541 ArtifactDefinition latestArtifact = null;
5542 List<ArtifactDefinition> artifacts = null;
5543 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5544 if (getArtifactsRes.isRight()) {
5545 storageStatus = getArtifactsRes.right().value();
5546 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5547 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5548 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5550 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5552 if (errorWrapper.isEmpty()) {
5553 artifacts = getArtifactsRes.left()
5557 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5558 .equals(artifactUUID))
5559 .collect(Collectors.toList());
5560 if (artifacts == null || artifacts.isEmpty()) {
5561 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5562 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5565 if (errorWrapper.isEmpty()) {
5566 latestArtifact = artifacts.stream().max((a1, a2) -> {
5567 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5568 if (compareRes == 0) {
5569 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5570 .getLastUpdateDate());
5574 if (latestArtifact == null) {
5575 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5576 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5579 if (errorWrapper.isEmpty()) {
5580 artifactId = latestArtifact.getUniqueId();
5585 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5587 Component component = null;
5588 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5589 if (getUserRes.isRight()) {
5590 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5593 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5595 if (errorWrapper.isEmpty()) {
5596 User modifier = getUserRes.left().value();
5597 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5598 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5599 if (checkoutRes.isRight()) {
5600 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5601 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5602 errorWrapper.setInnerElement(checkoutRes.right().value());
5605 component = checkoutRes.left().value();
5611 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
5612 if (artifact == null) {
5613 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
5614 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
5615 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
5616 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
5620 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
5621 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
5622 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
5626 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5627 Map<String, Object> json = new HashMap<>();
5628 String artifactName = artifact.getArtifactName();
5629 json.put(Constants.ARTIFACT_NAME, artifactName);
5630 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5631 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5632 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5633 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5634 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5635 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5636 return gson.toJson(json);
5640 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5641 this.nodeTemplateOperation = nodeTemplateOperation;