2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.function.Predicate;
37 import java.util.function.Supplier;
38 import java.util.stream.Collectors;
40 import javax.servlet.http.HttpServletRequest;
42 import org.apache.commons.codec.binary.Base64;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.apache.commons.collections.MapUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
47 import org.openecomp.sdc.be.components.ArtifactsResolver;
48 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
49 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
52 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
55 import org.openecomp.sdc.be.config.ConfigurationManager;
56 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
59 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
60 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
61 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
62 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.ArtifactType;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentParametersView;
71 import org.openecomp.sdc.be.model.GroupDefinition;
72 import org.openecomp.sdc.be.model.GroupInstance;
73 import org.openecomp.sdc.be.model.HeatParameterDefinition;
74 import org.openecomp.sdc.be.model.InterfaceDefinition;
75 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
76 import org.openecomp.sdc.be.model.LifecycleStateEnum;
77 import org.openecomp.sdc.be.model.Operation;
78 import org.openecomp.sdc.be.model.Resource;
79 import org.openecomp.sdc.be.model.Service;
80 import org.openecomp.sdc.be.model.User;
81 import org.openecomp.sdc.be.model.heat.HeatParameterType;
82 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
83 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
84 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
85 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
86 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
87 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
88 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
89 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
90 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
91 import org.openecomp.sdc.be.resources.data.ESArtifactData;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
94 import org.openecomp.sdc.be.servlets.RepresentationUtils;
95 import org.openecomp.sdc.be.tosca.CsarUtils;
96 import org.openecomp.sdc.be.tosca.ToscaError;
97 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
98 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
99 import org.openecomp.sdc.be.user.IUserBusinessLogic;
100 import org.openecomp.sdc.be.user.Role;
101 import org.openecomp.sdc.be.user.UserBusinessLogic;
102 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
103 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
104 import org.openecomp.sdc.common.api.Constants;
105 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
106 import org.openecomp.sdc.common.datastructure.Wrapper;
107 import org.openecomp.sdc.common.util.GeneralUtility;
108 import org.openecomp.sdc.common.util.ValidationUtils;
109 import org.openecomp.sdc.common.util.YamlToObjectConverter;
110 import org.openecomp.sdc.exception.ResponseFormat;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
113 import org.springframework.beans.factory.annotation.Autowired;
114 import org.xml.sax.*;
115 import org.yaml.snakeyaml.Yaml;
117 import com.google.gson.Gson;
118 import com.google.gson.GsonBuilder;
119 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
121 import fj.data.Either;
123 @org.springframework.stereotype.Component("artifactBusinessLogic")
124 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
125 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
126 private static final String ARTIFACT_DESCRIPTION = "artifact description";
127 private static final String ARTIFACT_LABEL = "artifact label";
128 private static final String ARTIFACT_URL = "artifact url";
129 private static final String ARTIFACT_NAME = "artifact name";
130 private static final String ARTIFACT_PAYLOAD = "artifact payload";
132 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
133 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
134 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
136 public static final String HEAT_ENV_NAME = "heatEnv";
137 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
138 public static final String HEAT_ENV_SUFFIX = "env";
139 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
141 // private static Integer defaultHeatTimeout;
142 // private static final Integer NON_HEAT_TIMEOUT = 0;
143 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
144 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
146 @javax.annotation.Resource
147 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
148 @javax.annotation.Resource
149 private IUserAdminOperation userOperaton;
151 @javax.annotation.Resource
152 private IElementOperation elementOperation;
154 @javax.annotation.Resource
155 private ResourceBusinessLogic resourceBusinessLogic;
157 @javax.annotation.Resource
158 private ServiceBusinessLogic serviceBusinessLogic;
160 @javax.annotation.Resource
161 private UserBusinessLogic userAdminManager;
163 @javax.annotation.Resource
164 private IHeatParametersOperation heatParametersOperation;
167 private ArtifactCassandraDao artifactCassandraDao;
170 private ToscaExportHandler toscaExportUtils;
173 private CsarUtils csarUtils;
176 private LifecycleBusinessLogic lifecycleBusinessLogic;
179 private IUserBusinessLogic userBusinessLogic;
181 NodeTemplateOperation nodeTemplateOperation;
184 private ArtifactsResolver artifactsResolver;
186 public ArtifactsBusinessLogic() {
187 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
188 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
189 // defaultHeatTimeout = 60;
193 public static enum ArtifactOperationEnum {
194 Create(), Update(), Delete(), Download();
197 public class ArtifactOperationInfo {
199 private ArtifactOperationEnum artifactOperationEnum;
200 private boolean isExternalApi;
201 private boolean ignoreLifecycleState;
203 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
204 this.artifactOperationEnum = artifactOperationEnum;
205 this.isExternalApi = isExternalApi;
206 this.ignoreLifecycleState = ignoreLifecycleState;
209 public boolean isExternalApi() {
210 return isExternalApi;
213 public boolean ignoreLifecycleState() {
214 return ignoreLifecycleState;
217 public ArtifactOperationEnum getArtifactOperationEnum() {
218 return artifactOperationEnum;
224 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
225 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
226 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
229 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
230 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
232 // step 1 - detect auditing type
233 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
234 // step 2 - check header
235 if (userId == null) {
236 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
237 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
238 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
239 return Either.right(responseFormat);
241 // step 3 - check user existence
242 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
243 if (userResult.isRight()) {
244 return Either.right(userResult.right().value());
247 // step 4 - check user's role
248 User user = userResult.left().value();
249 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
250 if (validateUserRole.isRight()) {
251 return Either.right(validateUserRole.right().value());
255 // 5. check service/resource existence
256 // 6. check service/resource check out
257 // 7. user is owner of checkout state
258 org.openecomp.sdc.be.model.Component component = null;
259 // ComponentInstance resourceInstance = null;
260 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
261 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
262 if (validateComponent.isRight()) {
263 return Either.right(validateComponent.right().value());
265 component = validateComponent.left().value();
266 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
267 if (validateWorkOnResource.isRight()) {
268 return Either.right(validateWorkOnResource.right().value());
271 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
272 shouldLock, inTransaction, true);
278 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
279 * For regular usage use <br>
280 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
284 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
285 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
286 Component parent = component;
287 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
289 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
290 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
292 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
293 if (errorWrapper.isEmpty()) {
295 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
297 result = Either.right(errorWrapper.getInnerElement());
302 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
303 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
304 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
305 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
306 if (validateArtifact.isRight()) {
307 ResponseFormat responseFormat = validateArtifact.right().value();
308 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
309 errorWrapper.setInnerElement(validateArtifact.right().value());
311 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
312 artifactInfo = validateArtifact.left().value();
313 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
320 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
321 Wrapper<ResponseFormat> errorWrapper) {
322 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
324 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
325 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
326 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
327 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
329 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
330 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
331 if (eitherGenerated.isRight()) {
332 errorWrapper.setInnerElement(eitherGenerated.right().value());
338 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
339 boolean needGenerate;
340 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
341 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
345 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
346 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
349 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
350 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
352 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
353 if (generated.isRight()) {
356 byte[] decodedPayload = artifactDefinition.getPayloadData();
357 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
358 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
359 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
360 shouldLock, inTransaction);
364 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
365 log.debug("tosca artifact generation");
366 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
367 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
369 if (generated.isRight()) {
370 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
372 return Either.right(generated.right().value());
374 byte[] value = generated.left().value();
375 artifactInfo.setPayload(value);
378 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
379 if (exportComponent.isRight()) {
380 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
381 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
382 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
383 return Either.right(responseFormat);
385 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
386 String payload = exportComponent.left().value().getMainYaml();
387 artifactInfo.setPayloadData(payload);
389 return Either.left(Either.left(artifactInfo));
392 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
393 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
394 if (interfaceName != null && operationName != null) {
395 interfaceName = interfaceName.toLowerCase();
396 operationName = operationName.toLowerCase();
398 switch (operation.getArtifactOperationEnum()) {
400 if (artifactGenerationRequired(parent, artifactInfo)) {
401 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
403 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
405 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
407 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
408 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
409 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
410 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
411 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
412 if (needUpdateGroup && result.isLeft()) {
413 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
414 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
415 if (error != ActionStatus.OK) {
416 result = Either.right(componentsUtils.getResponseFormat(error));
420 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
421 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
424 if (result == null) {
425 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
426 if (needUpdateGroup && result.isLeft()) {
427 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
429 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
430 if (error != ActionStatus.OK) {
431 result = Either.right(componentsUtils.getResponseFormat(error));
437 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
442 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
443 List<GroupDefinition> groups = parent.getGroups();
444 if (groups != null && !groups.isEmpty()) {
445 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
446 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
447 groupToUpdate.forEach(g -> {
448 g.getArtifacts().remove(artifactInfo.getUniqueId());
449 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
450 g.getArtifacts().add(artAfterUpdate.getUniqueId());
451 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
453 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
454 if (status.isRight()) {
455 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
456 return componentsUtils.convertFromStorageResponse(status.right().value());
460 return ActionStatus.OK;
463 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
464 List<GroupDefinition> groups = parent.getGroups();
465 if (groups != null && !groups.isEmpty()) {
466 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
467 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
468 groupToUpdate.forEach(g -> {
469 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
470 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
471 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
472 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
473 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
474 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
476 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
477 if (status.isRight()) {
478 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
479 return componentsUtils.convertFromStorageResponse(status.right().value());
483 return ActionStatus.OK;
486 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
487 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
488 List<GroupInstance> groupInstances = null;
489 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
490 if (componentInstOp.isPresent()) {
491 groupInstances = componentInstOp.get().getGroupInstances();
493 if (CollectionUtils.isNotEmpty(groupInstances)) {
494 boolean isUpdated = false;
495 for (GroupInstance groupInstance : groupInstances) {
497 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
498 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
499 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
502 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
503 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
504 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
508 updatedGroupInstances.add(groupInstance);
512 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
513 if (status.isRight()) {
514 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
515 return componentsUtils.convertFromStorageResponse(status.right().value());
517 return ActionStatus.OK;
520 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
521 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
522 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
523 result = generateToscaArtifact(parent, artifactInfo, false, false);
525 String heatArtifactId = artifactInfo.getGeneratedFromId();
526 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
527 if (heatRes.isRight()) {
528 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
529 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
530 return Either.right(responseFormat);
532 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
533 artifactInfo.setPayloadData(generatedPayload);
534 result = Either.left(Either.left(artifactInfo));
539 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
540 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
541 convertParentType(componentType);
542 String parentId = parent.getUniqueId();
543 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
544 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
546 if (origMd5 != null) {
547 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
548 if (validateMd5.isRight()) {
549 ResponseFormat responseFormat = validateMd5.right().value();
550 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
551 return Either.right(responseFormat);
554 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
556 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
557 if (payloadEither.isRight()) {
558 ResponseFormat responseFormat = payloadEither.right().value();
559 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
560 return Either.right(responseFormat);
562 } else { // duplicate
563 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
564 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
565 return Either.right(responseFormat);
571 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
572 if (lockComponent.isRight()) {
573 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
574 return Either.right(lockComponent.right().value());
577 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
579 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
584 if (resultOp == null || resultOp.isRight()) {
585 log.debug("all changes rollback");
586 if (false == inTransaction)
589 log.debug("all changes committed");
590 if (false == inTransaction)
594 componentType = parent.getComponentType();
595 NodeTypeEnum nodeType = componentType.getNodeType();
596 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
597 // graphLockOperation.unlockComponent(parentId, parentType);
606 * @param componentType
611 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
612 if (artifactGenerationRequired(component, csarArtifact)) {
613 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
615 if (generated.isRight()) {
616 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
618 return Either.right(generated.right().value());
620 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
622 return downloadArtifact(csarArtifact);
625 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
626 // perform all validation in common flow
627 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
628 null, parentId, containerComponentType);
629 if (result.isRight()) {
630 return Either.right(result.right().value());
632 ArtifactDefinition artifactDefinition;
633 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
634 if (insideValue.isLeft()) {
635 artifactDefinition = insideValue.left().value();
637 artifactDefinition = insideValue.right().value().getImplementationArtifact();
639 // for tosca artifacts and heat env on VF level generated on download without saving
640 if (artifactDefinition.getPayloadData() != null) {
641 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
643 return downloadArtifact(artifactDefinition);
646 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
648 // detect auditing type
649 Map<String, ArtifactDefinition> resMap = null;
650 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
655 if (userId == null) {
656 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
657 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
659 resultOp = Either.right(responseFormat);
663 // check user existence
667 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
668 if (userResult.isRight()) {
670 resultOp = Either.right(userResult.right().value());
674 userResult.left().value();
677 // 5. check service/resource existence
678 // 6. check service/resource check out
679 // 7. user is owner of checkout state
680 org.openecomp.sdc.be.model.Component component = null;
681 // ComponentInstance resourceInstance = null;
682 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
683 ComponentParametersView componentFilter = new ComponentParametersView();
684 componentFilter.disableAll();
685 componentFilter.setIgnoreArtifacts(false);
686 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
687 componentFilter.setIgnoreComponentInstances(false);
689 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
691 if (validateComponent.isRight()) {
692 resultOp = Either.right(validateComponent.right().value());
695 component = validateComponent.left().value();
696 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
697 if (lockComponent.isRight()) {
699 resultOp = Either.right(lockComponent.right().value());
704 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
706 if (groupType == null) {
707 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
708 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
710 resultOp = Either.right(responseFormat);
714 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
715 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
716 if (list != null && !list.isEmpty()) {
717 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
719 resMap = new HashMap<>();
721 resultOp = Either.left(resMap);
725 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
726 if (artifactsMapStatus.isRight()) {
727 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
728 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
729 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
730 resultOp = Either.right(responseFormat);
732 resMap = new HashMap<>();
733 resultOp = Either.left(resMap);
736 resMap = artifactsMapStatus.left().value();
737 resultOp = Either.left(resMap);
743 if (resultOp == null || resultOp.isRight()) {
744 log.debug("all changes rollback");
747 log.debug("all changes committed");
752 componentType = component.getComponentType();
753 NodeTypeEnum nodeType = componentType.getNodeType();
754 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
755 // graphLockOperation.unlockComponent(parentId, parentType);
760 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
761 boolean inTransaction) {
763 // check artifact existence
764 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
765 if (artifactResult.isRight()) {
766 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
767 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
768 log.debug("addArtifact - artifact {} not found", artifactId);
769 return Either.right(responseFormat);
772 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
773 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
774 return Either.right(responseFormat);
778 // check artifact belong to component
779 boolean found = false;
780 switch (componentType) {
783 found = checkArtifactInComponent(component, artifactId);
785 case RESOURCE_INSTANCE:
786 found = checkArtifactInResourceInstance(component, componentId, artifactId);
792 // String component =
793 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
795 String componentName = componentType.name().toLowerCase();
796 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
797 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
798 return Either.right(responseFormat);
800 return Either.left(artifactResult.left().value());
803 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
804 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
806 String artifactId = null;
809 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
810 if (payloadEither.isRight()) {
811 return Either.right(payloadEither.right().value());
813 byte[] decodedPayload = payloadEither.left().value();
814 convertParentType(componentType);
817 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
818 if (lockComponent.isRight()) {
819 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
820 return Either.right(lockComponent.right().value());
823 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
826 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
830 unlockComponent(resultOp, parent, inTransaction);
837 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
838 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
840 convertParentType(componentType);
844 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
846 if (lockComponent.isRight()) {
847 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
848 return Either.right(lockComponent.right().value());
852 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
854 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
859 unlockComponent(resultOp, parent, inTransaction);
864 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
865 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
867 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
869 if (payloadEither.isRight()) {
870 return Either.right(payloadEither.right().value());
872 byte[] decodedPayload = payloadEither.left().value();
874 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
877 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
878 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
880 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
881 if (validateMd5.isRight()) {
882 ResponseFormat responseFormat = validateMd5.right().value();
883 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
884 return Either.right(responseFormat);
888 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
889 if (validateResult.isRight()) {
890 ResponseFormat responseFormat = validateResult.right().value();
891 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
892 return Either.right(validateResult.right().value());
895 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
896 if (payloadEither.isRight()) {
897 ResponseFormat responseFormat = payloadEither.right().value();
898 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
899 log.debug("Error during handle payload");
900 return Either.right(responseFormat);
903 // validate heat parameters. this part must be after the parameters are
904 // extracted in "handlePayload"
905 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
906 if (validateAndConvertHeatParamers.isRight()) {
907 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
908 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
909 log.debug("Error during handle payload");
910 return Either.right(responseFormat);
912 return payloadEither;
915 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
916 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
918 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
922 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
926 user.setUserId("UNKNOWN");
928 switch (componentTypeEnum) {
931 Resource resource = (Resource) component;
932 if (resource == null) {
933 // In that case, component ID should be instead of name
934 resource = new Resource();
935 resource.setName(componentId);
937 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
941 Service service = (Service) component;
942 if (service == null) {
943 // In that case, component ID should be instead of name
944 service = new Service();
945 service.setName(componentId);
947 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
950 case RESOURCE_INSTANCE:
951 if (resourceInstanceName == null) {
952 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
954 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
955 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
963 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
964 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
965 String resourceInstanceName = null;
966 if (resourceInstance != null) {
967 resourceInstanceName = resourceInstance.getName();
969 return resourceInstanceName;
972 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
973 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
974 // Putting together artifact info
975 String artifactData = buildAuditingArtifactData(artifactDefinition);
976 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
977 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
978 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
979 return auditingFields;
984 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
985 StringBuilder sb = new StringBuilder();
986 if (artifactDefinition != null) {
987 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
988 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
991 if (artifactDefinition.getArtifactVersion() != null) {
993 sb.append(artifactDefinition.getArtifactVersion());
998 if (artifactDefinition.getArtifactUUID() != null) {
999 sb.append(artifactDefinition.getArtifactUUID());
1004 return sb.toString();
1007 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1009 if (origMd5 != null) {
1010 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
1012 if (false == encodeBase64Str.equals(origMd5)) {
1013 log.debug("The calculated md5 is different then the received one");
1014 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1017 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1018 log.debug("Missing md5 header during artifact create");
1019 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1022 if (payload != null && payload.length != 0) {
1023 log.debug("Cannot have payload while md5 header is missing");
1024 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1027 return Either.left(true);
1030 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1031 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1033 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1034 if (artifactById.isRight()) {
1035 return Either.right(artifactById.right().value());
1037 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1039 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1040 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1041 if (validateInformationalArtifactRes.isRight()) {
1042 return Either.right(validateInformationalArtifactRes.right().value());
1044 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1045 if (validateAndSetArtifactname.isRight()) {
1046 return Either.right(validateAndSetArtifactname.right().value());
1048 if (operationName != null && interfaceName != null) {
1049 operationName = operationName.toLowerCase();
1050 interfaceName = interfaceName.toLowerCase();
1052 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
1053 if (logicalNameStatus.isRight()) {
1054 return Either.right(logicalNameStatus.right().value());
1056 // This is a patch to block possibility of updating service api fields
1057 // through other artifacts flow
1059 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1060 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1062 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1065 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1066 if (currentArtifactInfo != null) {
1067 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1070 // artifactGroupType is not allowed to be updated
1071 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1072 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1073 if (validateGroupType.isRight()) {
1074 return Either.right(validateGroupType.right().value());
1078 NodeTypeEnum parentType = convertParentType(componentType);
1081 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
1083 if (isDeploymentArtifact(artifactInfo)) {
1084 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1085 if (deploymentValidationResult.isRight()) {
1086 return Either.right(deploymentValidationResult.right().value());
1089 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1092 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1093 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1097 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1098 if (descriptionResult.isRight()) {
1099 return Either.right(descriptionResult.right().value());
1102 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1103 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1104 if (validateServiceApiType.isRight()) {
1105 return Either.right(validateServiceApiType.right().value());
1107 // Change of type is not allowed and should be ignored
1109 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1111 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1112 if (validateUrl.isRight()) {
1113 return Either.right(validateUrl.right().value());
1116 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1117 if (validateUpdate.isRight()) {
1118 log.debug("serviceApi first update cnnot be without payload.");
1119 return Either.right(validateUpdate.right().value());
1122 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1123 if (validateArtifactType.isRight()) {
1124 return Either.right(validateArtifactType.right().value());
1126 if (artifactInfo.getApiUrl() != null) {
1127 artifactInfo.setApiUrl(null);
1128 log.error("Artifact URL cannot be set through this API - ignoring");
1131 if (artifactInfo.getServiceApi() != null) {
1132 if (artifactInfo.getServiceApi()) {
1133 artifactInfo.setServiceApi(false);
1134 log.error("Artifact service API flag cannot be changed - ignoring");
1139 return Either.left(artifactInfo);
1142 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1143 if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
1144 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1145 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1146 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1150 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1152 Either<ArtifactDefinition, ResponseFormat> result = null;
1153 ArtifactDefinition foundArtifact = null;
1154 if (StringUtils.isNotEmpty(artifactId)) {
1155 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1157 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1158 log.debug("Artifact {} already exist", artifactId);
1159 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1161 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1162 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1163 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1165 if (result == null) {
1166 result = Either.left(foundArtifact);
1171 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1172 ArtifactDefinition foundArtifact;
1173 if (parentComponent.getUniqueId().equals(parentId)) {
1174 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1176 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1177 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1179 return foundArtifact;
1182 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1183 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1184 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1185 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1186 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1187 if (artifactType == null) {
1188 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1189 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1190 String artifactTypeName = artifactType.getType();
1191 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1192 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1193 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1194 if (!validArtifactTypes.contains(artifactTypeName)) {
1195 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1197 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1198 if (!validResourceType.contains(parentResourceType.name())) {
1199 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1203 return validationResult;
1206 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1207 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1208 return NodeTypeEnum.Resource;
1209 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1210 return NodeTypeEnum.ResourceInstance;
1212 return NodeTypeEnum.Service;
1216 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1217 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1219 NodeTypeEnum parentType = convertParentType(componentType);
1220 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1221 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1222 ArtifactDefinition foundArtifact = null;
1223 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1224 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1225 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1226 boolean isDuplicated = false;
1228 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1231 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1232 if (lockComponent.isRight()) {
1233 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1234 resultOp = Either.right(lockComponent.right().value());
1237 if (resultOp == null) {
1238 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1239 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1240 if (getContainerRes.isRight()) {
1241 log.debug("Failed to fetch the container component {}. ", parentId);
1242 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1243 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1244 resultOp = Either.right(responseFormat);
1247 if (resultOp == null) {
1248 fetchedContainerComponent = getContainerRes.left().value();
1249 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1250 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1251 if (getArtifactRes.isRight()) {
1252 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1253 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1254 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1255 resultOp = Either.right(responseFormat);
1257 foundArtifact = getArtifactRes.left().value().getLeft();
1258 esId = foundArtifact.getEsId();
1261 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1262 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1263 if (needCloneRes.isRight()) {
1264 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1265 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1266 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1267 resultOp = Either.right(responseFormat);
1270 if (resultOp == null) {
1271 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1272 if (updatedArtifactRes.isRight()) {
1273 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1274 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1275 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1276 resultOp = Either.right(responseFormat);
1278 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1282 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1283 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1284 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1285 if (cassandraStatus != CassandraOperationStatus.OK) {
1286 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1287 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1288 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1289 resultOp = Either.right(responseFormat);
1292 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1294 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1295 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1296 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1297 if (status.isRight()) {
1298 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1299 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1300 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1301 resultOp = Either.right(responseFormat);
1305 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1306 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1307 if (status != StorageOperationStatus.OK) {
1308 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1309 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1310 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1311 resultOp = Either.right(responseFormat);
1314 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1315 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1316 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1317 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1318 if (status.isRight()) {
1319 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1320 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1321 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1322 resultOp = Either.right(responseFormat);
1326 if (resultOp == null) {
1327 resultOp = Either.left(Either.left(foundArtifact));
1328 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1333 unlockComponent(resultOp, parent, inTransaction);
1338 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1339 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1340 boolean isUpdated = false;
1341 if (groups != null) {
1342 for (GroupDefinition group : groups) {
1344 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1345 group.getArtifacts().remove(artifactId);
1348 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1349 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1353 updatedGroups.add(group);
1357 return updatedGroups;
1360 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1361 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1362 if (CollectionUtils.isNotEmpty(groupInstances)) {
1363 boolean isUpdated = false;
1364 for (GroupInstance groupInstance : groupInstances) {
1366 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1367 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1370 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1371 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1375 updatedGroupInstances.add(groupInstance);
1379 return updatedGroupInstances;
1382 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1384 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1385 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1386 String componentId = component.getUniqueId();
1387 String instanceId = componentId.equals(parentId) ? null : parentId;
1389 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1390 resetMandatoryArtifactFields(foundArtifact);
1391 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true);
1392 } else if (cloneIsNeeded) {
1393 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1394 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1396 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1397 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1402 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1404 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1405 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1406 ComponentInstance foundInstance = null;
1407 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1408 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1409 if (!componentInstanceOpt.isPresent()) {
1410 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1412 foundInstance = componentInstanceOpt.get();
1413 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1416 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1418 if (result == null) {
1419 if (artifacts.containsKey(artifactId)) {
1420 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1422 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1428 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1429 Map<String, ArtifactDefinition> currArtifacts;
1430 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1431 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1432 if (MapUtils.isNotEmpty(currArtifacts)) {
1433 artifacts.putAll(currArtifacts);
1436 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1437 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1438 if (MapUtils.isNotEmpty(currArtifacts)) {
1439 artifacts.putAll(currArtifacts);
1442 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1443 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1444 if (MapUtils.isNotEmpty(currArtifacts)) {
1445 artifacts.putAll(currArtifacts);
1450 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1451 Map<String, ArtifactDefinition> currArtifacts;
1452 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1453 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1454 if (MapUtils.isNotEmpty(currArtifacts)) {
1455 artifacts.putAll(currArtifacts);
1458 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1459 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1460 if (MapUtils.isNotEmpty(currArtifacts)) {
1461 artifacts.putAll(currArtifacts);
1466 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1467 StorageOperationStatus result;
1468 switch (cassandraStatus) {
1470 result = StorageOperationStatus.OK;
1473 result = StorageOperationStatus.NOT_FOUND;
1475 case CLUSTER_NOT_CONNECTED:
1476 case KEYSPACE_NOT_CONNECTED:
1477 result = StorageOperationStatus.CONNECTION_FAILURE;
1480 result = StorageOperationStatus.GENERAL_ERROR;
1486 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1487 if (fetchedArtifact != null) {
1488 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1489 fetchedArtifact.setEsId(null);
1490 fetchedArtifact.setArtifactName(null);
1491 fetchedArtifact.setDescription(null);
1492 fetchedArtifact.setApiUrl(null);
1493 fetchedArtifact.setArtifactChecksum(null);
1494 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1495 fetchedArtifact.setArtifactUUID(null);
1496 long time = System.currentTimeMillis();
1497 fetchedArtifact.setPayloadUpdateDate(time);
1498 fetchedArtifact.setHeatParameters(null);
1499 fetchedArtifact.setHeatParamsUpdateDate(null);
1503 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1504 StorageOperationStatus error = StorageOperationStatus.OK;
1505 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1506 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1507 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1512 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1513 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1514 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1515 if (artifactById.isRight()) {
1516 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1517 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1518 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1519 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1520 return Either.right(responseFormat);
1522 ArtifactDefinition artifactDefinition = artifactById.left().value();
1523 if (artifactDefinition == null) {
1524 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1525 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1526 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1527 return Either.right(responseFormat);
1529 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1530 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1531 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1532 return Either.left(insideEither);
1535 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1536 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1537 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1538 // in case of update artifact must be
1539 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1540 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1541 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1543 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1544 log.debug("Artifact {} already exist", artifactId);
1545 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1547 ArtifactDefinition currentArtifactInfo = null;
1548 if (artifactById.isLeft()) {
1549 // get previous value
1550 currentArtifactInfo = artifactById.left().value();
1552 return Either.left(currentArtifactInfo);
1555 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1556 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
1558 String artifactLabel = artifactInfo.getArtifactLabel();
1559 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1560 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1561 log.debug("missing artifact logical name for component {}", componentId);
1562 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1564 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1566 if (operationName != null) {
1567 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1568 log.debug("artifact label cannot be set {}", artifactLabel);
1569 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1571 artifactLabel = operationName;
1574 String displayName = artifactInfo.getArtifactDisplayName();
1575 if (displayName == null || displayName.isEmpty())
1576 displayName = artifactLabel;
1577 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1578 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1579 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1580 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1582 artifactInfo.setArtifactDisplayName(displayName);
1584 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1585 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1586 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1588 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1590 if (artifactLabel.isEmpty()) {
1591 log.debug("missing normalized artifact logical name for component {}", componentId);
1592 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1595 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1596 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1597 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1599 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1600 log.debug("Non unique Artifact label : {}", artifactLabel);
1601 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1604 artifactInfo.setArtifactLabel(artifactLabel);
1606 return Either.left(ActionStatus.OK);
1609 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1610 boolean isUnique = true;
1611 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1612 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1613 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1615 artifacts = artifactToscaOperation.getArtifacts(componentId);
1618 if (artifacts.isLeft()) {
1619 for (String label : artifacts.left().value().keySet()) {
1620 if (label.equals(artifactLabel)) {
1626 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1627 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
1628 if (allInterfacesOfResource.isLeft()) {
1629 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1630 for (Operation operation : interace.getOperationsMap().values()) {
1631 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1642 // ***************************************************************
1644 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1645 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1647 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1648 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1649 Either<ArtifactDefinition, Operation> insideEither = null;
1650 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1651 String instanceId = null;
1652 String instanceName = null;
1653 if (foundInstance != null) {
1654 instanceId = foundInstance.getUniqueId();
1655 instanceName = foundInstance.getName();
1657 if (artifactData == null) {
1658 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1659 log.debug("Failed to create artifact object for ES.");
1660 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1661 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1662 resultOp = Either.right(responseFormat);
1666 // set on graph object id of artifact in ES!
1667 artifactInfo.setEsId(artifactData.getId());
1669 boolean isLeft = false;
1670 String artifactUniqueId = null;
1671 StorageOperationStatus error = null;
1672 if (interfaceType != null && operationName != null) {
1673 // lifecycle artifact
1674 Operation operation = convertToOperation(artifactInfo, operationName);
1676 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1678 isLeft = result.isLeft();
1680 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1681 result.left().value().getImplementation();
1683 insideEither = Either.right(result.left().value());
1684 resultOp = Either.left(insideEither);
1686 error = result.right().value();
1689 // information/deployment/api aritfacts
1690 log.trace("Try to create entry on graph");
1691 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1692 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1694 isLeft = result.isLeft();
1696 artifactUniqueId = result.left().value().getUniqueId();
1697 result.left().value();
1699 insideEither = Either.left(result.left().value());
1700 resultOp = Either.left(insideEither);
1702 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1703 if (error != StorageOperationStatus.OK) {
1708 error = result.right().value();
1712 boolean res = saveArtifacts(artifactData, parentId, false);
1713 // String uniqueId = artifactDefinition.getUniqueId();
1716 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1718 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1719 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1722 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1723 log.debug("Failed to save the artifact.");
1724 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1725 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1727 resultOp = Either.right(responseFormat);
1731 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1732 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1733 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1734 resultOp = Either.right(responseFormat);
1740 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1741 ComponentInstance foundInstance = null;
1742 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1743 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1745 return foundInstance;
1748 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1750 Either<Boolean, ResponseFormat> result = Either.left(true);
1751 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1753 validateArtifactTypeExists(responseWrapper, artifactInfo);
1755 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1757 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1759 if (responseWrapper.isEmpty()) {
1760 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1763 if (responseWrapper.isEmpty()) {
1764 // Common code for all types
1765 // not allowed to change artifactType
1767 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1768 if (validateServiceApiType.isRight()) {
1769 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1773 if (responseWrapper.isEmpty()) {
1774 if (parentType.equals(NodeTypeEnum.Resource)) {
1775 // if (parentComponent instanceof Resource) {
1776 Resource resource = (Resource) parentComponent;
1777 ResourceTypeEnum resourceType = resource.getResourceType();
1778 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1779 if (config == null) {
1780 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1782 List<String> myList = config.getValidForResourceTypes();
1783 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1784 if (either.isRight()) {
1785 responseWrapper.setInnerElement(either.right().value());
1790 if (responseWrapper.isEmpty()) {
1791 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1794 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1795 String artifactName = artifactInfo.getArtifactName();
1796 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1797 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1801 if (responseWrapper.isEmpty()) {
1802 switch (artifactType) {
1806 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1810 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1811 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1814 case DCAE_INVENTORY_TOSCA:
1815 case DCAE_INVENTORY_JSON:
1816 case DCAE_INVENTORY_POLICY:
1817 // Validation is done in handle payload.
1818 case DCAE_INVENTORY_DOC:
1819 case DCAE_INVENTORY_BLUEPRINT:
1820 case DCAE_INVENTORY_EVENT:
1821 // No specific validation
1823 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1829 if (!responseWrapper.isEmpty()) {
1830 result = Either.right(responseWrapper.getInnerElement());
1835 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1836 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1837 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1838 responseWrapper.setInnerElement(responseFormat);
1839 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1843 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1844 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1845 if (parentType.equals(NodeTypeEnum.Resource)) {
1846 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1847 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1848 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1850 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1852 return resourceDeploymentArtifacts;
1855 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1856 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1857 if (artifactType == null) {
1858 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1859 responseWrapper.setInnerElement(responseFormat);
1860 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1864 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1865 ArtifactTypeConfig retConfig = null;
1866 String fileType = artifactType.getType();
1867 if (parentType.equals(NodeTypeEnum.Resource)) {
1868 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1869 } else if (parentType.equals(NodeTypeEnum.Service)) {
1870 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1871 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1872 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1877 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1878 // extract heat parameters
1879 if (artifactInfo.getPayloadData() != null) {
1880 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1881 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1882 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1883 log.info("failed to parse heat parameters ");
1884 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1885 return Either.right(responseFormat);
1886 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1887 artifactInfo.setListHeatParameters(heatParameters.left().value());
1890 return Either.left(true);
1895 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1896 String fileType = artifactType.getType();
1897 List<String> acceptedTypes = null;
1898 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1899 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1900 log.debug("parent type of artifact can be either resource or service");
1901 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1905 if (deploymentAcceptedTypes == null) {
1906 log.debug("parent type of artifact can be either resource or service");
1907 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1910 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1913 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1915 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1916 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1917 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1918 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1921 String artifactName = artifactInfo.getArtifactName();
1922 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1923 // Pavel - File extension validation is case-insensitive - Ella,
1925 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1926 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1927 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1932 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1934 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1935 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1936 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1938 if (errorWrapper.isEmpty()) {
1939 validateValidYaml(errorWrapper, artifactInfo);
1942 if (errorWrapper.isEmpty()) {
1943 // Validate Heat Exist
1944 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1947 // if (errorWrapper.isEmpty() && isCreate) {
1948 // // Validate Only Single HeatEnv Artifact
1949 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1952 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1953 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1956 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1957 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1961 Either<Boolean, ResponseFormat> eitherResponse;
1962 if (errorWrapper.isEmpty()) {
1963 eitherResponse = Either.left(true);
1965 eitherResponse = Either.right(errorWrapper.getInnerElement());
1967 return eitherResponse;
1970 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1971 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1972 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1973 if (fillArtifactPayload.isRight()) {
1974 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1975 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1978 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1982 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1983 Either<Boolean, ResponseFormat> result = Either.left(true);
1984 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1985 if (eitherArtifactData.isLeft()) {
1986 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1987 data = Base64.encodeBase64(data);
1988 payloadWrapper.setInnerElement(data);
1990 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1991 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1992 result = Either.right(responseFormat);
1998 @SuppressWarnings("unchecked")
1999 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2000 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2001 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2002 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2003 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2005 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2006 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2007 if (eitherHeatEnvProperties.isRight()) {
2008 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2009 errorWrapper.setInnerElement(responseFormat);
2010 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2011 } else if (eitherHeatProperties.isRight()) {
2012 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2013 errorWrapper.setInnerElement(responseFormat);
2014 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2016 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2017 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2018 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2019 if (heatEnvPropertiesKeys.size() > 0) {
2020 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2021 errorWrapper.setInnerElement(responseFormat);
2026 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2027 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2028 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2030 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2031 errorWrapper.setInnerElement(responseFormat);
2032 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2036 @SuppressWarnings("restriction")
2037 public boolean isValidXml(byte[] xmlToParse) {
2038 XMLReader parser = new SAXParser();
2040 parser.setFeature("http://apache.org/xml/features/validation/schema", false);
2041 } catch (SAXNotRecognizedException e) {
2042 e.printStackTrace();
2043 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2045 } catch (SAXNotSupportedException e) {
2046 e.printStackTrace();
2047 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2050 boolean isXmlValid = true;
2052 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2053 } catch (IOException | SAXException e) {
2054 log.debug("Xml is invalid : {}", e.getMessage(), e);
2060 public boolean isValidJson(byte[] jsonToParse) {
2061 String parsed = new String(jsonToParse);
2063 gson.fromJson(parsed, Object.class);
2064 } catch (Exception e) {
2065 log.debug("Json is invalid : {}", e.getMessage(), e);
2071 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2072 boolean typeArtifactFound = false;
2073 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2074 // (parentType == NodeTypeEnum.Resource) ?
2075 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2076 // parentComponent).iterator()
2077 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2079 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2081 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2082 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2083 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2085 if (typeArtifactFound) {
2086 String parentName = parentComponent.getName();
2087 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2089 errorWrapper.setInnerElement(responseFormat);
2090 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2095 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2096 boolean artifactNameFound = false;
2097 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2098 // (parentType == NodeTypeEnum.Resource) ?
2099 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2100 // parentComponent).iterator()
2101 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2103 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2105 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2106 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2108 if (artifactNameFound) {
2109 String parentName = parentComponent.getName();
2110 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2112 errorWrapper.setInnerElement(responseFormat);
2113 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2118 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2119 ComponentTypeEnum componentType) {
2120 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2121 if (res.isRight()) {
2122 ResponseFormat responseFormat;
2123 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2124 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2126 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2128 errorWrapper.setInnerElement(responseFormat);
2132 ArtifactDefinition heatArtifact = res.left().value();
2133 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2134 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2135 // while (!heatFound && parentArtifactsItr.hasNext()) {
2136 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2137 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2138 // heatFound = true;
2139 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2140 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2142 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2143 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2147 // if (!heatFound) {
2148 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2149 // errorWrapper.setInnerElement(responseFormat);
2150 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2155 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2156 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2157 // timeout > 0 for HEAT artifacts
2158 Integer timeout = artifactInfo.getTimeout();
2159 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2160 if (timeout == null) {
2161 artifactInfo.setTimeout(defaultTimeout);
2162 // HEAT artifact but timeout is invalid
2163 } else if (timeout < 1) {
2164 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2167 // US649856 - Allow several HEAT files on Resource
2169 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2170 * Either.right(errorWrapper.getInnerElement()); } }
2173 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2174 return Either.left(true);
2177 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2178 String listToString = (typeList != null) ? typeList.toString() : "";
2179 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2180 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2181 String resourceTypeName = resourceType.name();
2182 if (typeList != null && typeList.contains(resourceTypeName)) {
2183 either = Either.left(true);
2188 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2189 if (artifactInfo.getHeatParameters() != null) {
2190 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2191 String parameterType = heatParam.getType();
2192 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2193 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2194 if (heatParameterType == null) {
2195 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2196 return Either.right(responseFormat);
2199 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2200 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2201 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2202 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2203 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2204 return Either.right(responseFormat);
2208 return Either.left(artifactInfo);
2211 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2212 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2213 if (parentComponent.getDeploymentArtifacts() != null) {
2214 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2215 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2216 if (getRI.isRight()) {
2217 return deploymentArtifacts;
2219 ComponentInstance ri = getRI.left().value();
2220 if (ri.getDeploymentArtifacts() != null) {
2221 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2223 } else if (parentComponent.getDeploymentArtifacts() != null) {
2224 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2227 return deploymentArtifacts;
2230 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2231 // on create if null add informational to current
2232 if (artifactInfo.getArtifactGroupType() == null) {
2233 artifactInfo.setArtifactGroupType(type);
2235 if (artifactInfo.getUniqueId() != null) {
2236 log.error("artifact uniqid cannot be set ignoring");
2238 artifactInfo.setUniqueId(null);
2240 if (artifactInfo.getArtifactRef() != null) {
2241 log.error("artifact ref cannot be set ignoring");
2243 artifactInfo.setArtifactRef(null);
2245 if (artifactInfo.getArtifactRepository() != null) {
2246 log.error("artifact repository cannot be set ignoring");
2248 artifactInfo.setArtifactRepository(null);
2250 if (artifactInfo.getUserIdCreator() != null) {
2251 log.error("creator uuid cannot be set ignoring");
2253 artifactInfo.setArtifactCreator(user.getUserId());
2255 if (artifactInfo.getUserIdLastUpdater() != null) {
2256 log.error("userId of last updater cannot be set ignoring");
2258 artifactInfo.setUserIdLastUpdater(user.getUserId());
2260 if (artifactInfo.getCreatorFullName() != null) {
2261 log.error("creator Full name cannot be set ignoring");
2263 String fullName = user.getFirstName() + " " + user.getLastName();
2264 artifactInfo.setUpdaterFullName(fullName);
2266 if (artifactInfo.getUpdaterFullName() != null) {
2267 log.error("updater Full name cannot be set ignoring");
2269 artifactInfo.setUpdaterFullName(fullName);
2271 if (artifactInfo.getCreationDate() != null) {
2272 log.error("Creation Date cannot be set ignoring");
2274 long time = System.currentTimeMillis();
2275 artifactInfo.setCreationDate(time);
2277 if (artifactInfo.getLastUpdateDate() != null) {
2278 log.error("Last Update Date cannot be set ignoring");
2280 artifactInfo.setLastUpdateDate(time);
2282 if (artifactInfo.getEsId() != null) {
2283 log.error("es id cannot be set ignoring");
2285 artifactInfo.setEsId(null);
2290 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2291 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2292 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2293 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2294 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2295 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2298 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2299 String id = artifactId;
2300 if (artifactId == null || artifactId.isEmpty()) {
2301 String uniqueId = null;
2302 if (interfaceName != null && operationName != null) {
2303 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2305 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2307 artifactInfo.setUniqueId(uniqueId);
2308 artifactInfo.setEsId(uniqueId);
2311 artifactInfo.setUniqueId(artifactId);
2312 artifactInfo.setEsId(artifactId);
2317 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2318 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2319 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2320 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2321 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2324 boolean artifactTypeExist = false;
2325 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2326 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2328 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2329 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2332 allArtifactTypes = elementOperation.getAllArtifactTypes();
2334 if (allArtifactTypes.isRight()) {
2335 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2336 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2337 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2340 for (ArtifactType type : allArtifactTypes.left().value()) {
2341 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2342 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2343 artifactTypeExist = true;
2348 if (!artifactTypeExist) {
2349 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2350 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2351 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2354 return Either.left(ActionStatus.OK);
2357 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2359 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2360 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2362 if (parentType.equals(NodeTypeEnum.Service)) {
2363 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2364 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2365 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2367 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2369 if (deploymentArtifacts != null) {
2370 for (String artifactType : deploymentArtifacts.keySet()) {
2371 ArtifactType artifactT = new ArtifactType();
2372 artifactT.setName(artifactType);
2373 artifactTypes.add(artifactT);
2375 return Either.left(artifactTypes);
2377 return Either.right(ActionStatus.GENERAL_ERROR);
2382 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2383 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2384 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2386 return Either.left(true);
2390 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2391 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2392 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2395 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2396 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2397 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2399 artifactInfo.setArtifactName(normalizeFileName);
2401 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2402 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2405 return Either.left(true);
2408 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2409 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2410 log.info("artifact type is missing operation ignored");
2411 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2414 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2415 log.info("artifact type cannot be changed operation ignored");
2416 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2418 return Either.left(true);
2421 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2422 if (artifactInfo.getArtifactGroupType() == null) {
2423 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2426 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2427 log.info("artifact group type cannot be changed. operation failed");
2428 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2430 return Either.left(artifactInfo);
2433 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2435 // on update if null add informational to current
2436 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2437 currentArtifact.setArtifactGroupType(type);
2440 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2441 log.error("artifact uniqid cannot be set ignoring");
2443 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2445 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2446 log.error("artifact ref cannot be set ignoring");
2448 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2450 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2451 log.error("artifact repository cannot be set ignoring");
2453 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2455 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2456 log.error("creator uuid cannot be set ignoring");
2458 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2460 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2461 log.error("artifact creator cannot be set ignoring");
2463 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2465 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2466 log.error("userId of last updater cannot be set ignoring");
2468 artifactInfo.setUserIdLastUpdater(user.getUserId());
2470 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2471 log.error("creator Full name cannot be set ignoring");
2473 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2475 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2476 log.error("updater Full name cannot be set ignoring");
2478 String fullName = user.getFirstName() + " " + user.getLastName();
2479 artifactInfo.setUpdaterFullName(fullName);
2481 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2482 log.error("Creation Date cannot be set ignoring");
2484 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2486 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2487 log.error("Last Update Date cannot be set ignoring");
2489 long time = System.currentTimeMillis();
2490 artifactInfo.setLastUpdateDate(time);
2492 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2493 log.error("es id cannot be set ignoring");
2495 artifactInfo.setEsId(currentArtifact.getUniqueId());
2497 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2498 log.error(" Artifact Display Name cannot be set ignoring");
2500 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2502 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2503 log.debug("serviceApi cannot be set. ignoring.");
2505 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2507 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2508 log.debug("artifact group cannot be set. ignoring.");
2510 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2512 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2514 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2515 log.debug("artifact UUID cannot be set. ignoring.");
2517 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2519 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2520 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2524 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2526 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2527 for (HeatParameterDefinition parameter : heatParameters) {
2528 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2530 if (currentParam != null) {
2532 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2533 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2534 parameter.setName(currentParam.getName());
2536 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2537 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2538 parameter.setDefaultValue(currentParam.getDefaultValue());
2540 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2541 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2542 parameter.setType(currentParam.getType());
2544 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2545 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2546 parameter.setDescription(currentParam.getDescription());
2549 // check and set current value
2550 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2551 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2552 parameter.setCurrentValue(currentParam.getDefaultValue());
2558 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2560 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2561 for (HeatParameterDefinition param : currentParameters) {
2562 currentParamsMap.put(param.getUniqueId(), param);
2564 return currentParamsMap;
2567 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2568 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2569 log.debug("Artifact url cannot be empty.");
2570 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2572 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2574 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2575 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2577 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2578 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2581 return Either.left(true);
2584 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2585 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2586 log.debug("Artifact description cannot be empty.");
2587 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2589 String description = artifactInfo.getDescription();
2590 description = ValidationUtils.removeNoneUtf8Chars(description);
2591 description = ValidationUtils.normaliseWhitespace(description);
2592 description = ValidationUtils.stripOctets(description);
2593 description = ValidationUtils.removeHtmlTagsOnly(description);
2594 if (!ValidationUtils.validateIsEnglish(description)) {
2595 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2597 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2598 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2600 artifactInfo.setDescription(description);
2601 return Either.left(true);
2604 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2605 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2606 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2607 String prevArtifactId = null;
2608 String currArtifactId = artifactId;
2610 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2611 Either<ArtifactDefinition, Operation> insideEither = null;
2613 if (artifactData == null) {
2614 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2615 log.debug("Failed to create artifact object for ES.");
2616 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2617 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2618 resultOp = Either.right(responseFormat);
2621 log.trace("Try to update entry on graph");
2622 String artifactUniqueId = null;
2623 ArtifactDefinition artifactDefinition = artifactInfo;
2624 StorageOperationStatus error = null;
2626 boolean isLeft = false;
2627 if (interfaceType != null && operationName != null) {
2628 // lifecycle artifact
2630 * Operation operation = convertToOperation(artifactInfo, operationName);
2632 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2634 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2636 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2639 log.debug("Enty on graph is updated. Update artifact in ES");
2641 // Changing previous and current artifactId for auditing
2642 prevArtifactId = currArtifactId;
2643 currArtifactId = artifactDefinition.getUniqueId();
2645 NodeTypeEnum convertParentType = convertParentType(componentType);
2647 if (decodedPayload == null) {
2648 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2649 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2650 // Either<ESArtifactData, ResourceUploadStatus>
2651 // artifactfromES = daoUploader.getArtifact(artifactId);
2652 if (artifactFromCassandra.isRight()) {
2653 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2654 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2655 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2656 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2657 resultOp = Either.right(responseFormat);
2660 // clone data to new artifact
2661 artifactData.setData(artifactFromCassandra.left().value().getData());
2662 artifactData.setId(artifactFromCassandra.left().value().getId());
2665 if (artifactDefinition.getEsId() == null) {
2666 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2667 artifactData.setId(artifactDefinition.getUniqueId());
2671 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2672 isLeft = result.isLeft();
2674 artifactUniqueId = result.left().value().getUniqueId();
2675 artifactDefinition = result.left().value();
2676 String artifactType = artifactInfo.getArtifactType();
2677 if (NodeTypeEnum.Resource == convertParentType
2678 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2680 if (!artifactUniqueId.equals(artifactId)) {
2681 // need to update the generated id in heat env
2682 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2683 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2684 if (findFirst.isPresent()) {
2685 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2686 artifactEnvInfo.setArtifactChecksum(null);
2687 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2692 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2694 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2695 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2700 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2702 insideEither = Either.left(result.left().value());
2703 resultOp = Either.left(insideEither);
2704 if (error != StorageOperationStatus.OK) {
2709 error = result.right().value();
2713 // create new entry in ES
2715 if (artifactData.getData() != null) {
2716 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2717 artifactData.setId(artifactDefinition.getEsId());
2718 res = saveArtifacts(artifactData, parentId, false);
2724 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2725 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2726 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2727 // resultOp = Either.left(result.left().value());
2730 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2731 log.debug("Failed to save the artifact.");
2732 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2733 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2734 resultOp = Either.right(responseFormat);
2742 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2743 log.trace("Starting payload handling");
2744 byte[] payload = artifactInfo.getPayloadData();
2745 byte[] decodedPayload = null;
2747 if (payload != null && payload.length != 0) {
2748 // the generated artifacts were already decoded by the handler
2749 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2750 if (decodedPayload.length == 0) {
2751 log.debug("Failed to decode the payload.");
2752 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2753 return Either.right(responseFormat);
2756 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2757 artifactInfo.setArtifactChecksum(checkSum);
2758 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2760 // Specific payload validations of different types
2761 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2762 if (isDeploymentArtifact(artifactInfo)) {
2763 log.trace("Starting deployment artifacts payload validation");
2764 String artifactType = artifactInfo.getArtifactType();
2765 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2766 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2767 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2768 if (isValidPayload.isLeft()) {
2769 isValidPayload = extractHeatParameters(artifactInfo);
2771 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2772 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2773 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
2774 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2776 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2778 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2779 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2780 String artifactFileName = artifactInfo.getArtifactName();
2781 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2782 switch (fileExtension) {
2784 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2787 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2791 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2796 if (isValidPayload.isRight()) {
2797 ResponseFormat responseFormat = isValidPayload.right().value();
2798 return Either.right(responseFormat);
2801 } // null/empty payload is normal if called from metadata update ONLY.
2802 // The validation of whether this is metadata/payload update case is
2803 // currently done separately
2805 if (!isArtifactMetadataUpdate) {
2806 log.debug("Payload is missing.");
2807 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2808 return Either.right(responseFormat);
2811 log.trace("Ended payload handling");
2812 return Either.left(decodedPayload);
2815 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2816 // Basic YAML validation
2817 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2818 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2819 log.debug("Invalid YAML format");
2820 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2821 return Either.right(responseFormat);
2823 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2824 // HEAT specific YAML validation
2825 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2826 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2827 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2829 return Either.right(responseFormat);
2833 return Either.left(true);
2836 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2837 Either<Boolean, ResponseFormat> res = Either.left(true);
2838 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2839 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2840 log.debug("Invalid YAML format");
2841 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2842 res = Either.right(responseFormat);
2848 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
2849 boolean isXmlValid = isValidXml(payload);
2851 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2852 log.debug("Invalid XML content");
2853 return Either.right(responseFormat);
2855 return Either.left(true);
2858 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2859 boolean isJsonValid = isValidJson(payload);
2861 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2862 log.debug("Invalid JSON content");
2863 return Either.right(responseFormat);
2865 return Either.left(true);
2868 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2869 if (opState == null || opState.isRight()) {
2870 titanDao.rollback();
2876 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2877 boolean inTransaction) {
2878 User user = new User();
2879 user.setUserId(userUserId);
2880 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2881 if (parent.isRight()) {
2882 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2883 return Either.right(responseFormat);
2885 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2886 false, inTransaction);
2887 if (handleDelete.isRight()) {
2888 return Either.right(handleDelete.right().value());
2890 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2891 return Either.left(result.right().value());
2895 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2897 if (artifacts != null && !artifacts.isEmpty()) {
2898 for (ArtifactDefinition artifactDefinition : artifacts) {
2899 String esId = artifactDefinition.getEsId();
2900 if (esId != null && !esId.isEmpty()) {
2901 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2902 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2903 return deleteIfNotOnGraph;
2908 return StorageOperationStatus.OK;
2911 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2912 Operation op = new Operation();
2913 long time = System.currentTimeMillis();
2914 op.setCreationDate(time);
2916 String artifactName = artifactInfo.getArtifactName();
2917 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2919 op.setImplementation(artifactInfo);
2920 op.setLastUpdateDate(time);
2924 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2925 String newArtifactName = operationName + "_" + artifactName;
2926 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2927 return newArtifactName;
2930 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2931 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2932 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2933 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2934 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2936 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2937 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2938 // // last one. need to delete in ES
2939 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2940 // artifactCassandraDao.deleteArtifact(artifactEsId);
2941 // return StorageOperationStatus.OK;
2943 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2947 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2948 // return StorageOperationStatus.OK;
2952 return StorageOperationStatus.OK;
2956 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2958 // General validation
2959 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2960 log.debug("One of the function parameteres is null");
2961 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2964 // Normalizing artifact name
2965 artifactName = ValidationUtils.normalizeFileName(artifactName);
2967 // Resource validation
2968 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2969 if (validateResourceNameAndVersion.isRight()) {
2970 return Either.right(validateResourceNameAndVersion.right().value());
2973 Resource resource = validateResourceNameAndVersion.left().value();
2974 String resourceId = resource.getUniqueId();
2976 // Service validation
2977 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2978 if (validateServiceNameAndVersion.isRight()) {
2979 return Either.right(validateServiceNameAndVersion.right().value());
2982 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2983 if (artifacts == null || artifacts.isEmpty()) {
2984 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2985 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2988 ArtifactDefinition deploymentArtifact = null;
2990 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2991 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2992 log.debug("Found deployment artifact {}", artifactName);
2993 deploymentArtifact = artifactDefinition;
2998 if (deploymentArtifact == null) {
2999 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3000 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3003 // Downloading the artifact
3004 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3005 if (downloadArtifactEither.isRight()) {
3006 log.debug("Download artifact {} failed", artifactName);
3007 return Either.right(downloadArtifactEither.right().value());
3009 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3010 return Either.left(downloadArtifactEither.left().value().getRight());
3014 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3016 // General validation
3017 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3018 log.debug("One of the function parameteres is null");
3019 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3022 // Normalizing artifact name
3023 artifactName = ValidationUtils.normalizeFileName(artifactName);
3025 // Resource validation
3027 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3028 * Either.right(validateResourceNameAndVersion.right().value()); }
3030 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3033 // Service validation
3034 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3035 if (validateServiceNameAndVersion.isRight()) {
3036 return Either.right(validateServiceNameAndVersion.right().value());
3039 Service service = validateServiceNameAndVersion.left().value();
3041 // ResourceInstance validation
3042 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3043 if (validateResourceInstance.isRight()) {
3044 return Either.right(validateResourceInstance.right().value());
3047 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3049 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3051 final String finalArtifactName = artifactName;
3052 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3054 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3055 ArtifactDefinition deployableArtifact;
3057 if (!hasDeploymentArtifacts) {
3058 log.debug("Deployment artifact with name {} not found", artifactName);
3059 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3062 log.debug("Found deployment artifact {}", artifactName);
3063 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3064 // Downloading the artifact
3065 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3067 if (downloadArtifactEither.isRight()) {
3068 log.debug("Download artifact {} failed", artifactName);
3069 return Either.right(downloadArtifactEither.right().value());
3071 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3072 return Either.left(downloadArtifactEither.left().value().getRight());
3075 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3077 List<ComponentInstance> riList = service.getComponentInstances();
3078 for (ComponentInstance ri : riList) {
3079 if (ri.getNormalizedName().equals(resourceInstanceName))
3080 return Either.left(ri);
3083 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3086 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3088 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3089 if (serviceListBySystemName.isRight()) {
3090 log.debug("Couldn't fetch any service with name {}", serviceName);
3091 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3093 List<Service> serviceList = serviceListBySystemName.left().value();
3094 if (serviceList == null || serviceList.isEmpty()) {
3095 log.debug("Couldn't fetch any service with name {}", serviceName);
3096 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3099 Service foundService = null;
3100 for (Service service : serviceList) {
3101 if (service.getVersion().equals(serviceVersion)) {
3102 log.trace("Found service with version {}", serviceVersion);
3103 foundService = service;
3108 if (foundService == null) {
3109 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3110 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3112 return Either.left(foundService);
3115 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3117 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3118 if (resourceListBySystemName.isRight()) {
3119 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3120 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3122 return Either.left(resourceListBySystemName.left().value());
3125 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3127 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3128 if (serviceName == null || serviceVersion == null || artifactName == null) {
3129 log.debug("One of the function parameteres is null");
3130 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3133 // Normalizing artifact name
3134 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3136 // Service validation
3137 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3138 if (validateServiceNameAndVersion.isRight()) {
3139 return Either.right(validateServiceNameAndVersion.right().value());
3142 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3144 // Looking for deployment or tosca artifacts
3145 Service service = validateServiceNameAndVersion.left().value();
3147 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3148 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3149 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3152 Optional<ArtifactDefinition> foundArtifactOptl = null;
3154 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3155 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3156 // filters artifact by name
3157 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3159 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3160 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3161 // filters TOSCA artifact by name
3162 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3164 if (!foundArtifactOptl.isPresent()) {
3165 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3166 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3168 log.debug("Found deployment artifact {}", normalizedArtifactName);
3169 // Downloading the artifact
3170 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
3171 if (downloadArtifactEither.isRight()) {
3172 log.debug("Download artifact {} failed", normalizedArtifactName);
3173 return Either.right(downloadArtifactEither.right().value());
3175 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3176 return Either.left(downloadArtifactEither.left().value().getRight());
3179 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3180 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3181 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3182 if (artifactById.isRight()) {
3183 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3184 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3185 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3187 ArtifactDefinition artifactDefinition = artifactById.left().value();
3188 if (artifactDefinition == null) {
3189 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3190 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3193 return downloadArtifact(artifactDefinition);
3196 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3197 boolean found = false;
3198 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3199 if (artifactsS != null) {
3200 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3201 if (entry.getValue().getUniqueId().equals(artifactId)) {
3207 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3208 if (!found && deploymentArtifactsS != null) {
3209 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3210 if (entry.getValue().getUniqueId().equals(artifactId)) {
3216 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3217 if (!found && toscaArtifactsS != null) {
3218 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3219 if (entry.getValue().getUniqueId().equals(artifactId)) {
3225 switch (component.getComponentType()) {
3227 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3228 if (!found && interfaces != null) {
3229 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3230 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3231 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3232 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3241 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3242 if (!found && apiArtifacts != null) {
3243 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3244 if (entry.getValue().getUniqueId().equals(artifactId)) {
3258 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3260 boolean found = false;
3261 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3262 ComponentInstance resourceInstance = null;
3263 for (ComponentInstance ri : resourceInstances) {
3264 if (ri.getUniqueId().equals(resourceInstanceId)) {
3265 resourceInstance = ri;
3269 if (resourceInstance != null) {
3270 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3271 if (artifacts != null) {
3272 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3273 if (entry.getValue().getUniqueId().equals(artifactId)) {
3280 artifacts = resourceInstance.getArtifacts();
3281 if (artifacts != null) {
3282 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3283 if (entry.getValue().getUniqueId().equals(artifactId)) {
3294 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3295 String containerComponentType, boolean inTransaction) {
3297 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3298 componentForAudit.getNodeType();
3300 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3302 if (componentResult.isRight()) {
3303 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3304 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3305 log.debug("Service not found, serviceId {}", componentId);
3306 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3307 return Either.right(responseFormat);
3309 return Either.left(componentResult.left().value());
3312 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3313 ComponentTypeEnum componentType) {
3314 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3315 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3316 if (canWork.isRight()) {
3317 String uniqueId = component.getUniqueId();
3318 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3319 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3320 return Either.right(canWork.right().value());
3323 return Either.left(true);
3326 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3328 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3329 String role = user.getRole();
3330 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3331 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3332 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3333 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3334 return Either.right(responseFormat);
3337 return Either.left(true);
3340 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3341 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3343 if (validateUserExists.isRight()) {
3344 User user = new User();
3345 user.setUserId(userId);
3346 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3347 return Either.right(validateUserExists.right().value());
3349 return Either.left(validateUserExists.left().value());
3352 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3353 AuditingActionEnum auditingAction = null;
3354 switch (operation.getArtifactOperationEnum()) {
3356 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3359 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3362 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3365 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3370 return auditingAction;
3373 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3374 String esArtifactId = artifactDefinition.getEsId();
3375 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3376 if (artifactfromES.isRight()) {
3377 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3378 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3379 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3380 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3381 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3384 ESArtifactData esArtifactData = artifactfromES.left().value();
3385 byte[] data = esArtifactData.getDataAsArray();
3387 log.debug("Artifact data from ES is null");
3388 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3390 String artifactName = artifactDefinition.getArtifactName();
3391 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3392 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3395 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3396 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3397 return artifactData;
3400 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3402 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3404 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3405 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3407 log.info("Failed to save artifact {}.", artifactData.getId());
3413 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3414 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3417 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3418 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3421 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3422 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3423 if (user.isRight()) {
3424 ResponseFormat responseFormat;
3425 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3426 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3427 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3429 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3430 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3432 return Either.right(responseFormat);
3435 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3436 return Either.left(artifactDefinition);
3439 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3440 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3442 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3443 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3444 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3446 artifactInfo.setArtifactDisplayName(artifactName);
3447 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3448 artifactInfo.setArtifactType(artifactType);
3449 artifactInfo.setDescription(artifactDescription);
3450 artifactInfo.setArtifactGroupType(groupType);
3451 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3453 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3455 return artifactInfo;
3458 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3459 String uniqueId = null;
3461 if (resourceId != null) {
3462 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3463 artifactInfo.setUniqueId(uniqueId);
3465 artifactInfo.setUserIdCreator(user.getUserId());
3466 String fullName = user.getFullName();
3467 artifactInfo.setUpdaterFullName(fullName);
3469 long time = System.currentTimeMillis();
3471 artifactInfo.setCreatorFullName(fullName);
3472 artifactInfo.setCreationDate(time);
3474 artifactInfo.setLastUpdateDate(time);
3475 artifactInfo.setUserIdLastUpdater(user.getUserId());
3477 artifactInfo.setMandatory(true);
3480 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3481 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3484 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3485 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3488 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3490 byte[] payload = payloadStr.getBytes();
3492 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3493 return Either.left(artifactData);
3498 * @param artifactDefinition
3501 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3502 boolean shouldLock, String instanceId) {
3503 String payload = generateHeatEnvPayload(artifactDefinition);
3504 String prevUUID = artifactDefinition.getArtifactUUID();
3505 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3506 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3507 if (generateResult.isLeft()) {
3508 ArtifactDefinition updatedArtDef = generateResult.left().value();
3509 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3510 List<ComponentInstance> componentInstances = component.getComponentInstances();
3511 if (componentInstances != null) {
3512 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3513 if (findFirst.isPresent()) {
3514 ComponentInstance relevantInst = findFirst.get();
3515 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3517 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3518 updatedGroupInstances.forEach(gi -> {
3519 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3520 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3522 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3523 if (status.isRight()) {
3524 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3525 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3526 return Either.right(responseFormat);
3534 return generateResult;
3537 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3538 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3539 StringBuilder sb = new StringBuilder();
3540 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3541 sb.append("parameters:\n");
3542 if (heatParameters != null) {
3543 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3545 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3547 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3549 String heatValue = heatParameterDefinition.getCurrentValue();
3550 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3551 heatValue = heatParameterDefinition.getDefaultValue();
3552 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3553 empltyHeatValues.add(heatParameterDefinition);
3557 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3561 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3564 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3566 case COMMA_DELIMITED_LIST:
3568 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3571 String value = heatValue;
3572 boolean starts = value.startsWith("\"");
3573 boolean ends = value.endsWith("\"");
3574 if (!(starts && ends)) {
3575 starts = value.startsWith("'");
3576 ends = value.endsWith("'");
3577 if (!(starts && ends)) {
3578 value = "\"" + value + "\"";
3581 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3588 if (!empltyHeatValues.isEmpty()) {
3589 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3590 empltyHeatValues.forEach(hv -> {
3591 sb.append(" ").append(hv.getName()).append(":");
3592 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3593 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3594 sb.append(" \"\"").append("\n");
3596 sb.append(" ").append("\n");
3601 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3604 String result = sb.toString().replaceAll("\\\\n", "\n");
3611 * @param artifactDefinition
3615 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3616 User modifier, boolean shouldLock, String instanceId) {
3617 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3618 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3622 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3623 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3625 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3626 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3628 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3629 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3630 ESArtifactData artifactData = null;
3632 if (artifactDataRes.isLeft()) {
3633 artifactData = artifactDataRes.left().value();
3635 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3636 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3637 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3639 return Either.right(artifactDataRes.right().value());
3641 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3643 String esArtifactId = artifactDefinition.getEsId();
3644 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3645 ESArtifactData esArtifactData;
3646 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3647 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3648 if (artifactfromES.isRight()) {
3649 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3650 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3651 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3652 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3653 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3655 esArtifactData = artifactfromES.left().value();
3656 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3658 oldCheckSum = artifactDefinition.getArtifactChecksum();
3661 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3664 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3665 if (lockComponent.isRight()) {
3666 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3667 return Either.right(lockComponent.right().value());
3671 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3673 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3674 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3675 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3676 if (updateArifactDefinitionStatus.isRight()) {
3677 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3678 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3679 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3680 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3682 return Either.right(responseFormat);
3686 oldCheckSum = artifactDefinition.getArtifactChecksum();
3687 artifactDefinition.setArtifactChecksum(newCheckSum);
3688 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3689 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3690 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3691 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3693 log.trace("Update Payload ", artifactDefinition.getEsId());
3695 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3697 artifactDefinition = updateArifactDefinitionStatus.left().value();
3698 artifactData.setId(artifactDefinition.getUniqueId());
3699 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3701 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3703 log.debug("Artifact Saved In ES {}", artifactData.getId());
3704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3705 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3706 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3709 titanDao.rollback();
3710 log.info("Failed to save artifact {}.", artifactData.getId());
3711 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3712 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3713 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3715 return Either.right(responseFormat);
3718 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3719 log.debug("Failed To update artifact {}", artifactData.getId());
3720 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3721 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3723 return Either.right(responseFormat);
3728 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3733 return Either.left(artifactDefinition);
3736 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3737 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3738 convertParentType(componentType);
3739 String parentId = parent.getUniqueId();
3740 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3741 ArtifactDefinition currArtifact = artifactInfo;
3743 if (origMd5 != null) {
3744 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3745 if (validateMd5.isRight()) {
3746 ResponseFormat responseFormat = validateMd5.right().value();
3747 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3748 return Either.right(responseFormat);
3751 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3752 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3753 if (deploymentValidationResult.isRight()) {
3754 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3755 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3756 return Either.right(responseFormat);
3759 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3760 if (payloadEither.isRight()) {
3761 ResponseFormat responseFormat = payloadEither.right().value();
3762 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3763 return Either.right(responseFormat);
3765 } else { // duplicate
3766 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3767 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3768 return Either.right(responseFormat);
3774 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3775 if (lockComponent.isRight()) {
3776 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3777 return Either.right(lockComponent.right().value());
3780 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3782 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3787 if (resultOp == null || resultOp.isRight()) {
3788 log.debug("all changes rollback");
3789 if (false == inTransaction)
3790 titanDao.rollback();
3792 log.debug("all changes committed");
3793 if (false == inTransaction)
3797 componentType = parent.getComponentType();
3798 NodeTypeEnum nodeType = componentType.getNodeType();
3799 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3800 // graphLockOperation.unlockComponent(parentId, parentType);
3804 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3805 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3807 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3808 Either<ArtifactDefinition, Operation> insideEither = null;
3810 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3812 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3813 if (getRI.isRight()) {
3814 return Either.right(getRI.right().value());
3816 ComponentInstance ri = getRI.left().value();
3817 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3818 if (getArtifactRes.isRight()) {
3819 return Either.right(getArtifactRes.right().value());
3821 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3823 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3824 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3825 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3826 return Either.right(responseFormat);
3828 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3829 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3830 new ArrayList<HeatParameterDefinition>();
3833 if (origMd5 != null) {
3834 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3835 updatedHeatEnvParams, currArtifact.getArtifactName());
3836 if (uploadParamsValidationResult.isRight()) {
3837 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3838 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3839 return Either.right(responseFormat);
3841 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3844 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3845 if (validateAndConvertHeatParamers.isRight()) {
3846 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3847 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3848 return Either.right(responseFormat);
3851 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3853 // fill reduced heat env parameters List for updating
3854 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3855 paramName = heatEnvParam.getName();
3856 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3857 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3858 String updatedParamValue = heatEnvParam.getCurrentValue();
3859 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3860 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3861 } else if (updatedParamValue != null) {
3862 currHeatParam.setCurrentValue(updatedParamValue);
3867 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3868 currArtifact.setListHeatParameters(currentHeatEnvParams);
3870 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3871 if (updateArifactRes.isRight()) {
3872 log.debug("Failed to update artifact on graph - {}", artifactId);
3873 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3874 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3875 return Either.right(responseFormat);
3877 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3878 if (error != StorageOperationStatus.OK) {
3879 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3880 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3881 return Either.right(responseFormat);
3884 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3885 if (error != StorageOperationStatus.OK) {
3886 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3887 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3888 return Either.right(responseFormat);
3894 insideEither = Either.left(currArtifact);
3895 resultOp = Either.left(insideEither);
3896 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3897 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3901 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3902 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3904 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3905 Either<ArtifactDefinition, Operation> insideEither = null;
3907 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3909 String currentHeatId = currHeatArtifact.getUniqueId();
3911 String esArtifactId = currHeatArtifact.getEsId();
3912 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3913 if (artifactfromES.isRight()) {
3914 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3915 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3916 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3917 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3918 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3921 ESArtifactData esArtifactData = artifactfromES.left().value();
3922 byte[] data = esArtifactData.getDataAsArray();
3925 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3927 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3928 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3929 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3931 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3934 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3936 paramName = heatEnvParam.getName();
3937 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3938 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3940 String updatedParamValue = heatEnvParam.getCurrentValue();
3941 if (updatedParamValue == null)
3942 updatedParamValue = heatEnvParam.getDefaultValue();
3943 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3944 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3945 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3946 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3947 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3948 return Either.right(responseFormat);
3951 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3952 newHeatEnvParams.add(currHeatParam);
3957 if (!newHeatEnvParams.isEmpty()) {
3958 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3959 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3961 if (operationStatus.isRight()) {
3962 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3964 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3965 return Either.right(responseFormat);
3968 updatedHeatArt = operationStatus.left().value();
3970 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3971 esArtifactData.setId(updatedHeatArt.getEsId());
3972 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3975 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3976 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3977 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3978 // resultOp = Either.left(result.left().value());
3981 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3982 log.debug("Failed to save the artifact.");
3983 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3984 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3985 resultOp = Either.right(responseFormat);
3989 insideEither = Either.left(updatedHeatArt);
3992 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3993 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3994 artifactEnvInfo.setArtifactChecksum(null);
3995 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3997 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
4000 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4001 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
4002 if (result != ActionStatus.OK) {
4003 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4004 return Either.right(responseFormat);
4008 if (updatedHeatEnvParams.isEmpty()) {
4009 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
4011 resultOp = Either.left(insideEither);
4012 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4013 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4018 private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4019 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4020 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4021 return Either.right(responseFormat);
4025 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4026 StorageOperationStatus error = StorageOperationStatus.OK;
4027 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4028 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4029 // List<GroupInstance> associatedGroups = null;
4030 List<String> groupInstancesId = null;
4031 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4032 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4034 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4035 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4036 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4042 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4043 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4045 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4046 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4047 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4048 return Either.right(responseFormat);
4051 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4052 String paramName = uploadedHeatParam.getName();
4053 boolean isExistsInHeat = false;
4054 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4055 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4057 isExistsInHeat = true;
4058 uploadedHeatParam.setType(currHeatParam.getType());
4059 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4060 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4061 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4065 if (!isExistsInHeat) {
4066 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4067 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4068 return Either.right(responseFormat);
4071 return Either.left(updatedHeatEnvParams);
4074 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4075 ResponseFormat responseFormat = null;
4076 List<ComponentInstance> ris = component.getComponentInstances();
4077 for (ComponentInstance ri : ris) {
4078 if (riID.equals(ri.getUniqueId())) {
4079 return Either.left(ri);
4082 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4083 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4084 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4085 return Either.right(responseFormat);
4088 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4089 ResponseFormat responseFormat = null;
4090 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4091 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4092 if (artifactId.equals(artifact.getUniqueId())) {
4093 return Either.left(artifact);
4096 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4097 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4098 return Either.right(responseFormat);
4101 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4102 ArtifactDefinition ret;
4103 if (eitherArtifact.isLeft()) {
4104 ret = eitherArtifact.left().value();
4106 ret = eitherArtifact.right().value().getImplementationArtifact();
4112 * downloads artifact of component by UUIDs
4114 * @param componentType
4115 * @param componentUuid
4116 * @param artifactUUID
4117 * @param auditAdditionalParam
4120 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4121 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4122 Either<byte[], ResponseFormat> result;
4123 byte[] downloadedArtifact = null;
4124 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4125 if (errorWrapper.isEmpty()) {
4126 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4127 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4129 if (errorWrapper.isEmpty()) {
4130 result = Either.left(downloadedArtifact);
4132 result = Either.right(errorWrapper.getInnerElement());
4138 * downloads an artifact of resource instance of component by UUIDs
4140 * @param componentType
4141 * @param componentUuid
4142 * @param resourceName
4143 * @param artifactUUID
4144 * @param auditAdditionalParam
4147 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4148 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4149 Either<byte[], ResponseFormat> result;
4150 byte[] downloadedArtifact = null;
4151 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4152 if (errorWrapper.isEmpty()) {
4153 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4155 if (errorWrapper.isEmpty()) {
4156 result = Either.left(downloadedArtifact);
4158 result = Either.right(errorWrapper.getInnerElement());
4164 * uploads an artifact to a component by UUID
4168 * @param componentType
4169 * @param componentUuid
4170 * @param additionalParams
4174 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4175 ArtifactOperationInfo operation) {
4176 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4177 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4178 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4179 ArtifactDefinition uploadArtifact = null;
4180 Component component = null;
4181 String componentId = null;
4182 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4183 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4184 String userId = request.getHeader(Constants.USER_ID_HEADER);
4186 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4187 if (getComponentRes.isRight()) {
4188 StorageOperationStatus status = getComponentRes.right().value();
4189 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4190 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4192 if (errorWrapper.isEmpty()) {
4193 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4194 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4196 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4197 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4198 if (component != null) {
4199 componentId = component.getUniqueId();
4200 componentName = component.getName();
4203 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4205 if (errorWrapper.isEmpty()) {
4206 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4207 if (actionResult.isRight()) {
4208 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4209 errorWrapper.setInnerElement(actionResult.right().value());
4212 if (errorWrapper.isEmpty()) {
4213 uploadArtifact = actionResult.left().value().left().value();
4214 uploadArtifactResult = Either.left(uploadArtifact);
4216 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4218 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4219 return uploadArtifactResult;
4223 * upload an artifact to a resource instance by UUID
4227 * @param componentType
4228 * @param componentUuid
4229 * @param resourceInstanceName
4230 * @param additionalParams
4234 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4235 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4236 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4237 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4238 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4239 ArtifactDefinition uploadArtifact = null;
4240 Component component = null;
4241 String componentInstanceId;
4243 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4244 String userId = request.getHeader(Constants.USER_ID_HEADER);
4246 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4247 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4248 if (getComponentRes.isRight()) {
4249 StorageOperationStatus status = getComponentRes.right().value();
4250 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4251 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4253 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4254 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4256 if (errorWrapper.isEmpty()) {
4257 if (component == null) {
4258 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4260 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4263 if (errorWrapper.isEmpty()) {
4264 componentInstanceId = componentRiPair.getRight().getUniqueId();
4265 componentId = componentRiPair.getLeft().getUniqueId();
4266 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4268 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4269 if (actionResult.isRight()) {
4270 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4271 errorWrapper.setInnerElement(actionResult.right().value());
4274 if (errorWrapper.isEmpty()) {
4275 uploadArtifact = actionResult.left().value().left().value();
4276 uploadArtifactResult = Either.left(uploadArtifact);
4278 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4280 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4281 return uploadArtifactResult;
4285 * updates an artifact on a component by UUID
4289 * @param componentType
4290 * @param componentUuid
4291 * @param artifactUUID
4292 * @param additionalParams
4297 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4298 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4299 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4300 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4301 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4302 ArtifactDefinition updateArtifact = null;
4303 Component component = null;
4304 String componentId = null;
4305 String artifactId = null;
4306 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4307 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4308 String userId = request.getHeader(Constants.USER_ID_HEADER);
4310 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4311 if (getComponentRes.isRight()) {
4312 StorageOperationStatus status = getComponentRes.right().value();
4313 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4314 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4316 if (errorWrapper.isEmpty()) {
4317 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4318 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4320 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4321 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4322 if (component != null) {
4323 componentId = component.getUniqueId();
4324 componentName = component.getName();
4327 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4329 if (errorWrapper.isEmpty()) {
4330 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4332 if (errorWrapper.isEmpty()) {
4333 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4334 if (actionResult.isRight()) {
4335 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4336 errorWrapper.setInnerElement(actionResult.right().value());
4339 if (errorWrapper.isEmpty()) {
4340 updateArtifact = actionResult.left().value().left().value();
4341 updateArtifactResult = Either.left(updateArtifact);
4344 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4346 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4347 return updateArtifactResult;
4351 * updates an artifact on a resource instance by UUID
4355 * @param componentType
4356 * @param componentUuid
4357 * @param resourceInstanceName
4358 * @param artifactUUID
4359 * @param additionalParams
4364 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4365 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4367 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4368 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4369 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4370 ArtifactDefinition updateArtifact = null;
4371 Component component = null;
4372 String componentInstanceId = null;
4373 String componentId = null;
4374 String artifactId = null;
4375 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4376 String userId = request.getHeader(Constants.USER_ID_HEADER);
4378 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4379 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4380 if (getComponentRes.isRight()) {
4381 StorageOperationStatus status = getComponentRes.right().value();
4382 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4383 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4385 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4386 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4388 if (errorWrapper.isEmpty()) {
4389 if (component == null) {
4390 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4392 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4395 if (errorWrapper.isEmpty()) {
4396 componentInstanceId = componentRiPair.getRight().getUniqueId();
4397 componentId = componentRiPair.getLeft().getUniqueId();
4398 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4400 if (errorWrapper.isEmpty()) {
4401 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4403 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4404 if (actionResult.isRight()) {
4405 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4406 errorWrapper.setInnerElement(actionResult.right().value());
4409 if (errorWrapper.isEmpty()) {
4410 updateArtifact = actionResult.left().value().left().value();
4411 updateArtifactResult = Either.left(updateArtifact);
4413 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4415 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4416 return updateArtifactResult;
4420 * deletes an artifact on a component by UUID
4423 * @param componentType
4424 * @param componentUuid
4425 * @param artifactUUID
4426 * @param additionalParams
4431 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4432 ArtifactOperationInfo operation) {
4434 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4435 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4436 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4437 ArtifactDefinition deleteArtifact = null;
4438 Component component = null;
4439 String componentId = null;
4440 String artifactId = null;
4441 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4442 String userId = request.getHeader(Constants.USER_ID_HEADER);
4444 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4445 if (getComponentRes.isRight()) {
4446 StorageOperationStatus status = getComponentRes.right().value();
4447 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4448 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4450 if (errorWrapper.isEmpty()) {
4451 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4452 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4453 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4454 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4455 if (component != null) {
4456 componentId = component.getUniqueId();
4457 componentName = component.getName();
4460 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4462 if (errorWrapper.isEmpty()) {
4463 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4465 if (errorWrapper.isEmpty()) {
4466 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4467 if (actionResult.isRight()) {
4468 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4469 errorWrapper.setInnerElement(actionResult.right().value());
4472 if (errorWrapper.isEmpty()) {
4473 deleteArtifact = actionResult.left().value().left().value();
4474 deleteArtifactResult = Either.left(deleteArtifact);
4476 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4478 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4479 return deleteArtifactResult;
4483 * deletes an artifact from a resource instance by UUID
4486 * @param componentType
4487 * @param componentUuid
4488 * @param resourceInstanceName
4489 * @param artifactUUID
4490 * @param additionalParams
4495 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4496 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4498 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4499 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4500 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4501 ArtifactDefinition deleteArtifact = null;
4502 Component component = null;
4503 String componentInstanceId = null;
4504 String componentId = null;
4505 String artifactId = null;
4506 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4507 String userId = request.getHeader(Constants.USER_ID_HEADER);
4508 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4509 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4510 if (getComponentRes.isRight()) {
4511 StorageOperationStatus status = getComponentRes.right().value();
4512 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4513 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4515 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4516 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4518 if (errorWrapper.isEmpty()) {
4519 if (component == null) {
4520 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4522 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4525 if (errorWrapper.isEmpty()) {
4526 componentInstanceId = componentRiPair.getRight().getUniqueId();
4527 componentId = componentRiPair.getLeft().getUniqueId();
4528 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4530 if (errorWrapper.isEmpty()) {
4532 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4534 if (actionResult.isRight()) {
4535 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4536 errorWrapper.setInnerElement(actionResult.right().value());
4539 if (errorWrapper.isEmpty()) {
4540 deleteArtifact = actionResult.left().value().left().value();
4541 deleteArtifactResult = Either.left(deleteArtifact);
4543 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4545 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4546 return deleteArtifactResult;
4549 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4550 String artifactId = null;
4551 ArtifactDefinition foundArtifact = null;
4552 if (instance.getDeploymentArtifacts() != null) {
4553 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4555 if (foundArtifact == null && instance.getArtifacts() != null) {
4556 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4558 if (foundArtifact == null) {
4559 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4560 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4562 artifactId = foundArtifact.getUniqueId();
4567 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4568 Map<String, String> existingEnvVersions) {
4569 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4573 @SuppressWarnings("unchecked")
4574 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4575 Map<String, String> existingEnvVersions, boolean overrideId) {
4576 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4577 if (deploymentResourceArtifacts == null) {
4578 log.debug("no deployment artifacts are configured for generated artifacts");
4579 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4581 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4582 if (placeHolderData == null) {
4583 log.debug("no env type {} are configured for generated artifacts", envType);
4584 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4587 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4588 String parentIdParam = parentId;
4590 parentIdParam = null;
4592 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4593 if (createArtifactPlaceHolder.isRight()) {
4594 return Either.right(createArtifactPlaceHolder.right().value());
4596 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4598 // fix for migration only!!!! create heat env placeholder according to heat id.
4599 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4602 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4603 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4604 artifactHeatEnv.setTimeout(0);
4605 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4606 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4607 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4608 // clone heat parameters in case of heat env only not VF heat env
4609 if (envType.equals(HEAT_ENV_NAME)) {
4610 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4612 ArtifactDefinition artifactDefinition;
4613 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4614 if (parentType != NodeTypeEnum.ResourceInstance) {
4615 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4616 if (addHeatEnvArtifact.isRight()) {
4617 log.debug("failed to create heat env artifact on resource instance");
4618 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4620 artifactDefinition = createArtifactPlaceHolder.left().value();
4622 artifactDefinition = artifactHeatEnv;
4623 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4626 if (artifact.getHeatParameters() != null) {
4627 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4628 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4629 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4630 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4631 heatEnvParameters.add(heatEnvParameter);
4633 artifactDefinition.setListHeatParameters(heatEnvParameters);
4637 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4638 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4639 ComponentTypeEnum componentType = component.getComponentType();
4640 if (parentType == NodeTypeEnum.ResourceInstance) {
4641 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4643 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4644 return Either.left(artifactDefinition);
4647 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4648 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4649 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4650 String name = heatArtifact.getArtifactName();
4653 name = heatArtifact.getArtifactLabel();
4654 fileName = name + "." + envExtension;
4656 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4658 heatEnvArtifact.setArtifactName(fileName);
4661 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4662 if (null != existingEnvVersions) {
4663 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4664 if (null != prevVersion) {
4665 heatEnvArtifact.setArtifactVersion(prevVersion);
4671 * Handles Artifacts Request For Inner Component
4673 * @param artifactsToHandle
4676 * @param vfcsNewCreatedArtifacts
4679 * @param inTransaction
4682 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4683 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4685 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4686 ComponentTypeEnum componentType = component.getComponentType();
4687 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4688 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4689 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4693 for (ArtifactDefinition artifact : artifactsToHandle) {
4694 originData = buildJsonStringForCsarVfcArtifact(artifact);
4695 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4696 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4697 if (actionResult.isRight()) {
4698 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4699 errorWrapper.setInnerElement(actionResult.right().value());
4700 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4701 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4705 uploadedArtifacts.add(actionResult.left().value().left().value());
4707 if (errorWrapper.isEmpty()) {
4708 handleArtifactsResult = Either.left(uploadedArtifacts);
4710 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4712 } catch (Exception e) {
4713 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4714 handleArtifactsResult = Either.right(responseFormat);
4715 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4717 return handleArtifactsResult;
4720 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4721 ComponentInstance componentInstance = null;
4722 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4723 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4724 if (errorWrapper.isEmpty()) {
4725 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4726 if (componentInstance == null) {
4727 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4728 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4731 return componentInstance;
4734 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4736 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4737 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4738 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4739 if (componentInstance == null) {
4740 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4741 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4743 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4745 return relatedComponentComponentInstancePair;
4748 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4749 ComponentInstance componentInstance;
4750 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4751 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4752 if (errorWrapper.isEmpty()) {
4753 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4754 if (componentInstance == null) {
4755 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4756 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4758 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4761 return relatedComponentComponentInstancePair;
4764 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4766 byte[] downloadedArtifact = null;
4767 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4768 List<ArtifactDefinition> artifactsList = null;
4769 ArtifactDefinition deploymentArtifact = null;
4770 if (artifacts != null && !artifacts.isEmpty()) {
4771 artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4773 if (artifactsList == null || artifactsList.isEmpty()) {
4774 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4775 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4777 if (errorWrapper.isEmpty()) {
4778 deploymentArtifact = artifactsList.get(0);
4779 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4780 if (downloadArtifactEither.isRight()) {
4781 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4782 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4785 if (errorWrapper.isEmpty()) {
4786 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4787 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4789 return downloadedArtifact;
4792 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4793 Component component = null;
4794 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4795 if (getComponentRes.isRight()) {
4796 StorageOperationStatus status = getComponentRes.right().value();
4797 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4798 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4800 component = getComponentRes.left().value();
4805 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4806 Component component = null;
4807 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4808 if (getComponentRes.isRight()) {
4809 StorageOperationStatus status = getComponentRes.right().value();
4810 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4811 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4813 List<Component> value = getComponentRes.left().value();
4814 if (value.isEmpty()){
4815 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4816 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4817 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4819 component = value.get(0);
4825 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4826 String artifactId = null;
4827 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4828 StorageOperationStatus storageStatus;
4829 ArtifactDefinition latestArtifact = null;
4830 List<ArtifactDefinition> artifacts = null;
4831 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4832 if (getArtifactsRes.isRight()) {
4833 storageStatus = getArtifactsRes.right().value();
4834 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4835 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4836 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4838 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4840 if (errorWrapper.isEmpty()) {
4841 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4842 if (artifacts == null || artifacts.isEmpty()) {
4843 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4844 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4847 if (errorWrapper.isEmpty()) {
4848 latestArtifact = artifacts.stream().max((a1, a2) -> {
4849 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4850 if (compareRes == 0) {
4851 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4855 if (latestArtifact == null) {
4856 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4857 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4860 if (errorWrapper.isEmpty()) {
4861 artifactId = latestArtifact.getUniqueId();
4866 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4868 Component component = null;
4869 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4870 if (getUserRes.isRight()) {
4871 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4872 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4874 if (errorWrapper.isEmpty()) {
4875 User modifier = getUserRes.left().value();
4876 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4877 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4878 if (checkoutRes.isRight()) {
4879 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4880 errorWrapper.setInnerElement(checkoutRes.right().value());
4882 component = checkoutRes.left().value();
4888 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4889 if (artifact == null) {
4890 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4891 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4892 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4893 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4896 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4897 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4898 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4902 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4903 Map<String, Object> json = new HashMap<>();
4904 String artifactName = artifact.getArtifactName();
4905 json.put(Constants.ARTIFACT_NAME, artifactName);
4906 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4907 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4908 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4909 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4910 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4911 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4912 return gson.toJson(json);