2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import fj.data.Either;
27 import org.apache.commons.codec.binary.Base64;
28 import org.apache.commons.collections.CollectionUtils;
29 import org.apache.commons.collections.MapUtils;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.openecomp.sdc.be.components.ArtifactsResolver;
33 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
35 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
36 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
40 import org.openecomp.sdc.be.config.ConfigurationManager;
41 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
42 import org.openecomp.sdc.be.dao.api.ActionStatus;
43 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
44 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
45 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
46 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
49 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
50 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
51 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
52 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
53 import org.openecomp.sdc.be.model.*;
54 import org.openecomp.sdc.be.model.heat.HeatParameterType;
55 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
56 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
57 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
58 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
59 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
60 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
61 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
62 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
63 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
64 import org.openecomp.sdc.be.resources.data.ESArtifactData;
65 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
66 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
67 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
68 import org.openecomp.sdc.be.servlets.RepresentationUtils;
69 import org.openecomp.sdc.be.tosca.CsarUtils;
70 import org.openecomp.sdc.be.tosca.ToscaError;
71 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
72 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
73 import org.openecomp.sdc.be.user.IUserBusinessLogic;
74 import org.openecomp.sdc.be.user.Role;
75 import org.openecomp.sdc.be.user.UserBusinessLogic;
76 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
77 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
78 import org.openecomp.sdc.common.api.Constants;
79 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
80 import org.openecomp.sdc.common.datastructure.Wrapper;
81 import org.openecomp.sdc.common.util.GeneralUtility;
82 import org.openecomp.sdc.common.util.ValidationUtils;
83 import org.openecomp.sdc.common.util.YamlToObjectConverter;
84 import org.openecomp.sdc.exception.ResponseFormat;
85 import org.slf4j.Logger;
86 import org.slf4j.LoggerFactory;
87 import org.springframework.beans.factory.annotation.Autowired;
88 import org.xml.sax.InputSource;
89 import org.xml.sax.SAXException;
90 import org.xml.sax.SAXNotRecognizedException;
91 import org.xml.sax.SAXNotSupportedException;
92 import org.xml.sax.XMLReader;
93 import org.yaml.snakeyaml.Yaml;
95 import javax.servlet.http.HttpServletRequest;
96 import javax.xml.XMLConstants;
97 import javax.xml.parsers.ParserConfigurationException;
98 import javax.xml.parsers.SAXParserFactory;
99 import java.io.ByteArrayInputStream;
100 import java.io.IOException;
101 import java.math.BigDecimal;
102 import java.util.ArrayList;
103 import java.util.Comparator;
104 import java.util.EnumMap;
105 import java.util.HashMap;
106 import java.util.Iterator;
107 import java.util.List;
108 import java.util.Map;
109 import java.util.Map.Entry;
110 import java.util.Optional;
111 import java.util.Set;
112 import java.util.function.Predicate;
113 import java.util.function.Supplier;
114 import java.util.stream.Collectors;
116 @org.springframework.stereotype.Component("artifactBusinessLogic")
117 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
118 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
119 private static final String ARTIFACT_DESCRIPTION = "artifact description";
120 private static final String ARTIFACT_LABEL = "artifact label";
121 private static final String ARTIFACT_URL = "artifact url";
122 private static final String ARTIFACT_NAME = "artifact name";
123 private static final String ARTIFACT_PAYLOAD = "artifact payload";
125 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
126 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
127 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
129 public static final String HEAT_ENV_NAME = "heatEnv";
130 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
131 public static final String HEAT_ENV_SUFFIX = "env";
132 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
134 private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
135 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
137 @javax.annotation.Resource
138 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
139 @javax.annotation.Resource
140 private IUserAdminOperation userOperaton;
142 @javax.annotation.Resource
143 private IElementOperation elementOperation;
145 @javax.annotation.Resource
146 private ResourceBusinessLogic resourceBusinessLogic;
148 @javax.annotation.Resource
149 private ServiceBusinessLogic serviceBusinessLogic;
151 @javax.annotation.Resource
152 private UserBusinessLogic userAdminManager;
154 @javax.annotation.Resource
155 private IHeatParametersOperation heatParametersOperation;
158 private ArtifactCassandraDao artifactCassandraDao;
161 private ToscaExportHandler toscaExportUtils;
164 private CsarUtils csarUtils;
167 private LifecycleBusinessLogic lifecycleBusinessLogic;
170 private IUserBusinessLogic userBusinessLogic;
173 private NodeTemplateOperation nodeTemplateOperation;
176 private ArtifactsResolver artifactsResolver;
178 public enum ArtifactOperationEnum {
179 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
181 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
182 return operation == CREATE || operation == LINK;
186 public class ArtifactOperationInfo {
188 private ArtifactOperationEnum artifactOperationEnum;
189 private boolean isExternalApi;
190 private boolean ignoreLifecycleState;
192 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
193 this.artifactOperationEnum = artifactOperationEnum;
194 this.isExternalApi = isExternalApi;
195 this.ignoreLifecycleState = ignoreLifecycleState;
198 public boolean isExternalApi() {
199 return isExternalApi;
202 public boolean ignoreLifecycleState() {
203 return ignoreLifecycleState;
206 public ArtifactOperationEnum getArtifactOperationEnum() {
207 return artifactOperationEnum;
213 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
214 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
215 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
218 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
219 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
221 // step 1 - detect auditing type
222 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
223 // step 2 - check header
224 if (userId == null) {
225 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
226 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
227 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
228 return Either.right(responseFormat);
230 // step 3 - check user existence
231 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
232 if (userResult.isRight()) {
233 return Either.right(userResult.right().value());
236 // step 4 - check user's role
237 User user = userResult.left().value();
238 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
239 if (validateUserRole.isRight()) {
240 return Either.right(validateUserRole.right().value());
244 // 5. check service/resource existence
245 // 6. check service/resource check out
246 // 7. user is owner of checkout state
247 org.openecomp.sdc.be.model.Component component = null;
248 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
249 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
250 if (validateComponent.isRight()) {
251 return Either.right(validateComponent.right().value());
253 component = validateComponent.left().value();
254 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
255 if (validateWorkOnResource.isRight()) {
256 return Either.right(validateWorkOnResource.right().value());
260 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, user, component,
261 shouldLock, inTransaction, true);
265 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
266 * For regular usage use <br>
267 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
271 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
272 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
273 Component parent = component;
274 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
276 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
277 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
279 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
280 if (errorWrapper.isEmpty()) {
282 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
285 result = Either.right(errorWrapper.getInnerElement());
290 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
291 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
292 ArtifactDefinition validatedArtifactInfo = artifactInfo;
293 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
294 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
295 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
296 if (validateArtifact.isRight()) {
297 ResponseFormat responseFormat = validateArtifact.right().value();
298 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
299 errorWrapper.setInnerElement(validateArtifact.right().value());
301 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
302 validatedArtifactInfo = validateArtifact.left().value();
303 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
306 return validatedArtifactInfo;
309 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
310 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
311 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
313 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
314 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
315 ComponentInstance componentInstance = component.getComponentInstances()
317 .filter(p -> p.getUniqueId().equals(componentId))
320 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
322 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
324 .filter(p -> p.getUniqueId()
325 .equals(validatedArtifact.getUniqueId()))
328 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
329 .getName(), user, componentId, shouldLock, inTransaction);
330 if (eitherGenerated.isRight()) {
331 errorWrapper.setInnerElement(eitherGenerated.right().value());
336 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
337 boolean needGenerate;
338 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
339 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
340 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
341 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
342 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
346 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
347 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
349 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
352 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
353 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
355 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
356 if (generated.isRight()) {
359 byte[] decodedPayload = artifactDefinition.getPayloadData();
360 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
361 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
362 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
363 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
364 shouldLock, inTransaction);
368 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
369 log.debug("tosca artifact generation");
370 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
371 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
373 if (generated.isRight()) {
374 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
377 return Either.right(generated.right().value());
379 byte[] value = generated.left().value();
380 artifactInfo.setPayload(value);
384 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
385 if (exportComponent.isRight()) {
386 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
388 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
389 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
390 return Either.right(responseFormat);
392 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
393 String payload = exportComponent.left().value().getMainYaml();
394 artifactInfo.setPayloadData(payload);
396 return Either.left(Either.left(artifactInfo));
399 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
400 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
401 if (interfaceName != null && operationName != null) {
402 interfaceName = interfaceName.toLowerCase();
403 operationName = operationName.toLowerCase();
405 switch (operation.getArtifactOperationEnum()) {
407 if (artifactGenerationRequired(parent, artifactInfo)) {
408 return generateNotSavedArtifact(parent, artifactInfo);
410 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
412 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
414 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
415 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
416 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
417 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
418 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
419 if (needUpdateGroup && result.isLeft()) {
420 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
421 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
422 .value(), parent, componentType, componentId);
423 if (error != ActionStatus.OK) {
424 result = Either.right(componentsUtils.getResponseFormat(error));
429 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
430 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
433 if (result == null) {
434 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
435 if (needUpdateGroup && result.isLeft()) {
436 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
438 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
439 .value(), parent, componentType);
440 if (error != ActionStatus.OK) {
441 result = Either.right(componentsUtils.getResponseFormat(error));
447 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
449 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
454 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
455 List<GroupDefinition> groups = parent.getGroups();
456 if (groups != null && !groups.isEmpty()) {
457 List<GroupDataDefinition> groupToUpdate = groups.stream()
458 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
459 .contains(artifactInfo
461 .collect(Collectors.toList());
462 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
463 groupToUpdate.forEach(g -> {
464 g.getArtifacts().remove(artifactInfo.getUniqueId());
465 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
466 g.getArtifacts().add(artAfterUpdate.getUniqueId());
467 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
469 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
470 if (status.isRight()) {
471 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
472 return componentsUtils.convertFromStorageResponse(status.right().value());
476 return ActionStatus.OK;
479 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
480 List<GroupDefinition> groups = parent.getGroups();
481 if (groups != null && !groups.isEmpty()) {
482 List<GroupDataDefinition> groupToUpdate = groups.stream()
483 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
484 .contains(artifactInfoHeat
486 .collect(Collectors.toList());
487 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
488 groupToUpdate.forEach(g -> {
489 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
490 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
491 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
492 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
493 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
494 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
496 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
497 if (status.isRight()) {
498 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
499 return componentsUtils.convertFromStorageResponse(status.right().value());
503 return ActionStatus.OK;
506 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
507 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
508 List<GroupInstance> groupInstances = null;
509 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
511 .filter(ci -> ci.getUniqueId().equals(parentId))
513 if (componentInstOp.isPresent()) {
514 groupInstances = componentInstOp.get().getGroupInstances();
516 if (CollectionUtils.isNotEmpty(groupInstances)) {
517 boolean isUpdated = false;
518 for (GroupInstance groupInstance : groupInstances) {
520 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
521 .contains(artifactInfo
523 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
524 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
527 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
528 .contains(artifactInfo
529 .getArtifactUUID())) {
530 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
531 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
535 updatedGroupInstances.add(groupInstance);
539 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
540 if (status.isRight()) {
541 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
542 return componentsUtils.convertFromStorageResponse(status.right().value());
544 return ActionStatus.OK;
547 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
548 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
549 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
550 result = generateToscaArtifact(parent, artifactInfo, false, false);
553 String heatArtifactId = artifactInfo.getGeneratedFromId();
554 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
555 if (heatRes.isRight()) {
556 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
558 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
561 return Either.right(responseFormat);
563 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
564 artifactInfo.setPayloadData(generatedPayload);
565 result = Either.left(Either.left(artifactInfo));
570 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
571 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
572 convertParentType(componentType);
573 String parentId = parent.getUniqueId();
574 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
575 .getGeneratedFromId());
576 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
578 if (origMd5 != null) {
579 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
580 if (validateMd5.isRight()) {
581 ResponseFormat responseFormat = validateMd5.right().value();
582 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
583 return Either.right(responseFormat);
586 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
588 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
589 if (payloadEither.isRight()) {
590 ResponseFormat responseFormat = payloadEither.right().value();
591 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
592 return Either.right(responseFormat);
596 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
597 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
598 return Either.right(responseFormat);
604 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
605 if (lockComponent.isRight()) {
606 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
607 .value(), componentType, null);
608 return Either.right(lockComponent.right().value());
611 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
613 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
619 if (resultOp == null || resultOp.isRight()) {
620 log.debug("all changes rollback");
621 if (!inTransaction) {
626 log.debug("all changes committed");
627 if (!inTransaction) {
632 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
637 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
638 if (artifactGenerationRequired(component, csarArtifact)) {
639 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
641 if (generated.isRight()) {
642 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
645 return Either.right(generated.right().value());
647 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
650 return downloadArtifact(csarArtifact);
653 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
654 // perform all validation in common flow
655 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
656 null, parentId, containerComponentType);
657 if (result.isRight()) {
658 return Either.right(result.right().value());
660 ArtifactDefinition artifactDefinition;
661 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
662 if (insideValue.isLeft()) {
663 artifactDefinition = insideValue.left().value();
666 artifactDefinition = insideValue.right().value().getImplementationArtifact();
668 // for tosca artifacts and heat env on VF level generated on download without saving
669 if (artifactDefinition.getPayloadData() != null) {
670 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
673 return downloadArtifact(artifactDefinition);
676 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
678 // detect auditing type
679 Map<String, ArtifactDefinition> resMap = null;
680 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
685 if (userId == null) {
686 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
687 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
689 resultOp = Either.right(responseFormat);
693 // check user existence
697 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
698 if (userResult.isRight()) {
700 resultOp = Either.right(userResult.right().value());
704 userResult.left().value();
707 // 5. check service/resource existence
708 // 6. check service/resource check out
709 // 7. user is owner of checkout state
710 org.openecomp.sdc.be.model.Component component = null;
711 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
712 ComponentParametersView componentFilter = new ComponentParametersView();
713 componentFilter.disableAll();
714 componentFilter.setIgnoreArtifacts(false);
715 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
716 componentFilter.setIgnoreComponentInstances(false);
719 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
720 .findByParamName(containerComponentType), componentFilter);
722 if (validateComponent.isRight()) {
723 resultOp = Either.right(validateComponent.right().value());
726 component = validateComponent.left().value();
727 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
728 if (lockComponent.isRight()) {
730 resultOp = Either.right(lockComponent.right().value());
735 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
737 if (groupType == null) {
738 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
739 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
741 resultOp = Either.right(responseFormat);
745 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
746 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
747 if (list != null && !list.isEmpty()) {
748 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
751 resMap = new HashMap<>();
753 resultOp = Either.left(resMap);
758 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
759 .getNodeType(), groupType, componentId);
760 if (artifactsMapStatus.isRight()) {
761 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
762 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
763 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
764 resultOp = Either.right(responseFormat);
767 resMap = new HashMap<>();
768 resultOp = Either.left(resMap);
772 resMap = artifactsMapStatus.left().value();
773 resultOp = Either.left(resMap);
780 if (resultOp == null || resultOp.isRight()) {
781 log.debug("all changes rollback");
785 log.debug("all changes committed");
789 componentType = component.getComponentType();
790 NodeTypeEnum nodeType = componentType.getNodeType();
791 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
796 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
798 // check artifact existence
799 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
801 if (artifactResult.isRight()) {
802 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
803 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
804 log.debug("addArtifact - artifact {} not found", artifactId);
805 return Either.right(responseFormat);
809 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
812 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
814 return Either.right(responseFormat);
818 // check artifact belong to component
819 boolean found = false;
820 switch (componentType) {
823 found = checkArtifactInComponent(component, artifactId);
825 case RESOURCE_INSTANCE:
826 found = checkArtifactInResourceInstance(component, componentId, artifactId);
832 String componentName = componentType.name().toLowerCase();
833 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
834 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
835 return Either.right(responseFormat);
837 return Either.left(artifactResult.left().value());
840 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
841 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
843 String artifactId = null;
846 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
847 if (payloadEither.isRight()) {
848 return Either.right(payloadEither.right().value());
850 byte[] decodedPayload = payloadEither.left().value();
851 convertParentType(componentType);
854 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
855 if (lockComponent.isRight()) {
856 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
857 .value(), componentType, null);
858 return Either.right(lockComponent.right().value());
861 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
864 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
869 unlockComponent(resultOp, parent, inTransaction);
876 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
877 Component parent, boolean shouldLock, boolean inTransaction) {
880 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
881 if (lockComponent.isRight()) {
882 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
883 .value(), componentType, null);
884 return Either.right(lockComponent.right().value());
887 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
890 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
895 unlockComponent(resultOp, parent, inTransaction);
902 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
903 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
905 convertParentType(componentType);
909 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
911 if (lockComponent.isRight()) {
912 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
913 .value(), componentType, null);
914 return Either.right(lockComponent.right().value());
918 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
920 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
926 unlockComponent(resultOp, parent, inTransaction);
931 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
932 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
934 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
936 if (payloadEither.isRight()) {
937 return Either.right(payloadEither.right().value());
939 byte[] decodedPayload = payloadEither.left().value();
941 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
944 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
945 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
947 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
948 if (validateMd5.isRight()) {
949 ResponseFormat responseFormat = validateMd5.right().value();
950 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
951 return Either.right(responseFormat);
955 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
956 if (validateResult.isRight()) {
957 ResponseFormat responseFormat = validateResult.right().value();
958 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
959 return Either.right(validateResult.right().value());
962 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
963 if (payloadEither.isRight()) {
964 ResponseFormat responseFormat = payloadEither.right().value();
965 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
966 log.debug("Error during handle payload");
967 return Either.right(responseFormat);
970 // validate heat parameters. this part must be after the parameters are
971 // extracted in "handlePayload"
972 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
974 if (validateAndConvertHeatParamers.isRight()) {
975 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
976 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
977 log.debug("Error during handle payload");
978 return Either.right(responseFormat);
980 return payloadEither;
983 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
984 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
986 if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType()
987 .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
990 String artifactData = buildAuditingArtifactData(artifactDefinition);
994 user.setUserId("UNKNOWN");
996 switch (componentTypeEnum) {
998 Resource resource = (Resource) component;
999 if (resource == null) {
1000 // In that case, component ID should be instead of name
1001 resource = new Resource();
1002 resource.setName(componentId);
1004 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1005 ResourceAuditData.newBuilder()
1006 .artifactUuid(prevArtifactUuid)
1007 .build(), currentArtifactUuid, artifactData);
1011 Service service = (Service) component;
1012 if (service == null) {
1013 // In that case, component ID should be instead of name
1014 service = new Service();
1015 service.setName(componentId);
1017 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE,
1018 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1019 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1020 null, null, artifactData, null);
1023 case RESOURCE_INSTANCE:
1024 if (resourceInstanceName == null) {
1025 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1027 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE,
1028 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1029 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1030 resourceInstanceName, null, artifactData, null);
1037 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1038 ComponentInstance resourceInstance = component.getComponentInstances()
1040 .filter(p -> p.getUniqueId().equals(componentId))
1043 String resourceInstanceName = null;
1044 if (resourceInstance != null) {
1045 resourceInstanceName = resourceInstance.getName();
1047 return resourceInstanceName;
1050 public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
1051 Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1052 // Putting together artifact info
1053 String artifactData = buildAuditingArtifactData(artifactDefinition);
1054 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
1055 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
1056 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
1057 return auditingFields;
1062 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1063 StringBuilder sb = new StringBuilder();
1064 if (artifactDefinition != null) {
1065 sb.append(artifactDefinition.getArtifactGroupType().getType())
1068 .append(artifactDefinition.getArtifactLabel())
1071 .append(artifactDefinition.getArtifactType())
1073 .append(artifactDefinition.getArtifactName())
1075 .append(artifactDefinition.getTimeout())
1077 .append(artifactDefinition.getEsId());
1080 if (artifactDefinition.getArtifactVersion() != null) {
1082 sb.append(artifactDefinition.getArtifactVersion());
1088 if (artifactDefinition.getArtifactUUID() != null) {
1089 sb.append(artifactDefinition.getArtifactUUID());
1095 return sb.toString();
1098 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1100 if (origMd5 != null) {
1101 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1102 if (!encodeBase64Str.equals(origMd5)) {
1103 log.debug("The calculated md5 is different then the received one");
1104 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1108 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1109 log.debug("Missing md5 header during artifact create");
1110 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1113 if (payload != null && payload.length != 0) {
1114 log.debug("Cannot have payload while md5 header is missing");
1115 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1118 return Either.left(true);
1121 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1122 ComponentTypeEnum componentType, Component parentComponent) {
1124 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1125 if (artifactById.isRight()) {
1126 return Either.right(artifactById.right().value());
1128 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1130 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1131 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1132 if (validateInformationalArtifactRes.isRight()) {
1133 return Either.right(validateInformationalArtifactRes.right().value());
1135 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1136 if (validateAndSetArtifactname.isRight()) {
1137 return Either.right(validateAndSetArtifactname.right().value());
1139 if (operationName != null && interfaceName != null) {
1140 operationName = operationName.toLowerCase();
1141 interfaceName = interfaceName.toLowerCase();
1143 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1144 if (logicalNameStatus.isRight()) {
1145 return Either.right(logicalNameStatus.right().value());
1147 // This is a patch to block possibility of updating service api fields
1148 // through other artifacts flow
1150 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1151 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1152 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1155 checkCreateFields(user, artifactInfo, artifactGroupType);
1158 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1159 if (currentArtifactInfo != null) {
1160 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1163 // artifactGroupType is not allowed to be updated
1164 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1165 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1166 if (validateGroupType.isRight()) {
1167 return Either.right(validateGroupType.right().value());
1171 NodeTypeEnum parentType = convertParentType(componentType);
1174 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1176 if (isDeploymentArtifact(artifactInfo)) {
1177 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1178 if (deploymentValidationResult.isRight()) {
1179 return Either.right(deploymentValidationResult.right().value());
1183 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1186 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1187 if (descriptionResult.isRight()) {
1188 return Either.right(descriptionResult.right().value());
1191 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1192 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1193 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1194 if (validateServiceApiType.isRight()) {
1195 return Either.right(validateServiceApiType.right().value());
1197 // Change of type is not allowed and should be ignored
1199 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1201 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1202 if (validateUrl.isRight()) {
1203 return Either.right(validateUrl.right().value());
1206 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1207 if (validateUpdate.isRight()) {
1208 log.debug("serviceApi first update cnnot be without payload.");
1209 return Either.right(validateUpdate.right().value());
1213 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1214 if (validateArtifactType.isRight()) {
1215 return Either.right(validateArtifactType.right().value());
1217 if (artifactInfo.getApiUrl() != null) {
1218 artifactInfo.setApiUrl(null);
1219 log.error("Artifact URL cannot be set through this API - ignoring");
1222 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1223 artifactInfo.setServiceApi(false);
1224 log.error("Artifact service API flag cannot be changed - ignoring");
1228 return Either.left(artifactInfo);
1231 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1232 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1233 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1234 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1235 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1239 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1241 Either<ArtifactDefinition, ResponseFormat> result = null;
1242 ArtifactDefinition foundArtifact = null;
1243 if (StringUtils.isNotEmpty(artifactId)) {
1244 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1246 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1247 log.debug("Artifact {} already exist", artifactId);
1248 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1250 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1251 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1252 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1254 if (result == null) {
1255 result = Either.left(foundArtifact);
1260 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1261 ArtifactDefinition foundArtifact;
1262 if (parentComponent.getUniqueId().equals(parentId)) {
1263 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1266 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1267 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1269 return foundArtifact;
1272 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1273 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1274 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1275 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1276 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1277 if (artifactType == null) {
1278 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1279 .getArtifactType()));
1281 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1282 String artifactTypeName = artifactType.getType();
1283 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1284 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1286 .getResourceInformationalArtifacts();
1287 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1288 if (!validArtifactTypes.contains(artifactTypeName)) {
1289 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1292 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1293 .getValidForResourceTypes();
1294 if (!validResourceType.contains(parentResourceType.name())) {
1295 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1299 return validationResult;
1302 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1303 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1304 return NodeTypeEnum.Resource;
1306 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1307 return NodeTypeEnum.ResourceInstance;
1310 return NodeTypeEnum.Service;
1314 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1315 boolean shouldLock, boolean inTransaction) {
1317 NodeTypeEnum parentType = convertParentType(componentType);
1318 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1319 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1320 ArtifactDefinition foundArtifact = null;
1321 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1322 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1323 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1324 boolean isDuplicated = false;
1326 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1329 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1330 if (lockComponent.isRight()) {
1331 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1332 .value(), componentType, null);
1333 resultOp = Either.right(lockComponent.right().value());
1336 if (resultOp == null) {
1337 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1338 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1339 if (getContainerRes.isRight()) {
1340 log.debug("Failed to fetch the container component {}. ", parentId);
1341 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1343 .value()), artifactId);
1344 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1345 resultOp = Either.right(responseFormat);
1348 if (resultOp == null) {
1349 fetchedContainerComponent = getContainerRes.left().value();
1350 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1351 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1352 if (getArtifactRes.isRight()) {
1353 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1355 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1356 .value(), artifactId);
1357 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1358 resultOp = Either.right(responseFormat);
1361 foundArtifact = getArtifactRes.left().value().getLeft();
1362 esId = foundArtifact.getEsId();
1365 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1366 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1367 .getComponentType()));
1368 if (needCloneRes.isRight()) {
1369 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1370 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1372 .value()), foundArtifact.getArtifactDisplayName());
1373 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1374 resultOp = Either.right(responseFormat);
1377 boolean isNeedToDeleteArtifactFromDB = true;
1378 if (resultOp == null) {
1380 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1381 String instanceId = parentId;
1382 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1384 if (isOnlyResourceInstanceArtifact.isRight()) {
1385 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1386 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1387 .value(), foundArtifact
1388 .getArtifactDisplayName());
1389 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1390 return Either.right(responseFormat);
1392 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1395 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1398 if (updatedArtifactRes.isRight()) {
1399 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1400 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1402 .value()), foundArtifact.getArtifactDisplayName());
1403 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1404 resultOp = Either.right(responseFormat);
1407 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1411 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1412 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1413 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1414 if (cassandraStatus != CassandraOperationStatus.OK) {
1415 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1416 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1417 .getArtifactDisplayName());
1418 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1419 resultOp = Either.right(responseFormat);
1422 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1424 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1428 .getGroupInstances());
1429 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1430 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1431 if (status.isRight()) {
1432 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1433 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1435 .value()), foundArtifact.getArtifactDisplayName());
1436 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1437 resultOp = Either.right(responseFormat);
1441 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1442 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1443 if (status != StorageOperationStatus.OK) {
1444 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1445 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1446 .getArtifactDisplayName());
1447 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1448 resultOp = Either.right(responseFormat);
1451 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1452 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1454 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1455 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1456 if (status.isRight()) {
1457 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1458 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1460 .value()), foundArtifact.getArtifactDisplayName());
1461 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1462 resultOp = Either.right(responseFormat);
1466 if (resultOp == null) {
1467 resultOp = Either.left(Either.left(foundArtifact));
1468 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1474 unlockComponent(resultOp, parent, inTransaction);
1479 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1480 Either<Boolean, ActionStatus> result = Either.left(true);
1481 ComponentInstance foundInstance = null;
1482 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1484 .filter(i -> i.getUniqueId().equals(instanceId))
1486 if (!componentInstanceOpt.isPresent()) {
1487 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1490 foundInstance = componentInstanceOpt.get();
1491 String componentUid = foundInstance.getComponentUid();
1492 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1493 if (getContainerRes.isRight()) {
1494 log.debug("Failed to fetch the container component {}. ", componentUid);
1495 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1497 Component origComponent = getContainerRes.left().value();
1498 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1499 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1500 Optional<String> op = deploymentArtifacts.keySet()
1502 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1504 if (op.isPresent()) {
1505 return Either.left(false);
1508 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1509 if (artifacts != null && !artifacts.isEmpty()) {
1510 Optional<String> op = artifacts.keySet()
1512 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1514 if (op.isPresent()) {
1515 return Either.left(false);
1523 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1524 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1525 boolean isUpdated = false;
1526 if (groups != null) {
1527 for (GroupDefinition group : groups) {
1529 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1530 group.getArtifacts().remove(artifactId);
1533 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1534 .contains(foundArtifact.getArtifactUUID())) {
1535 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1539 updatedGroups.add(group);
1543 return updatedGroups;
1546 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1547 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1548 if (CollectionUtils.isNotEmpty(groupInstances)) {
1549 boolean isUpdated = false;
1550 for (GroupInstance groupInstance : groupInstances) {
1552 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1553 .contains(artifactId)) {
1554 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1557 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1558 .contains(foundArtifact
1559 .getArtifactUUID())) {
1560 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1564 updatedGroupInstances.add(groupInstance);
1568 return updatedGroupInstances;
1571 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1573 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1574 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1575 String componentId = component.getUniqueId();
1576 String instanceId = componentId.equals(parentId) ? null : parentId;
1578 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1579 resetMandatoryArtifactFields(foundArtifact);
1580 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1582 else if (cloneIsNeeded) {
1583 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1584 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1587 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1588 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1593 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1595 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1596 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1597 ComponentInstance foundInstance = null;
1598 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1599 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1601 .filter(i -> i.getUniqueId()
1604 if (!componentInstanceOpt.isPresent()) {
1605 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1608 foundInstance = componentInstanceOpt.get();
1609 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1613 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1615 if (result == null) {
1616 if (artifacts.containsKey(artifactId)) {
1617 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1620 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1626 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1627 Map<String, ArtifactDefinition> currArtifacts;
1628 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1629 currArtifacts = component.getDeploymentArtifacts()
1632 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1633 if (MapUtils.isNotEmpty(currArtifacts)) {
1634 artifacts.putAll(currArtifacts);
1637 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1638 currArtifacts = component.getArtifacts()
1641 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1642 if (MapUtils.isNotEmpty(currArtifacts)) {
1643 artifacts.putAll(currArtifacts);
1646 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1647 currArtifacts = component.getToscaArtifacts()
1650 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1651 if (MapUtils.isNotEmpty(currArtifacts)) {
1652 artifacts.putAll(currArtifacts);
1657 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1658 Map<String, ArtifactDefinition> currArtifacts;
1659 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1660 currArtifacts = instance.getDeploymentArtifacts()
1663 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1664 if (MapUtils.isNotEmpty(currArtifacts)) {
1665 artifacts.putAll(currArtifacts);
1668 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1669 currArtifacts = instance.getArtifacts()
1672 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1673 if (MapUtils.isNotEmpty(currArtifacts)) {
1674 artifacts.putAll(currArtifacts);
1679 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1680 StorageOperationStatus result;
1681 switch (cassandraStatus) {
1683 result = StorageOperationStatus.OK;
1686 result = StorageOperationStatus.NOT_FOUND;
1688 case CLUSTER_NOT_CONNECTED:
1689 case KEYSPACE_NOT_CONNECTED:
1690 result = StorageOperationStatus.CONNECTION_FAILURE;
1693 result = StorageOperationStatus.GENERAL_ERROR;
1699 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1700 if (fetchedArtifact != null) {
1701 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1702 fetchedArtifact.setEsId(null);
1703 fetchedArtifact.setArtifactName(null);
1704 fetchedArtifact.setDescription(null);
1705 fetchedArtifact.setApiUrl(null);
1706 fetchedArtifact.setArtifactChecksum(null);
1707 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1708 fetchedArtifact.setArtifactUUID(null);
1709 long time = System.currentTimeMillis();
1710 fetchedArtifact.setPayloadUpdateDate(time);
1711 fetchedArtifact.setHeatParameters(null);
1712 fetchedArtifact.setHeatParamsUpdateDate(null);
1716 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1717 StorageOperationStatus error = StorageOperationStatus.OK;
1718 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1719 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1720 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1725 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1727 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1729 if (artifactById.isRight()) {
1730 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1731 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1732 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1733 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1734 return Either.right(responseFormat);
1736 ArtifactDefinition artifactDefinition = artifactById.left().value();
1737 if (artifactDefinition == null) {
1738 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1739 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1740 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1741 return Either.right(responseFormat);
1744 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1745 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1746 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1747 return Either.left(insideEither);
1750 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1751 ComponentTypeEnum componentType) {
1753 String artifactLabel = artifactInfo.getArtifactLabel();
1754 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1756 BeEcompErrorManager.getInstance()
1757 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1758 log.debug("missing artifact logical name for component {}", componentId);
1759 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1761 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1763 if (operationName != null) {
1764 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1765 log.debug("artifact label cannot be set {}", artifactLabel);
1766 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1769 artifactLabel = operationName;
1772 String displayName = artifactInfo.getArtifactDisplayName();
1773 if (displayName == null || displayName.isEmpty()) {
1774 displayName = artifactLabel;
1776 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1777 artifactInfo.setArtifactDisplayName(displayName);
1779 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1780 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1781 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1783 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1785 if (artifactLabel.isEmpty()) {
1786 log.debug("missing normalized artifact logical name for component {}", componentId);
1787 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1790 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1791 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1792 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1793 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1795 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1796 log.debug("Non unique Artifact label : {}", artifactLabel);
1797 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1800 artifactInfo.setArtifactLabel(artifactLabel);
1802 return Either.left(ActionStatus.OK);
1805 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1806 boolean isUnique = true;
1807 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1808 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1809 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1812 artifacts = artifactToscaOperation.getArtifacts(componentId);
1815 if (artifacts.isLeft()) {
1816 for (String label : artifacts.left().value().keySet()) {
1817 if (label.equals(artifactLabel)) {
1823 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1824 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1825 .getAllInterfacesOfResource(componentId, true, true);
1826 if (allInterfacesOfResource.isLeft()) {
1827 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1828 for (Operation operation : interace.getOperationsMap().values()) {
1829 if (operation.getImplementation() != null && operation.getImplementation()
1831 .equals(artifactLabel)) {
1842 // ***************************************************************
1844 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1845 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1846 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1847 Either<ArtifactDefinition, Operation> insideEither = null;
1848 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1849 String instanceId = null;
1850 String instanceName = null;
1851 if (foundInstance != null) {
1852 instanceId = foundInstance.getUniqueId();
1853 instanceName = foundInstance.getName();
1855 boolean isLeft = false;
1856 String artifactUniqueId = null;
1857 StorageOperationStatus error = null;
1858 // information/deployment/api aritfacts
1859 log.trace("Try to create entry on graph");
1860 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1861 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1862 .getUniqueId(), nodeType, true, instanceId);
1864 isLeft = result.isLeft();
1866 artifactUniqueId = result.left().value().getUniqueId();
1867 result.left().value();
1869 insideEither = Either.left(result.left().value());
1870 resultOp = Either.left(insideEither);
1872 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1873 if (error != StorageOperationStatus.OK) {
1879 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1880 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1884 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1885 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1886 .getArtifactDisplayName());
1887 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1888 resultOp = Either.right(responseFormat);
1894 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1895 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1897 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1898 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1899 Either<ArtifactDefinition, Operation> insideEither = null;
1900 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1901 String instanceId = null;
1902 String instanceName = null;
1903 if (foundInstance != null) {
1904 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1905 log.debug("Failed to create artifact, already exists");
1906 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1907 .getArtifactLabel());
1908 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1910 resultOp = Either.right(responseFormat);
1914 instanceId = foundInstance.getUniqueId();
1915 instanceName = foundInstance.getName();
1917 if (artifactData == null) {
1918 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1919 log.debug("Failed to create artifact object for ES.");
1920 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1921 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1922 resultOp = Either.right(responseFormat);
1926 // set on graph object id of artifact in ES!
1927 artifactInfo.setEsId(artifactData.getId());
1929 boolean isLeft = false;
1930 String artifactUniqueId = null;
1931 StorageOperationStatus error = null;
1932 if (interfaceType != null && operationName != null) {
1933 // lifecycle artifact
1934 Operation operation = convertToOperation(artifactInfo, operationName);
1936 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1938 isLeft = result.isLeft();
1940 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1941 result.left().value().getImplementation();
1943 insideEither = Either.right(result.left().value());
1944 resultOp = Either.left(insideEither);
1947 error = result.right().value();
1951 // information/deployment/api aritfacts
1952 log.trace("Try to create entry on graph");
1953 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1954 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1955 .getUniqueId(), nodeType, true, instanceId);
1957 isLeft = result.isLeft();
1959 artifactUniqueId = result.left().value().getUniqueId();
1960 artifactData.setId(result.left().value().getEsId());
1961 insideEither = Either.left(result.left().value());
1962 resultOp = Either.left(insideEither);
1964 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1965 if (error != StorageOperationStatus.OK) {
1971 error = result.right().value();
1975 boolean res = saveArtifacts(artifactData, parentId);
1978 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1980 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1981 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1985 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1986 log.debug("Failed to save the artifact.");
1987 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1988 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1990 resultOp = Either.right(responseFormat);
1995 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1996 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1997 .getArtifactDisplayName());
1998 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1999 resultOp = Either.right(responseFormat);
2005 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2006 ComponentInstance foundInstance = null;
2007 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2008 foundInstance = containerComponent.getComponentInstances()
2010 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2014 return foundInstance;
2017 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2019 Either<Boolean, ResponseFormat> result = Either.left(true);
2020 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
2022 validateArtifactTypeExists(responseWrapper, artifactInfo);
2024 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2026 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2028 if (responseWrapper.isEmpty()) {
2029 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2032 // Common code for all types
2033 // not allowed to change artifactType
2034 if (responseWrapper.isEmpty() && !isCreate) {
2035 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2036 if (validateServiceApiType.isRight()) {
2037 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2040 if (responseWrapper.isEmpty()) {
2041 if (parentType.equals(NodeTypeEnum.Resource)) {
2042 Resource resource = (Resource) parentComponent;
2043 ResourceTypeEnum resourceType = resource.getResourceType();
2044 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2045 if (config == null) {
2046 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2047 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2048 .getArtifactType()));
2051 List<String> myList = config.getValidForResourceTypes();
2052 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2053 if (either.isRight()) {
2054 responseWrapper.setInnerElement(either.right().value());
2059 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2062 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2063 String artifactName = artifactInfo.getArtifactName();
2064 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2065 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2069 if (responseWrapper.isEmpty()) {
2070 switch (artifactType) {
2074 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2077 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2078 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2080 case DCAE_INVENTORY_TOSCA:
2081 case DCAE_INVENTORY_JSON:
2082 case DCAE_INVENTORY_POLICY:
2083 // Validation is done in handle payload.
2084 case DCAE_INVENTORY_DOC:
2085 case DCAE_INVENTORY_BLUEPRINT:
2086 case DCAE_INVENTORY_EVENT:
2087 // No specific validation
2089 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2095 if (!responseWrapper.isEmpty()) {
2096 result = Either.right(responseWrapper.getInnerElement());
2101 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2102 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2103 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2104 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2105 .getArtifactType());
2106 responseWrapper.setInnerElement(responseFormat);
2107 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2111 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2112 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2113 if (parentType.equals(NodeTypeEnum.Resource)) {
2114 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2116 .getResourceDeploymentArtifacts();
2118 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2119 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2121 .getResourceInstanceDeploymentArtifacts();
2124 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2126 .getServiceDeploymentArtifacts();
2128 return resourceDeploymentArtifacts;
2131 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2132 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2133 if (artifactType == null) {
2134 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2135 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2136 .getArtifactType());
2137 responseWrapper.setInnerElement(responseFormat);
2138 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2142 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2143 ArtifactTypeConfig retConfig = null;
2144 String fileType = artifactType.getType();
2145 if (parentType.equals(NodeTypeEnum.Resource)) {
2146 retConfig = ConfigurationManager.getConfigurationManager()
2148 .getResourceDeploymentArtifacts()
2151 else if (parentType.equals(NodeTypeEnum.Service)) {
2152 retConfig = ConfigurationManager.getConfigurationManager()
2154 .getServiceDeploymentArtifacts()
2157 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2158 retConfig = ConfigurationManager.getConfigurationManager()
2160 .getResourceInstanceDeploymentArtifacts()
2166 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2167 // extract heat parameters
2168 if (artifactInfo.getPayloadData() != null) {
2169 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2170 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2171 .getArtifactType());
2172 if (heatParameters.isRight() && (!heatParameters.right()
2174 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2175 log.info("failed to parse heat parameters ");
2176 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2177 .getArtifactType());
2178 return Either.right(responseFormat);
2180 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2181 artifactInfo.setListHeatParameters(heatParameters.left().value());
2184 return Either.left(true);
2189 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2190 String fileType = artifactType.getType();
2191 List<String> acceptedTypes = null;
2192 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2193 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2194 log.debug("parent type of artifact can be either resource or service");
2195 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2199 if (deploymentAcceptedTypes == null) {
2200 log.debug("parent type of artifact can be either resource or service");
2201 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2202 .getArtifactType()));
2206 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2209 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2212 String artifactName = artifactInfo.getArtifactName();
2213 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2214 // Pavel - File extension validation is case-insensitive - Ella,
2216 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2217 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2218 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2223 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2225 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
2226 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
2227 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2229 if (errorWrapper.isEmpty()) {
2230 validateValidYaml(errorWrapper, artifactInfo);
2233 if (errorWrapper.isEmpty()) {
2234 // Validate Heat Exist
2235 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2236 .getComponentType());
2239 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2240 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2243 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2244 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2248 Either<Boolean, ResponseFormat> eitherResponse;
2249 if (errorWrapper.isEmpty()) {
2250 eitherResponse = Either.left(true);
2253 eitherResponse = Either.right(errorWrapper.getInnerElement());
2255 return eitherResponse;
2258 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2259 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2260 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2261 if (fillArtifactPayload.isRight()) {
2262 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2263 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2267 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2271 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2272 Either<Boolean, ResponseFormat> result = Either.left(true);
2273 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2275 if (eitherArtifactData.isLeft()) {
2276 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2277 data = Base64.encodeBase64(data);
2278 payloadWrapper.setInnerElement(data);
2281 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2284 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2285 result = Either.right(responseFormat);
2291 @SuppressWarnings("unchecked")
2292 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2293 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2294 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2295 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2296 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2298 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2299 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2300 if (eitherHeatEnvProperties.isRight()) {
2301 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2302 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2303 errorWrapper.setInnerElement(responseFormat);
2304 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2306 else if (eitherHeatProperties.isRight()) {
2307 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2308 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2309 .getArtifactName(), heatArtifact.getArtifactName());
2310 errorWrapper.setInnerElement(responseFormat);
2311 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2312 .getArtifactName());
2315 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2316 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2317 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2318 if (!heatEnvPropertiesKeys.isEmpty()) {
2319 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2320 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2321 .getArtifactName(), heatArtifact.getArtifactName());
2322 errorWrapper.setInnerElement(responseFormat);
2327 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2328 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2329 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2331 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2332 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2333 .getArtifactType());
2334 errorWrapper.setInnerElement(responseFormat);
2335 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2339 private boolean isValidXml(byte[] xmlToParse) {
2340 boolean isXmlValid = true;
2342 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2343 setFeatures(reader);
2344 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2346 catch (ParserConfigurationException | IOException | SAXException e) {
2347 log.debug("Xml is invalid : {}", e.getMessage(), e);
2353 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2355 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2356 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2358 catch (SAXNotRecognizedException e) {
2359 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2363 private boolean isValidJson(byte[] jsonToParse) {
2364 String parsed = new String(jsonToParse);
2366 gson.fromJson(parsed, Object.class);
2368 catch (Exception e) {
2369 log.debug("Json is invalid : {}", e.getMessage(), e);
2375 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2376 boolean artifactNameFound = false;
2377 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2380 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2381 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2383 if (artifactNameFound) {
2384 String parentName = parentComponent.getName();
2385 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2386 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2387 .name(), parentName, artifactName);
2389 errorWrapper.setInnerElement(responseFormat);
2390 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2395 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2396 ComponentTypeEnum componentType) {
2397 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2398 if (res.isRight()) {
2399 ResponseFormat responseFormat;
2400 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2401 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2404 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2406 errorWrapper.setInnerElement(responseFormat);
2409 ArtifactDefinition heatArtifact = res.left().value();
2410 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2413 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2414 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2415 // timeout > 0 for HEAT artifacts
2416 Integer timeout = artifactInfo.getTimeout();
2417 if (timeout == null) {
2418 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2419 artifactInfo.setTimeout(defaultTimeout);
2420 // HEAT artifact but timeout is invalid
2422 else if (timeout < 1) {
2423 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2426 // US649856 - Allow several HEAT files on Resource
2427 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2428 return Either.left(true);
2431 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2432 String listToString = (typeList != null) ? typeList.toString() : "";
2433 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2434 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2435 .getArtifactName(), listToString, resourceType.getValue());
2436 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2437 String resourceTypeName = resourceType.name();
2438 if (typeList != null && typeList.contains(resourceTypeName)) {
2439 either = Either.left(true);
2444 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2445 if (artifactInfo.getHeatParameters() != null) {
2446 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2447 String parameterType = heatParam.getType();
2448 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2449 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2450 if (heatParameterType == null) {
2451 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2453 return Either.right(responseFormat);
2456 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2457 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2458 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2459 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2460 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2461 .getType(), heatParam.getName());
2462 return Either.right(responseFormat);
2466 return Either.left(artifactInfo);
2469 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2470 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2471 if (parentComponent.getDeploymentArtifacts() != null) {
2472 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2473 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2474 if (getRI.isRight()) {
2475 return deploymentArtifacts;
2477 ComponentInstance ri = getRI.left().value();
2478 if (ri.getDeploymentArtifacts() != null) {
2479 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2482 else if (parentComponent.getDeploymentArtifacts() != null) {
2483 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2486 return deploymentArtifacts;
2489 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2490 // on create if null add informational to current
2491 if (artifactInfo.getArtifactGroupType() == null) {
2492 artifactInfo.setArtifactGroupType(type);
2494 if (artifactInfo.getUniqueId() != null) {
2495 log.error("artifact uniqid cannot be set ignoring");
2497 artifactInfo.setUniqueId(null);
2499 if (artifactInfo.getArtifactRef() != null) {
2500 log.error("artifact ref cannot be set ignoring");
2502 artifactInfo.setArtifactRef(null);
2504 if (artifactInfo.getArtifactRepository() != null) {
2505 log.error("artifact repository cannot be set ignoring");
2507 artifactInfo.setArtifactRepository(null);
2509 if (artifactInfo.getUserIdCreator() != null) {
2510 log.error("creator uuid cannot be set ignoring");
2512 artifactInfo.setArtifactCreator(user.getUserId());
2514 if (artifactInfo.getUserIdLastUpdater() != null) {
2515 log.error("userId of last updater cannot be set ignoring");
2517 artifactInfo.setUserIdLastUpdater(user.getUserId());
2519 if (artifactInfo.getCreatorFullName() != null) {
2520 log.error("creator Full name cannot be set ignoring");
2522 String fullName = user.getFirstName() + " " + user.getLastName();
2523 artifactInfo.setUpdaterFullName(fullName);
2525 if (artifactInfo.getUpdaterFullName() != null) {
2526 log.error("updater Full name cannot be set ignoring");
2528 artifactInfo.setUpdaterFullName(fullName);
2530 if (artifactInfo.getCreationDate() != null) {
2531 log.error("Creation Date cannot be set ignoring");
2533 long time = System.currentTimeMillis();
2534 artifactInfo.setCreationDate(time);
2536 if (artifactInfo.getLastUpdateDate() != null) {
2537 log.error("Last Update Date cannot be set ignoring");
2539 artifactInfo.setLastUpdateDate(time);
2541 if (artifactInfo.getEsId() != null) {
2542 log.error("es id cannot be set ignoring");
2544 artifactInfo.setEsId(null);
2549 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2550 String id = artifactId;
2551 if (artifactId == null || artifactId.isEmpty()) {
2552 String uniqueId = null;
2553 if (interfaceName != null && operationName != null) {
2554 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2555 .getArtifactLabel());
2558 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2560 artifactInfo.setUniqueId(uniqueId);
2561 artifactInfo.setEsId(uniqueId);
2565 artifactInfo.setUniqueId(artifactId);
2566 artifactInfo.setEsId(artifactId);
2571 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2572 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2573 BeEcompErrorManager.getInstance()
2574 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2575 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2579 boolean artifactTypeExist = false;
2580 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2581 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2583 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2584 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2588 allArtifactTypes = elementOperation.getAllArtifactTypes();
2590 if (allArtifactTypes.isRight()) {
2591 BeEcompErrorManager.getInstance()
2592 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2596 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2598 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2601 for (ArtifactType type : allArtifactTypes.left().value()) {
2602 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2603 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2604 artifactTypeExist = true;
2609 if (!artifactTypeExist) {
2610 BeEcompErrorManager.getInstance()
2611 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2612 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2613 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2614 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2615 .getArtifactType()));
2618 return Either.left(ActionStatus.OK);
2621 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2623 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2624 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2626 if (parentType.equals(NodeTypeEnum.Service)) {
2627 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2629 .getServiceDeploymentArtifacts();
2631 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2632 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2634 .getResourceInstanceDeploymentArtifacts();
2637 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2639 .getResourceDeploymentArtifacts();
2641 if (deploymentArtifacts != null) {
2642 for (String artifactType : deploymentArtifacts.keySet()) {
2643 ArtifactType artifactT = new ArtifactType();
2644 artifactT.setName(artifactType);
2645 artifactTypes.add(artifactT);
2647 return Either.left(artifactTypes);
2650 return Either.right(ActionStatus.GENERAL_ERROR);
2655 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2656 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2657 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2659 return Either.left(true);
2663 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2664 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2665 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2668 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2669 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2670 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2672 artifactInfo.setArtifactName(normalizeFileName);
2674 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2675 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2678 return Either.left(true);
2681 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2682 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2683 log.info("artifact type is missing operation ignored");
2684 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2687 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2688 log.info("artifact type cannot be changed operation ignored");
2689 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2691 return Either.left(true);
2694 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2695 if (artifactInfo.getArtifactGroupType() == null) {
2696 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2699 else if (!currentArtifact.getArtifactGroupType()
2701 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2702 log.info("artifact group type cannot be changed. operation failed");
2703 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2705 return Either.left(artifactInfo);
2708 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2710 // on update if null add informational to current
2711 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2712 currentArtifact.setArtifactGroupType(type);
2715 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2716 log.error("artifact uniqid cannot be set ignoring");
2718 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2720 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2721 .equals(artifactInfo.getArtifactRef())) {
2722 log.error("artifact ref cannot be set ignoring");
2724 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2726 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2727 .equals(artifactInfo.getArtifactRepository())) {
2728 log.error("artifact repository cannot be set ignoring");
2730 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2732 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2733 .equals(artifactInfo.getUserIdCreator())) {
2734 log.error("creator uuid cannot be set ignoring");
2736 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2738 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2739 .equals(artifactInfo.getArtifactCreator())) {
2740 log.error("artifact creator cannot be set ignoring");
2742 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2744 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2745 .equals(artifactInfo.getUserIdLastUpdater())) {
2746 log.error("userId of last updater cannot be set ignoring");
2748 artifactInfo.setUserIdLastUpdater(user.getUserId());
2750 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2751 .equals(artifactInfo.getCreatorFullName())) {
2752 log.error("creator Full name cannot be set ignoring");
2754 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2756 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2757 .equals(artifactInfo.getUpdaterFullName())) {
2758 log.error("updater Full name cannot be set ignoring");
2760 String fullName = user.getFirstName() + " " + user.getLastName();
2761 artifactInfo.setUpdaterFullName(fullName);
2763 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2764 .equals(artifactInfo.getCreationDate())) {
2765 log.error("Creation Date cannot be set ignoring");
2767 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2769 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2770 .equals(artifactInfo.getLastUpdateDate())) {
2771 log.error("Last Update Date cannot be set ignoring");
2773 long time = System.currentTimeMillis();
2774 artifactInfo.setLastUpdateDate(time);
2776 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2777 log.error("es id cannot be set ignoring");
2779 artifactInfo.setEsId(currentArtifact.getUniqueId());
2781 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2782 .equals(artifactInfo.getArtifactDisplayName())) {
2783 log.error(" Artifact Display Name cannot be set ignoring");
2785 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2787 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2788 .equals(artifactInfo.getServiceApi())) {
2789 log.debug("serviceApi cannot be set. ignoring.");
2791 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2793 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2794 .equals(artifactInfo.getArtifactGroupType())) {
2795 log.debug("artifact group cannot be set. ignoring.");
2797 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2799 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2801 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2802 .isEmpty() && !currentArtifact.getArtifactUUID()
2803 .equals(artifactInfo.getArtifactUUID())) {
2804 log.debug("artifact UUID cannot be set. ignoring.");
2806 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2808 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2809 .getHeatParameters()
2810 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2811 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2815 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2817 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2818 for (HeatParameterDefinition parameter : heatParameters) {
2819 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2821 if (currentParam != null) {
2823 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2824 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2825 parameter.setName(currentParam.getName());
2827 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2828 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2829 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2830 parameter.setDefaultValue(currentParam.getDefaultValue());
2832 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2833 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2834 parameter.setType(currentParam.getType());
2836 if (parameter.getDescription() != null && !parameter.getDescription()
2837 .equalsIgnoreCase(currentParam.getDescription())) {
2838 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2839 parameter.setDescription(currentParam.getDescription());
2842 // check and set current value
2843 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2844 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2845 parameter.setCurrentValue(currentParam.getDefaultValue());
2851 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2853 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2854 for (HeatParameterDefinition param : currentParameters) {
2855 currentParamsMap.put(param.getUniqueId(), param);
2857 return currentParamsMap;
2860 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2861 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2862 log.debug("Artifact url cannot be empty.");
2863 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2865 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2867 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2868 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2870 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2871 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2874 return Either.left(true);
2877 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2878 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2879 log.debug("Artifact description cannot be empty.");
2880 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2882 String description = artifactInfo.getDescription();
2883 description = ValidationUtils.removeNoneUtf8Chars(description);
2884 description = ValidationUtils.normaliseWhitespace(description);
2885 description = ValidationUtils.stripOctets(description);
2886 description = ValidationUtils.removeHtmlTagsOnly(description);
2887 if (!ValidationUtils.validateIsEnglish(description)) {
2888 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2890 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2891 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2892 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2894 artifactInfo.setDescription(description);
2895 return Either.left(true);
2898 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2899 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2900 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2901 String prevArtifactId = null;
2902 String currArtifactId = artifactId;
2904 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2905 Either<ArtifactDefinition, Operation> insideEither = null;
2907 if (artifactData == null) {
2908 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2909 log.debug("Failed to create artifact object for ES.");
2910 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2911 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2912 resultOp = Either.right(responseFormat);
2915 log.trace("Try to update entry on graph");
2916 String artifactUniqueId = null;
2917 ArtifactDefinition artifactDefinition = artifactInfo;
2918 StorageOperationStatus error;
2921 if (!(interfaceType != null && operationName != null)) {
2922 log.debug("Enty on graph is updated. Update artifact in ES");
2924 // Changing previous and current artifactId for auditing
2925 prevArtifactId = currArtifactId;
2926 currArtifactId = artifactDefinition.getUniqueId();
2928 NodeTypeEnum convertParentType = convertParentType(componentType);
2930 if (decodedPayload == null) {
2931 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2932 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2934 if (artifactFromCassandra.isRight()) {
2935 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2936 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2938 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2939 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2940 resultOp = Either.right(responseFormat);
2943 // clone data to new artifact
2944 artifactData.setData(artifactFromCassandra.left().value().getData());
2945 artifactData.setId(artifactFromCassandra.left().value().getId());
2949 if (artifactDefinition.getEsId() == null) {
2950 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2951 artifactData.setId(artifactDefinition.getUniqueId());
2955 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent
2956 .getUniqueId(), artifactId, convertParentType, parentId);
2957 isLeft = result.isLeft();
2959 artifactUniqueId = result.left().value().getUniqueId();
2960 artifactDefinition = result.left().value();
2961 String artifactType = artifactInfo.getArtifactType();
2962 if (NodeTypeEnum.Resource == convertParentType
2963 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
2964 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
2965 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
2966 && !artifactUniqueId.equals(artifactId)) {
2967 // need to update the generated id in heat env
2968 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2969 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
2971 .filter(a -> a.getValue()
2972 .getGeneratedFromId() != null && a
2974 .getGeneratedFromId()
2975 .equals(artifactId))
2977 if (findFirst.isPresent()) {
2978 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2979 artifactEnvInfo.setArtifactChecksum(null);
2980 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2983 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2985 insideEither = Either.left(result.left().value());
2986 resultOp = Either.left(insideEither);
2987 if (error != StorageOperationStatus.OK) {
2993 error = result.right().value();
2997 // create new entry in ES
2999 if (artifactData.getData() != null) {
3000 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3001 artifactData.setId(artifactDefinition.getEsId());
3003 res = saveArtifacts(artifactData, parentId);
3009 log.debug("Artifact saved into ES - {}", artifactUniqueId);
3010 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3011 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3014 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3015 log.debug("Failed to save the artifact.");
3016 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3017 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3018 resultOp = Either.right(responseFormat);
3025 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3026 log.trace("Starting payload handling");
3027 byte[] payload = artifactInfo.getPayloadData();
3028 byte[] decodedPayload = null;
3030 if (payload != null && payload.length != 0) {
3031 // the generated artifacts were already decoded by the handler
3032 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3033 if (decodedPayload.length == 0) {
3034 log.debug("Failed to decode the payload.");
3035 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3036 return Either.right(responseFormat);
3039 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3040 artifactInfo.setArtifactChecksum(checkSum);
3041 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3043 // Specific payload validations of different types
3044 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3045 if (isDeploymentArtifact(artifactInfo)) {
3046 log.trace("Starting deployment artifacts payload validation");
3047 String artifactType = artifactInfo.getArtifactType();
3048 if (ArtifactTypeEnum.HEAT.getType()
3049 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3050 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3052 .equalsIgnoreCase(artifactType)
3053 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3054 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3055 if (isValidPayload.isLeft()) {
3056 isValidPayload = extractHeatParameters(artifactInfo);
3059 else if (ArtifactTypeEnum.YANG_XML.getType()
3060 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3061 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3063 .equalsIgnoreCase(artifactType)
3064 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3065 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3067 .equalsIgnoreCase(artifactType)
3068 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3069 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3071 .equalsIgnoreCase(artifactType)) {
3072 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3074 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3075 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3077 .equalsIgnoreCase(artifactType)
3078 || ArtifactTypeEnum.VES_EVENTS.getType()
3079 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3081 .equalsIgnoreCase(artifactType)) {
3082 String artifactFileName = artifactInfo.getArtifactName();
3083 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3084 switch (fileExtension) {
3086 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3089 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3093 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3100 if (isValidPayload.isRight()) {
3101 ResponseFormat responseFormat = isValidPayload.right().value();
3102 return Either.right(responseFormat);
3105 } // null/empty payload is normal if called from metadata update ONLY.
3106 // The validation of whether this is metadata/payload update case is
3107 // currently done separately
3109 if (!isArtifactMetadataUpdate) {
3110 log.debug("Payload is missing.");
3111 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3112 return Either.right(responseFormat);
3115 log.trace("Ended payload handling");
3116 return Either.left(decodedPayload);
3119 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3120 // Basic YAML validation
3121 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3122 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3123 log.debug("Invalid YAML format");
3124 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3125 return Either.right(responseFormat);
3127 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3128 // HEAT specific YAML validation
3129 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3130 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3131 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3132 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3133 return Either.right(responseFormat);
3137 return Either.left(true);
3140 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3141 Either<Boolean, ResponseFormat> res = Either.left(true);
3142 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3143 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3144 log.debug("Invalid YAML format");
3145 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3146 res = Either.right(responseFormat);
3152 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3153 boolean isXmlValid = isValidXml(payload);
3155 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3156 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3157 log.debug("Invalid XML content");
3158 return Either.right(responseFormat);
3160 return Either.left(true);
3163 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3164 boolean isJsonValid = isValidJson(payload);
3166 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3167 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3168 log.debug("Invalid JSON content");
3169 return Either.right(responseFormat);
3171 return Either.left(true);
3174 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3175 boolean inTransaction) {
3176 User user = new User();
3177 user.setUserId(userUserId);
3178 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3179 if (parent.isRight()) {
3180 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3183 return Either.right(responseFormat);
3185 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3188 false, inTransaction);
3189 if (handleDelete.isRight()) {
3190 return Either.right(handleDelete.right().value());
3192 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3193 return Either.left(result.right().value());
3197 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3198 Operation op = new Operation();
3199 long time = System.currentTimeMillis();
3200 op.setCreationDate(time);
3202 String artifactName = artifactInfo.getArtifactName();
3203 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3205 op.setImplementation(artifactInfo);
3206 op.setLastUpdateDate(time);
3210 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3211 String newArtifactName = operationName + "_" + artifactName;
3212 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3213 return newArtifactName;
3217 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3219 // General validation
3220 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3221 log.debug("One of the function parameteres is null");
3222 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3225 // Normalizing artifact name
3226 artifactName = ValidationUtils.normalizeFileName(artifactName);
3228 // Resource validation
3229 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3230 if (validateResourceNameAndVersion.isRight()) {
3231 return Either.right(validateResourceNameAndVersion.right().value());
3234 Resource resource = validateResourceNameAndVersion.left().value();
3235 String resourceId = resource.getUniqueId();
3237 // Service validation
3238 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3239 if (validateServiceNameAndVersion.isRight()) {
3240 return Either.right(validateServiceNameAndVersion.right().value());
3243 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3244 if (artifacts == null || artifacts.isEmpty()) {
3245 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3246 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3249 ArtifactDefinition deploymentArtifact = null;
3251 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3252 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3253 .equals(artifactName)) {
3254 log.debug("Found deployment artifact {}", artifactName);
3255 deploymentArtifact = artifactDefinition;
3260 if (deploymentArtifact == null) {
3261 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3262 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3265 // Downloading the artifact
3266 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3267 if (downloadArtifactEither.isRight()) {
3268 log.debug("Download artifact {} failed", artifactName);
3269 return Either.right(downloadArtifactEither.right().value());
3271 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3272 return Either.left(downloadArtifactEither.left().value().getRight());
3276 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3278 // General validation
3279 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3280 log.debug("One of the function parameteres is null");
3281 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3284 // Normalizing artifact name
3285 artifactName = ValidationUtils.normalizeFileName(artifactName);
3287 // Service validation
3288 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3289 if (validateServiceNameAndVersion.isRight()) {
3290 return Either.right(validateServiceNameAndVersion.right().value());
3293 Service service = validateServiceNameAndVersion.left().value();
3295 // ResourceInstance validation
3296 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3297 if (validateResourceInstance.isRight()) {
3298 return Either.right(validateResourceInstance.right().value());
3301 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3303 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3305 final String finalArtifactName = artifactName;
3306 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3308 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3310 .anyMatch(filterArtifactByName);
3311 ArtifactDefinition deployableArtifact;
3313 if (!hasDeploymentArtifacts) {
3314 log.debug("Deployment artifact with name {} not found", artifactName);
3315 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3318 log.debug("Found deployment artifact {}", artifactName);
3319 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3320 // Downloading the artifact
3321 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3323 if (downloadArtifactEither.isRight()) {
3324 log.debug("Download artifact {} failed", artifactName);
3325 return Either.right(downloadArtifactEither.right().value());
3327 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3328 return Either.left(downloadArtifactEither.left().value().getRight());
3331 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3333 List<ComponentInstance> riList = service.getComponentInstances();
3334 for (ComponentInstance ri : riList) {
3335 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3336 return Either.left(ri);
3340 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3343 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3345 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3346 if (serviceListBySystemName.isRight()) {
3347 log.debug("Couldn't fetch any service with name {}", serviceName);
3348 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3350 .value(), ComponentTypeEnum.SERVICE), serviceName));
3352 List<Service> serviceList = serviceListBySystemName.left().value();
3353 if (serviceList == null || serviceList.isEmpty()) {
3354 log.debug("Couldn't fetch any service with name {}", serviceName);
3355 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3358 Service foundService = null;
3359 for (Service service : serviceList) {
3360 if (service.getVersion().equals(serviceVersion)) {
3361 log.trace("Found service with version {}", serviceVersion);
3362 foundService = service;
3367 if (foundService == null) {
3368 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3369 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3370 .getValue(), serviceVersion));
3372 return Either.left(foundService);
3375 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3377 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3378 if (resourceListBySystemName.isRight()) {
3379 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3380 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3382 .value()), resourceName));
3384 return Either.left(resourceListBySystemName.left().value());
3387 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3389 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3390 if (serviceName == null || serviceVersion == null || artifactName == null) {
3391 log.debug("One of the function parameteres is null");
3392 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3395 // Normalizing artifact name
3396 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3398 // Service validation
3399 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3400 if (validateServiceNameAndVersion.isRight()) {
3401 return Either.right(validateServiceNameAndVersion.right().value());
3404 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3406 // Looking for deployment or tosca artifacts
3407 Service service = validateServiceNameAndVersion.left().value();
3409 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3410 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3411 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3414 Optional<ArtifactDefinition> foundArtifactOptl = null;
3416 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3417 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3418 // filters artifact by name
3419 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3421 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3422 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3423 // filters TOSCA artifact by name
3424 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3426 if (!foundArtifactOptl.isPresent()) {
3427 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3428 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3430 log.debug("Found deployment artifact {}", normalizedArtifactName);
3431 // Downloading the artifact
3432 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3434 if (downloadArtifactEither.isRight()) {
3435 log.debug("Download artifact {} failed", normalizedArtifactName);
3436 return Either.right(downloadArtifactEither.right().value());
3438 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3439 return Either.left(downloadArtifactEither.left().value().getRight());
3442 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3443 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3444 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3445 if (artifactById.isRight()) {
3446 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3447 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3448 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3450 ArtifactDefinition artifactDefinition = artifactById.left().value();
3451 if (artifactDefinition == null) {
3452 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3453 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3456 return downloadArtifact(artifactDefinition);
3459 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3460 boolean found = false;
3461 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3462 if (artifactsS != null) {
3463 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3464 if (entry.getValue().getUniqueId().equals(artifactId)) {
3470 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3471 if (!found && deploymentArtifactsS != null) {
3472 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3473 if (entry.getValue().getUniqueId().equals(artifactId)) {
3479 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3480 if (!found && toscaArtifactsS != null) {
3481 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3482 if (entry.getValue().getUniqueId().equals(artifactId)) {
3488 switch (component.getComponentType()) {
3490 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3491 if (!found && interfaces != null) {
3492 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3493 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3494 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3495 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3496 .getImplementation()
3498 .equals(artifactId)) {
3507 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3508 if (!found && apiArtifacts != null) {
3509 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3510 if (entry.getValue().getUniqueId().equals(artifactId)) {
3524 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3526 boolean found = false;
3527 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3528 ComponentInstance resourceInstance = null;
3529 for (ComponentInstance ri : resourceInstances) {
3530 if (ri.getUniqueId().equals(resourceInstanceId)) {
3531 resourceInstance = ri;
3535 if (resourceInstance != null) {
3536 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3537 if (artifacts != null) {
3538 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3539 if (entry.getValue().getUniqueId().equals(artifactId)) {
3546 artifacts = resourceInstance.getArtifacts();
3547 if (artifacts != null) {
3548 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3549 if (entry.getValue().getUniqueId().equals(artifactId)) {
3560 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3561 String containerComponentType) {
3563 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3564 componentForAudit.getNodeType();
3566 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3567 .getToscaFullElement(componentId);
3569 if (componentResult.isRight()) {
3570 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3571 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3572 log.debug("Service not found, serviceId {}", componentId);
3573 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3574 return Either.right(responseFormat);
3576 return Either.left(componentResult.left().value());
3579 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3580 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3581 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3582 if (canWork.isRight()) {
3583 String uniqueId = component.getUniqueId();
3584 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3585 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3587 .getComponentType(), null);
3588 return Either.right(canWork.right().value());
3591 return Either.left(true);
3594 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3596 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3597 String role = user.getRole();
3598 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3599 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3600 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3601 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3602 return Either.right(responseFormat);
3605 return Either.left(true);
3608 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3609 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3611 if (validateUserExists.isRight()) {
3612 User user = new User();
3613 user.setUserId(userId);
3614 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right()
3615 .value(), componentType, null);
3616 return Either.right(validateUserExists.right().value());
3618 return Either.left(validateUserExists.left().value());
3621 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3622 AuditingActionEnum auditingAction = null;
3623 switch (operation.getArtifactOperationEnum()) {
3625 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3628 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3631 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3634 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3639 return auditingAction;
3642 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3643 String esArtifactId = artifactDefinition.getEsId();
3644 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3645 if (artifactfromES.isRight()) {
3646 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3647 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3648 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3649 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3650 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3651 .getArtifactDisplayName());
3653 return Either.right(responseFormat);
3656 ESArtifactData esArtifactData = artifactfromES.left().value();
3657 byte[] data = esArtifactData.getDataAsArray();
3659 log.debug("Artifact data from ES is null");
3660 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3662 String artifactName = artifactDefinition.getArtifactName();
3663 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3664 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3667 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3668 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3671 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3672 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3674 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3675 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3678 log.info("Failed to save artifact {}.", artifactData.getId());
3684 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3685 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3688 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3689 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3692 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3693 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3694 if (user.isRight()) {
3695 ResponseFormat responseFormat;
3696 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3697 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3698 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3701 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3702 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3704 return Either.right(responseFormat);
3707 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3709 .value(), groupType);
3710 return Either.left(artifactDefinition);
3713 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3714 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3716 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3717 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3718 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3720 artifactInfo.setArtifactDisplayName(artifactName);
3721 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3722 artifactInfo.setArtifactType(artifactType);
3723 artifactInfo.setDescription(artifactDescription);
3724 artifactInfo.setArtifactGroupType(groupType);
3725 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3727 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3729 return artifactInfo;
3732 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3733 String uniqueId = null;
3735 if (resourceId != null) {
3736 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3738 artifactInfo.setUniqueId(uniqueId);
3740 artifactInfo.setUserIdCreator(user.getUserId());
3741 String fullName = user.getFullName();
3742 artifactInfo.setUpdaterFullName(fullName);
3744 long time = System.currentTimeMillis();
3746 artifactInfo.setCreatorFullName(fullName);
3747 artifactInfo.setCreationDate(time);
3749 artifactInfo.setLastUpdateDate(time);
3750 artifactInfo.setUserIdLastUpdater(user.getUserId());
3752 artifactInfo.setMandatory(true);
3755 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3756 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3759 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3760 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3763 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3765 byte[] payload = payloadStr.getBytes();
3767 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3768 return Either.left(artifactData);
3772 * @param artifactDefinition
3775 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3776 String instanceId, boolean shouldLock, boolean inTransaction) {
3777 String payload = generateHeatEnvPayload(artifactDefinition);
3778 String prevUUID = artifactDefinition.getArtifactUUID();
3779 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3780 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3782 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3785 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3786 boolean shouldLock, boolean inTransaction, String instanceId) {
3787 String payload = generateHeatEnvPayload(artifactDefinition);
3788 String prevUUID = artifactDefinition.getArtifactUUID();
3789 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3790 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3792 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3795 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3796 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3797 List<ComponentInstance> componentInstances = component.getComponentInstances();
3798 if (componentInstances != null) {
3799 Optional<ComponentInstance> findFirst = componentInstances.stream()
3800 .filter(ci -> ci.getUniqueId()
3801 .equals(instanceId))
3803 if (findFirst.isPresent()) {
3804 ComponentInstance relevantInst = findFirst.get();
3805 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3806 .getGroupInstances());
3808 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3809 updatedGroupInstances.forEach(gi -> {
3810 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3811 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3813 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3814 if (status.isRight()) {
3815 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3816 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3817 .convertFromStorageResponse(status.right()
3818 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3819 return Either.right(responseFormat);
3825 return Either.left(updatedArtDef);
3828 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3829 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3830 StringBuilder sb = new StringBuilder();
3831 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3832 sb.append("parameters:\n");
3833 if (heatParameters != null) {
3834 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3836 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3838 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3840 String heatValue = heatParameterDefinition.getCurrentValue();
3841 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3842 heatValue = heatParameterDefinition.getDefaultValue();
3843 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3844 empltyHeatValues.add(heatParameterDefinition);
3848 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3853 .append(heatParameterDefinition.getName())
3856 .append(Boolean.parseBoolean(heatValue))
3861 .append(heatParameterDefinition.getName())
3864 .append(new BigDecimal(heatValue).toPlainString())
3867 case COMMA_DELIMITED_LIST:
3870 .append(heatParameterDefinition.getName())
3877 String value = heatValue;
3878 boolean starts = value.startsWith("\"");
3879 boolean ends = value.endsWith("\"");
3880 if (!(starts && ends)) {
3881 starts = value.startsWith("'");
3882 ends = value.endsWith("'");
3883 if (!(starts && ends)) {
3884 value = "\"" + value + "\"";
3888 .append(heatParameterDefinition.getName())
3898 if (!empltyHeatValues.isEmpty()) {
3899 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3900 empltyHeatValues.forEach(hv -> {
3901 sb.append(" ").append(hv.getName()).append(":");
3902 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3903 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3904 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3905 sb.append(" \"\"").append("\n");
3908 sb.append(" ").append("\n");
3913 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3916 return sb.toString().replaceAll("\\\\n", "\n");
3920 * @param artifactDefinition
3924 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3925 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3926 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
3927 .getHeatParamsUpdateDate(),
3928 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3932 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3933 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3934 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3935 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3939 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3940 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3942 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3944 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3945 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3947 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3948 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3949 ESArtifactData artifactData = null;
3951 if (artifactDataRes.isLeft()) {
3952 artifactData = artifactDataRes.left().value();
3955 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3956 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3957 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3958 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3960 return Either.right(artifactDataRes.right().value());
3962 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
3964 String esArtifactId = artifactDefinition.getEsId();
3965 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3966 ESArtifactData esArtifactData;
3967 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3968 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
3969 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3970 if (artifactfromES.isRight()) {
3971 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3972 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3973 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3974 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
3975 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3977 esArtifactData = artifactfromES.left().value();
3978 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
3981 oldCheckSum = artifactDefinition.getArtifactChecksum();
3984 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3987 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3988 if (lockComponent.isRight()) {
3989 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
3990 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3991 return Either.right(lockComponent.right().value());
3995 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3997 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3998 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component
3999 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4000 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4001 .getArtifactType(), artifactDefinition.getEsId());
4002 if (updateArifactDefinitionStatus.isRight()) {
4003 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4005 .value()), artifactDefinition.getArtifactDisplayName());
4006 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4007 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4008 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4009 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4011 return Either.right(responseFormat);
4016 oldCheckSum = artifactDefinition.getArtifactChecksum();
4017 artifactDefinition.setArtifactChecksum(newCheckSum);
4018 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4019 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4020 .getArtifactType(), artifactDefinition.getEsId());
4021 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component
4022 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4024 log.trace("Update Payload ", artifactDefinition.getEsId());
4026 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4028 artifactDefinition = updateArifactDefinitionStatus.left().value();
4029 artifactData.setId(artifactDefinition.getUniqueId());
4030 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4032 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4033 if (!inTransaction) {
4036 log.debug("Artifact Saved In ES {}", artifactData.getId());
4037 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4038 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4039 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4040 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4044 if (!inTransaction) {
4045 titanDao.rollback();
4047 log.info("Failed to save artifact {}.", artifactData.getId());
4048 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4049 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4050 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4051 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4053 return Either.right(responseFormat);
4057 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4059 .value()), artifactDefinition.getArtifactDisplayName());
4060 log.debug("Failed To update artifact {}", artifactData.getId());
4061 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4062 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4063 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4065 return Either.right(responseFormat);
4071 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4077 return Either.left(artifactDefinition);
4081 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4082 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4083 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4084 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4088 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4089 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4091 Map<String, Object> json = new HashMap<String, Object>();
4092 if (artifactId != null && !artifactId.isEmpty()) {
4093 json.put(Constants.ARTIFACT_ID, artifactId);
4096 json.put(Constants.ARTIFACT_NAME, artifactName);
4097 json.put(Constants.ARTIFACT_TYPE, artifactType);
4098 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4100 if (artifactContent != null) {
4101 log.debug("payload is encoded. perform decode");
4102 String encodedPayload = Base64.encodeBase64String(artifactContent);
4103 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4105 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4106 json.put(Constants.ARTIFACT_LABEL, label);
4107 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4108 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4109 : updatedRequiredArtifacts.stream()
4110 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4112 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4113 .map(e -> e.getFileName())
4114 .collect(Collectors.toList()));
4115 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4120 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4122 String jsonStr = gson.toJson(json);
4123 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4124 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4125 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4126 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4127 if (uploadArtifactToService.isRight()) {
4128 return Either.right(uploadArtifactToService.right().value());
4131 return Either.left(uploadArtifactToService.left().value());
4134 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4135 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4136 convertParentType(componentType);
4137 String parentId = parent.getUniqueId();
4138 ArtifactDefinition currArtifact = artifactInfo;
4140 if (origMd5 != null) {
4141 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4142 if (validateMd5.isRight()) {
4143 ResponseFormat responseFormat = validateMd5.right().value();
4144 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4145 return Either.right(responseFormat);
4148 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4149 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4150 if (deploymentValidationResult.isRight()) {
4151 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4152 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4153 return Either.right(responseFormat);
4156 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4157 if (payloadEither.isRight()) {
4158 ResponseFormat responseFormat = payloadEither.right().value();
4159 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4160 return Either.right(responseFormat);
4164 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4165 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4166 return Either.right(responseFormat);
4172 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
4173 if (lockComponent.isRight()) {
4174 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4175 .value(), componentType, null);
4176 return Either.right(lockComponent.right().value());
4179 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4181 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4187 if (resultOp == null || resultOp.isRight()) {
4188 log.debug("all changes rollback");
4189 if (!inTransaction) {
4190 titanDao.rollback();
4194 log.debug("all changes committed");
4195 if (!inTransaction) {
4200 componentType = parent.getComponentType();
4202 NodeTypeEnum nodeType = componentType.getNodeType();
4203 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4207 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4208 ComponentTypeEnum componentType, String origMd5) {
4210 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4211 Either<ArtifactDefinition, Operation> insideEither = null;
4212 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4213 if (getRI.isRight()) {
4214 return Either.right(getRI.right().value());
4216 ComponentInstance ri = getRI.left().value();
4217 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4218 if (getArtifactRes.isRight()) {
4219 return Either.right(getArtifactRes.right().value());
4221 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4223 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4224 .equals(ArtifactTypeEnum.HEAT_VOL
4225 .getType()) || currArtifact
4227 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4228 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4229 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4231 return Either.right(responseFormat);
4233 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4234 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4235 new ArrayList<HeatParameterDefinition>();
4238 if (origMd5 != null) {
4239 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4240 .getName(), currentHeatEnvParams,
4241 updatedHeatEnvParams, currArtifact.getArtifactName());
4242 if (uploadParamsValidationResult.isRight()) {
4243 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4244 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4246 return Either.right(responseFormat);
4248 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4251 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4253 if (validateAndConvertHeatParamers.isRight()) {
4254 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4255 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4257 return Either.right(responseFormat);
4260 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4261 // fill reduced heat env parameters List for updating
4262 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4263 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4264 currArtifact.setListHeatParameters(currentHeatEnvParams);
4266 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent
4267 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4268 if (updateArifactRes.isRight()) {
4269 log.debug("Failed to update artifact on graph - {}", artifactId);
4270 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4273 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4275 return Either.right(responseFormat);
4277 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4278 if (error != StorageOperationStatus.OK) {
4279 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4280 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4282 return Either.right(responseFormat);
4285 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4287 .getUniqueId(), parent.getUniqueId());
4288 if (error != StorageOperationStatus.OK) {
4289 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4290 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4292 return Either.right(responseFormat);
4296 insideEither = Either.left(currArtifact);
4297 resultOp = Either.left(insideEither);
4298 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4299 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4304 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4305 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4306 String paramName = heatEnvParam.getName();
4307 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4308 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4309 String updatedParamValue = heatEnvParam.getCurrentValue();
4310 currHeatParam.setCurrentValue(updatedParamValue);
4316 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4317 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4319 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4320 Either<ArtifactDefinition, Operation> insideEither = null;
4321 String currentHeatId = currHeatArtifact.getUniqueId();
4323 String esArtifactId = currHeatArtifact.getEsId();
4324 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4325 if (artifactFromES.isRight()) {
4326 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4327 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4328 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4329 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4330 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4333 ESArtifactData esArtifactData = artifactFromES.left().value();
4335 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4337 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4338 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4339 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4341 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4345 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4347 paramName = heatEnvParam.getName();
4348 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4349 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4351 String updatedParamValue = heatEnvParam.getCurrentValue();
4352 if (updatedParamValue == null) {
4353 updatedParamValue = heatEnvParam.getDefaultValue();
4355 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4356 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4357 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4358 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4359 .getType(), paramType.getType(), paramName);
4360 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4361 return Either.right(responseFormat);
4364 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4365 newHeatEnvParams.add(currHeatParam);
4370 if (!newHeatEnvParams.isEmpty()) {
4371 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4372 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent
4373 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4375 if (operationStatus.isRight()) {
4376 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4378 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4381 return Either.right(responseFormat);
4384 updatedHeatArt = operationStatus.left().value();
4386 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4387 esArtifactData.setId(updatedHeatArt.getEsId());
4389 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4392 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
4393 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4394 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4395 .getUniqueId(), responseFormat, componentType, null);
4398 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
4399 log.debug("Failed to save the artifact.");
4400 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4401 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4402 .getUniqueId(), responseFormat, componentType, null);
4403 resultOp = Either.right(responseFormat);
4406 insideEither = Either.left(updatedHeatArt);
4409 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4410 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4411 artifactEnvInfo.setArtifactChecksum(null);
4412 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4413 .getUniqueId(), componentType.getNodeType(), componentId);
4416 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4420 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4421 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4423 .value(), parent, componentType);
4424 if (result != ActionStatus.OK) {
4425 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4426 return Either.right(responseFormat);
4430 if (updatedHeatEnvParams.isEmpty()) {
4431 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4433 resultOp = Either.left(insideEither);
4434 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4435 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4440 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4441 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4442 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4443 return Either.right(responseFormat);
4447 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4448 StorageOperationStatus error = StorageOperationStatus.OK;
4449 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4450 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4451 List<String> groupInstancesId = null;
4452 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4453 groupInstancesId = groupsInstances.stream()
4454 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4455 .contains(artifactId))
4456 .map(GroupInstanceDataDefinition::getUniqueId)
4457 .collect(Collectors.toList());
4459 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4460 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4466 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4467 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4469 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4470 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4471 .getArtifactName(), currArtifactName);
4472 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4473 return Either.right(responseFormat);
4476 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4477 String paramName = uploadedHeatParam.getName();
4478 boolean isExistsInHeat = false;
4479 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4480 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4482 isExistsInHeat = true;
4483 uploadedHeatParam.setType(currHeatParam.getType());
4484 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4485 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4486 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4490 if (!isExistsInHeat) {
4491 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4492 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4493 return Either.right(responseFormat);
4496 return Either.left(updatedHeatEnvParams);
4499 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4500 ResponseFormat responseFormat = null;
4501 List<ComponentInstance> ris = component.getComponentInstances();
4502 for (ComponentInstance ri : ris) {
4503 if (riID.equals(ri.getUniqueId())) {
4504 return Either.left(ri);
4507 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4508 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4509 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4510 return Either.right(responseFormat);
4513 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4514 ResponseFormat responseFormat = null;
4515 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4516 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4517 if (artifactId.equals(artifact.getUniqueId())) {
4518 return Either.left(artifact);
4521 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4522 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4524 return Either.right(responseFormat);
4527 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4528 ArtifactDefinition ret;
4529 if (eitherArtifact.isLeft()) {
4530 ret = eitherArtifact.left().value();
4533 ret = eitherArtifact.right().value().getImplementationArtifact();
4539 * downloads artifact of component by UUIDs
4541 * @param componentType
4542 * @param componentUuid
4543 * @param artifactUUID
4544 * @param auditAdditionalParam
4547 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4548 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4549 Either<byte[], ResponseFormat> result;
4550 byte[] downloadedArtifact = null;
4551 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4552 if (errorWrapper.isEmpty()) {
4553 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4554 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4556 if (errorWrapper.isEmpty()) {
4557 result = Either.left(downloadedArtifact);
4560 result = Either.right(errorWrapper.getInnerElement());
4566 * downloads an artifact of resource instance of component by UUIDs
4568 * @param componentType
4569 * @param componentUuid
4570 * @param resourceInstanceName
4571 * @param artifactUUID
4572 * @param auditAdditionalParam
4575 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4576 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4577 Either<byte[], ResponseFormat> result;
4578 byte[] downloadedArtifact = null;
4579 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4580 if (errorWrapper.isEmpty()) {
4581 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4584 if (errorWrapper.isEmpty()) {
4585 result = Either.left(downloadedArtifact);
4588 result = Either.right(errorWrapper.getInnerElement());
4594 * uploads an artifact to a component by UUID
4598 * @param componentType
4599 * @param componentUuid
4600 * @param additionalParams
4604 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4605 ArtifactOperationInfo operation) {
4606 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4607 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4608 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4609 ArtifactDefinition uploadArtifact = null;
4610 Component component = null;
4611 String componentId = null;
4612 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4613 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4614 String userId = request.getHeader(Constants.USER_ID_HEADER);
4616 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4617 if (getComponentRes.isRight()) {
4618 StorageOperationStatus status = getComponentRes.right().value();
4619 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4620 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4622 if (errorWrapper.isEmpty()) {
4623 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4624 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4626 if (!getComponentRes.left()
4628 .getMetadataDataDefinition()
4630 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4631 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4632 if (component != null) {
4633 componentId = component.getUniqueId();
4634 componentName = component.getName();
4637 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4639 if (errorWrapper.isEmpty()) {
4640 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4641 if (actionResult.isRight()) {
4642 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4645 errorWrapper.setInnerElement(actionResult.right().value());
4648 if (errorWrapper.isEmpty()) {
4649 uploadArtifact = actionResult.left().value().left().value();
4650 uploadArtifactResult = Either.left(uploadArtifact);
4653 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4655 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4656 return uploadArtifactResult;
4660 * upload an artifact to a resource instance by UUID
4664 * @param componentType
4665 * @param componentUuid
4666 * @param resourceInstanceName
4667 * @param additionalParams
4671 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4672 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4673 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4674 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4675 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4676 ArtifactDefinition uploadArtifact = null;
4677 Component component = null;
4678 String componentInstanceId;
4680 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4681 String userId = request.getHeader(Constants.USER_ID_HEADER);
4683 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4684 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4685 if (getComponentRes.isRight()) {
4686 StorageOperationStatus status = getComponentRes.right().value();
4687 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4688 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4690 if (errorWrapper.isEmpty() && !getComponentRes.left()
4692 .getMetadataDataDefinition()
4694 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4695 component = checkoutParentComponent(componentType, getComponentRes.left()
4697 .getMetadataDataDefinition()
4698 .getUniqueId(), userId, errorWrapper);
4700 if (errorWrapper.isEmpty()) {
4701 if (component == null) {
4702 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4705 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4708 if (errorWrapper.isEmpty()) {
4709 componentInstanceId = componentRiPair.getRight().getUniqueId();
4710 componentId = componentRiPair.getLeft().getUniqueId();
4711 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4713 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4714 .findParamByType(componentType));
4715 if (actionResult.isRight()) {
4716 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4719 errorWrapper.setInnerElement(actionResult.right().value());
4722 if (errorWrapper.isEmpty()) {
4723 uploadArtifact = actionResult.left().value().left().value();
4724 uploadArtifactResult = Either.left(uploadArtifact);
4727 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4729 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4730 return uploadArtifactResult;
4734 * updates an artifact on a component by UUID
4738 * @param componentType
4739 * @param componentUuid
4740 * @param artifactUUID
4741 * @param additionalParams
4742 * @param operation TODO
4745 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4746 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4747 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4748 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4749 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4750 ArtifactDefinition updateArtifact = null;
4751 Component component = null;
4752 String componentId = null;
4753 String artifactId = null;
4754 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4755 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4756 String userId = request.getHeader(Constants.USER_ID_HEADER);
4758 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4759 if (getComponentRes.isRight()) {
4760 StorageOperationStatus status = getComponentRes.right().value();
4761 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4762 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4764 if (errorWrapper.isEmpty()) {
4765 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4766 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4768 if (!getComponentRes.left()
4770 .getMetadataDataDefinition()
4772 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4773 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4774 if (component != null) {
4775 componentId = component.getUniqueId();
4776 componentName = component.getName();
4779 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4781 if (errorWrapper.isEmpty()) {
4782 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4784 if (errorWrapper.isEmpty()) {
4785 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4786 if (actionResult.isRight()) {
4787 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4790 errorWrapper.setInnerElement(actionResult.right().value());
4793 if (errorWrapper.isEmpty()) {
4794 updateArtifact = actionResult.left().value().left().value();
4795 updateArtifactResult = Either.left(updateArtifact);
4799 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4801 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4802 return updateArtifactResult;
4806 * updates an artifact on a resource instance by UUID
4810 * @param componentType
4811 * @param componentUuid
4812 * @param resourceInstanceName
4813 * @param artifactUUID
4814 * @param additionalParams
4815 * @param operation TODO
4818 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4819 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4821 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4822 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4823 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4824 ArtifactDefinition updateArtifact = null;
4825 Component component = null;
4826 String componentInstanceId = null;
4827 String componentId = null;
4828 String artifactId = null;
4829 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4830 String userId = request.getHeader(Constants.USER_ID_HEADER);
4832 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4833 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4834 if (getComponentRes.isRight()) {
4835 StorageOperationStatus status = getComponentRes.right().value();
4836 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4837 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4839 if (errorWrapper.isEmpty() && !getComponentRes.left()
4841 .getMetadataDataDefinition()
4843 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4844 component = checkoutParentComponent(componentType, getComponentRes.left()
4846 .getMetadataDataDefinition()
4847 .getUniqueId(), userId, errorWrapper);
4849 if (errorWrapper.isEmpty()) {
4850 if (component == null) {
4851 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4854 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4857 if (errorWrapper.isEmpty()) {
4858 componentInstanceId = componentRiPair.getRight().getUniqueId();
4859 componentId = componentRiPair.getLeft().getUniqueId();
4860 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4862 if (errorWrapper.isEmpty()) {
4863 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4865 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4866 .findParamByType(componentType));
4867 if (actionResult.isRight()) {
4868 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4871 errorWrapper.setInnerElement(actionResult.right().value());
4874 if (errorWrapper.isEmpty()) {
4875 updateArtifact = actionResult.left().value().left().value();
4876 updateArtifactResult = Either.left(updateArtifact);
4879 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4881 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4882 return updateArtifactResult;
4886 * deletes an artifact on a component by UUID
4889 * @param componentType
4890 * @param componentUuid
4891 * @param artifactUUID
4892 * @param additionalParams
4893 * @param operation TODO
4896 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4897 ArtifactOperationInfo operation) {
4899 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4900 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4901 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4902 ArtifactDefinition deleteArtifact = null;
4903 Component component = null;
4904 String componentId = null;
4905 String artifactId = null;
4906 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4907 String userId = request.getHeader(Constants.USER_ID_HEADER);
4909 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4910 if (getComponentRes.isRight()) {
4911 StorageOperationStatus status = getComponentRes.right().value();
4912 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4913 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4915 if (errorWrapper.isEmpty()) {
4916 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4917 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4918 if (!getComponentRes.left()
4920 .getMetadataDataDefinition()
4922 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4923 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4924 if (component != null) {
4925 componentId = component.getUniqueId();
4926 componentName = component.getName();
4929 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4931 if (errorWrapper.isEmpty()) {
4932 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4934 if (errorWrapper.isEmpty()) {
4935 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4936 if (actionResult.isRight()) {
4937 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4940 errorWrapper.setInnerElement(actionResult.right().value());
4943 if (errorWrapper.isEmpty()) {
4944 deleteArtifact = actionResult.left().value().left().value();
4945 deleteArtifactResult = Either.left(deleteArtifact);
4948 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4950 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4951 return deleteArtifactResult;
4955 * deletes an artifact from a resource instance by UUID
4958 * @param componentType
4959 * @param componentUuid
4960 * @param resourceInstanceName
4961 * @param artifactUUID
4962 * @param additionalParams
4963 * @param operation TODO
4966 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4967 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4969 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4970 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4971 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4972 ArtifactDefinition deleteArtifact = null;
4973 Component component = null;
4974 String componentInstanceId = null;
4975 String componentId = null;
4976 String artifactId = null;
4977 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4978 String userId = request.getHeader(Constants.USER_ID_HEADER);
4979 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4980 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4981 if (getComponentRes.isRight()) {
4982 StorageOperationStatus status = getComponentRes.right().value();
4983 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4984 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4986 if (errorWrapper.isEmpty() && !getComponentRes.left()
4988 .getMetadataDataDefinition()
4990 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4991 component = checkoutParentComponent(componentType, getComponentRes.left()
4993 .getMetadataDataDefinition()
4994 .getUniqueId(), userId, errorWrapper);
4996 if (errorWrapper.isEmpty()) {
4997 if (component == null) {
4998 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5001 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5004 if (errorWrapper.isEmpty()) {
5005 componentInstanceId = componentRiPair.getRight().getUniqueId();
5006 componentId = componentRiPair.getLeft().getUniqueId();
5007 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5009 if (errorWrapper.isEmpty()) {
5011 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5012 .findParamByType(componentType));
5014 if (actionResult.isRight()) {
5015 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
5018 errorWrapper.setInnerElement(actionResult.right().value());
5021 if (errorWrapper.isEmpty()) {
5022 deleteArtifact = actionResult.left().value().left().value();
5023 deleteArtifactResult = Either.left(deleteArtifact);
5026 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5028 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5029 return deleteArtifactResult;
5032 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5033 String artifactId = null;
5034 ArtifactDefinition foundArtifact = null;
5035 if (instance.getDeploymentArtifacts() != null) {
5036 foundArtifact = instance.getDeploymentArtifacts()
5039 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5040 .equals(artifactUUID))
5044 if (foundArtifact == null && instance.getArtifacts() != null) {
5045 foundArtifact = instance.getArtifacts()
5048 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5049 .equals(artifactUUID))
5053 if (foundArtifact == null) {
5054 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5055 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5058 artifactId = foundArtifact.getUniqueId();
5063 @SuppressWarnings("unchecked")
5064 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5065 Map<String, String> existingEnvVersions) {
5066 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5068 .getDeploymentResourceInstanceArtifacts();
5069 if (deploymentResourceArtifacts == null) {
5070 log.debug("no deployment artifacts are configured for generated artifacts");
5071 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5073 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5074 if (placeHolderData == null) {
5075 log.debug("no env type {} are configured for generated artifacts", envType);
5076 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5079 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5080 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5081 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5082 if (createArtifactPlaceHolder.isRight()) {
5083 return Either.right(createArtifactPlaceHolder.right().value());
5085 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5086 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5087 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5088 artifactHeatEnv.setTimeout(0);
5089 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5090 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5091 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5092 ArtifactDefinition heatEnvPlaceholder;
5093 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5094 if (parentType != NodeTypeEnum.ResourceInstance) {
5095 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5096 .getUniqueId(), parentType, parentId);
5097 if (addHeatEnvArtifact.isRight()) {
5098 log.debug("failed to create heat env artifact on resource instance");
5099 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5101 .value(), false), "", null));
5103 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5106 heatEnvPlaceholder = artifactHeatEnv;
5107 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5108 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5110 String artifactData = buildAuditingArtifactData(heatEnvPlaceholder);
5111 ComponentTypeEnum componentType = component.getComponentType();
5112 if (parentType == NodeTypeEnum.ResourceInstance) {
5113 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5115 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType,
5116 ResourceAuditData.newBuilder().build(),
5117 ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5118 parentName, null, artifactData, null);
5119 return Either.left(heatEnvPlaceholder);
5122 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5123 if (artifact.getListHeatParameters() == null) {
5126 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5127 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5128 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5129 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5130 heatEnvParameter.setCurrentValue(null);
5131 heatEnvParameters.add(heatEnvParameter);
5133 artifactDefinition.setListHeatParameters(heatEnvParameters);
5136 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5137 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5138 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5139 String name = heatArtifact.getArtifactName();
5142 name = heatArtifact.getArtifactLabel();
5143 fileName = name + "." + envExtension;
5146 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5148 heatEnvArtifact.setArtifactName(fileName);
5151 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5152 if (null != existingEnvVersions) {
5153 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5154 if (null != prevVersion) {
5155 heatEnvArtifact.setArtifactVersion(prevVersion);
5161 * Handles Artifacts Request For Inner Component
5163 * @param artifactsToHandle
5166 * @param vfcsNewCreatedArtifacts
5169 * @param inTransaction
5172 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5173 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5175 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5176 ComponentTypeEnum componentType = component.getComponentType();
5177 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5178 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5179 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5183 for (ArtifactDefinition artifact : artifactsToHandle) {
5184 originData = buildJsonStringForCsarVfcArtifact(artifact);
5185 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5186 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5187 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5188 if (actionResult.isRight()) {
5189 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5190 .getName(), actionResult.right().value());
5191 errorWrapper.setInnerElement(actionResult.right().value());
5192 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5193 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5197 uploadedArtifacts.add(actionResult.left().value().left().value());
5199 if (errorWrapper.isEmpty()) {
5200 handleArtifactsResult = Either.left(uploadedArtifacts);
5203 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5206 catch (Exception e) {
5207 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5208 handleArtifactsResult = Either.right(responseFormat);
5209 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5211 return handleArtifactsResult;
5214 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5215 ComponentInstance componentInstance = null;
5216 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5217 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5218 if (errorWrapper.isEmpty()) {
5219 componentInstance = component.getComponentInstances()
5221 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5222 .equals(normalizedName))
5225 if (componentInstance == null) {
5226 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5228 .getValue(), component.getName()));
5229 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5232 return componentInstance;
5235 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5237 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5238 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5239 ComponentInstance componentInstance = component.getComponentInstances()
5241 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5242 .equals(normalizedName))
5245 if (componentInstance == null) {
5246 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5248 .getValue(), component.getName()));
5249 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5252 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5254 return relatedComponentComponentInstancePair;
5257 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5258 ComponentInstance componentInstance;
5259 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5260 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5261 if (errorWrapper.isEmpty()) {
5262 componentInstance = component.getComponentInstances()
5264 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5267 if (componentInstance == null) {
5268 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5270 .getValue(), component.getName()));
5271 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5274 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5277 return relatedComponentComponentInstancePair;
5280 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5282 byte[] downloadedArtifact = null;
5283 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5284 List<ArtifactDefinition> artifactsList = null;
5285 ArtifactDefinition deploymentArtifact = null;
5286 if (artifacts != null && !artifacts.isEmpty()) {
5287 artifactsList = artifacts.values()
5289 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5290 .equals(artifactUUID))
5291 .collect(Collectors.toList());
5293 if (artifactsList == null || artifactsList.isEmpty()) {
5294 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5295 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5297 if (errorWrapper.isEmpty()) {
5298 deploymentArtifact = artifactsList.get(0);
5299 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5300 if (downloadArtifactEither.isRight()) {
5301 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5302 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5305 if (errorWrapper.isEmpty()) {
5306 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5307 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5309 return downloadedArtifact;
5312 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5313 Component component = null;
5314 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5315 if (getComponentRes.isRight()) {
5316 StorageOperationStatus status = getComponentRes.right().value();
5317 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5318 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5321 component = getComponentRes.left().value();
5326 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5327 Component component = null;
5328 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5329 if (getComponentRes.isRight()) {
5330 StorageOperationStatus status = getComponentRes.right().value();
5331 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5332 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5335 List<Component> value = getComponentRes.left().value();
5336 if (value.isEmpty()) {
5337 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5338 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5339 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5342 component = value.get(0);
5348 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5349 String artifactId = null;
5350 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5351 StorageOperationStatus storageStatus;
5352 ArtifactDefinition latestArtifact = null;
5353 List<ArtifactDefinition> artifacts = null;
5354 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5355 if (getArtifactsRes.isRight()) {
5356 storageStatus = getArtifactsRes.right().value();
5357 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5358 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5359 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5361 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5363 if (errorWrapper.isEmpty()) {
5364 artifacts = getArtifactsRes.left()
5368 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5369 .equals(artifactUUID))
5370 .collect(Collectors.toList());
5371 if (artifacts == null || artifacts.isEmpty()) {
5372 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5373 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5376 if (errorWrapper.isEmpty()) {
5377 latestArtifact = artifacts.stream().max((a1, a2) -> {
5378 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5379 if (compareRes == 0) {
5380 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5381 .getLastUpdateDate());
5385 if (latestArtifact == null) {
5386 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5387 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5390 if (errorWrapper.isEmpty()) {
5391 artifactId = latestArtifact.getUniqueId();
5396 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5398 Component component = null;
5399 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5400 if (getUserRes.isRight()) {
5401 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5404 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5406 if (errorWrapper.isEmpty()) {
5407 User modifier = getUserRes.left().value();
5408 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5409 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5410 if (checkoutRes.isRight()) {
5411 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5412 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5413 errorWrapper.setInnerElement(checkoutRes.right().value());
5416 component = checkoutRes.left().value();
5422 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
5423 if (artifact == null) {
5424 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
5425 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
5426 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
5427 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
5431 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
5432 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
5433 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
5437 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5438 Map<String, Object> json = new HashMap<>();
5439 String artifactName = artifact.getArtifactName();
5440 json.put(Constants.ARTIFACT_NAME, artifactName);
5441 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5442 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5443 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5444 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5445 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5446 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5447 return gson.toJson(json);
5451 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5452 this.nodeTemplateOperation = nodeTemplateOperation;