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.calculateMD5Base64EncodedByByteArray(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, component);
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, null);
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.calculateMD5Base64EncodedByString(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);
1530 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1531 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1532 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1533 return Either.left(insideEither);
1536 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1537 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1538 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1539 // in case of update artifact must be
1540 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1541 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1542 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1544 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1545 log.debug("Artifact {} already exist", artifactId);
1546 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1548 ArtifactDefinition currentArtifactInfo = null;
1549 if (artifactById.isLeft()) {
1550 // get previous value
1551 currentArtifactInfo = artifactById.left().value();
1553 return Either.left(currentArtifactInfo);
1556 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1557 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
1559 String artifactLabel = artifactInfo.getArtifactLabel();
1560 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1561 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1562 log.debug("missing artifact logical name for component {}", componentId);
1563 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1565 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1567 if (operationName != null) {
1568 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1569 log.debug("artifact label cannot be set {}", artifactLabel);
1570 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1572 artifactLabel = operationName;
1575 String displayName = artifactInfo.getArtifactDisplayName();
1576 if (displayName == null || displayName.isEmpty())
1577 displayName = artifactLabel;
1578 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1579 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1580 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1581 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1583 artifactInfo.setArtifactDisplayName(displayName);
1585 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1586 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1587 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1589 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1591 if (artifactLabel.isEmpty()) {
1592 log.debug("missing normalized artifact logical name for component {}", componentId);
1593 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1596 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1597 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1598 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1600 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1601 log.debug("Non unique Artifact label : {}", artifactLabel);
1602 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1605 artifactInfo.setArtifactLabel(artifactLabel);
1607 return Either.left(ActionStatus.OK);
1610 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1611 boolean isUnique = true;
1612 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1613 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1614 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1616 artifacts = artifactToscaOperation.getArtifacts(componentId);
1619 if (artifacts.isLeft()) {
1620 for (String label : artifacts.left().value().keySet()) {
1621 if (label.equals(artifactLabel)) {
1627 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1628 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
1629 if (allInterfacesOfResource.isLeft()) {
1630 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1631 for (Operation operation : interace.getOperationsMap().values()) {
1632 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1643 // ***************************************************************
1645 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1646 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1648 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1649 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1650 Either<ArtifactDefinition, Operation> insideEither = null;
1651 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1652 String instanceId = null;
1653 String instanceName = null;
1654 if (foundInstance != null) {
1655 instanceId = foundInstance.getUniqueId();
1656 instanceName = foundInstance.getName();
1658 if (artifactData == null) {
1659 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1660 log.debug("Failed to create artifact object for ES.");
1661 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1662 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1663 resultOp = Either.right(responseFormat);
1667 // set on graph object id of artifact in ES!
1668 artifactInfo.setEsId(artifactData.getId());
1670 boolean isLeft = false;
1671 String artifactUniqueId = null;
1672 StorageOperationStatus error = null;
1673 if (interfaceType != null && operationName != null) {
1674 // lifecycle artifact
1675 Operation operation = convertToOperation(artifactInfo, operationName);
1677 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1679 isLeft = result.isLeft();
1681 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1682 result.left().value().getImplementation();
1684 insideEither = Either.right(result.left().value());
1685 resultOp = Either.left(insideEither);
1687 error = result.right().value();
1690 // information/deployment/api aritfacts
1691 log.trace("Try to create entry on graph");
1692 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1693 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1695 isLeft = result.isLeft();
1697 artifactUniqueId = result.left().value().getUniqueId();
1698 result.left().value();
1700 insideEither = Either.left(result.left().value());
1701 resultOp = Either.left(insideEither);
1703 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1704 if (error != StorageOperationStatus.OK) {
1709 error = result.right().value();
1713 boolean res = saveArtifacts(artifactData, parentId, false);
1714 // String uniqueId = artifactDefinition.getUniqueId();
1717 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1719 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1720 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1723 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1724 log.debug("Failed to save the artifact.");
1725 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1726 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1728 resultOp = Either.right(responseFormat);
1732 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1733 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1734 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1735 resultOp = Either.right(responseFormat);
1741 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1742 ComponentInstance foundInstance = null;
1743 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1744 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1746 return foundInstance;
1749 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1751 Either<Boolean, ResponseFormat> result = Either.left(true);
1752 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1754 validateArtifactTypeExists(responseWrapper, artifactInfo);
1756 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1758 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1760 if (responseWrapper.isEmpty()) {
1761 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1764 if (responseWrapper.isEmpty()) {
1765 // Common code for all types
1766 // not allowed to change artifactType
1768 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1769 if (validateServiceApiType.isRight()) {
1770 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1774 if (responseWrapper.isEmpty()) {
1775 if (parentType.equals(NodeTypeEnum.Resource)) {
1776 // if (parentComponent instanceof Resource) {
1777 Resource resource = (Resource) parentComponent;
1778 ResourceTypeEnum resourceType = resource.getResourceType();
1779 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1780 if (config == null) {
1781 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1783 List<String> myList = config.getValidForResourceTypes();
1784 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1785 if (either.isRight()) {
1786 responseWrapper.setInnerElement(either.right().value());
1791 if (responseWrapper.isEmpty()) {
1792 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1795 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1796 String artifactName = artifactInfo.getArtifactName();
1797 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1798 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1802 if (responseWrapper.isEmpty()) {
1803 switch (artifactType) {
1807 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1811 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1812 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1815 case DCAE_INVENTORY_TOSCA:
1816 case DCAE_INVENTORY_JSON:
1817 case DCAE_INVENTORY_POLICY:
1818 // Validation is done in handle payload.
1819 case DCAE_INVENTORY_DOC:
1820 case DCAE_INVENTORY_BLUEPRINT:
1821 case DCAE_INVENTORY_EVENT:
1822 // No specific validation
1824 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1830 if (!responseWrapper.isEmpty()) {
1831 result = Either.right(responseWrapper.getInnerElement());
1836 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1837 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1838 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1839 responseWrapper.setInnerElement(responseFormat);
1840 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1844 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1845 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1846 if (parentType.equals(NodeTypeEnum.Resource)) {
1847 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1848 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1849 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1851 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1853 return resourceDeploymentArtifacts;
1856 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1857 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1858 if (artifactType == null) {
1859 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1860 responseWrapper.setInnerElement(responseFormat);
1861 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1865 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1866 ArtifactTypeConfig retConfig = null;
1867 String fileType = artifactType.getType();
1868 if (parentType.equals(NodeTypeEnum.Resource)) {
1869 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1870 } else if (parentType.equals(NodeTypeEnum.Service)) {
1871 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1872 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1873 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1878 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1879 // extract heat parameters
1880 if (artifactInfo.getPayloadData() != null) {
1881 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1882 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1883 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1884 log.info("failed to parse heat parameters ");
1885 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1886 return Either.right(responseFormat);
1887 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1888 artifactInfo.setListHeatParameters(heatParameters.left().value());
1891 return Either.left(true);
1896 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1897 String fileType = artifactType.getType();
1898 List<String> acceptedTypes = null;
1899 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1900 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1901 log.debug("parent type of artifact can be either resource or service");
1902 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1906 if (deploymentAcceptedTypes == null) {
1907 log.debug("parent type of artifact can be either resource or service");
1908 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1911 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1914 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1916 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1917 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1918 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1919 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1922 String artifactName = artifactInfo.getArtifactName();
1923 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1924 // Pavel - File extension validation is case-insensitive - Ella,
1926 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1927 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1928 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1933 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1935 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1936 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1937 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1939 if (errorWrapper.isEmpty()) {
1940 validateValidYaml(errorWrapper, artifactInfo);
1943 if (errorWrapper.isEmpty()) {
1944 // Validate Heat Exist
1945 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1948 // if (errorWrapper.isEmpty() && isCreate) {
1949 // // Validate Only Single HeatEnv Artifact
1950 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1953 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1954 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1957 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1958 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1962 Either<Boolean, ResponseFormat> eitherResponse;
1963 if (errorWrapper.isEmpty()) {
1964 eitherResponse = Either.left(true);
1966 eitherResponse = Either.right(errorWrapper.getInnerElement());
1968 return eitherResponse;
1971 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1972 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1973 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1974 if (fillArtifactPayload.isRight()) {
1975 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1976 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1979 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1983 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1984 Either<Boolean, ResponseFormat> result = Either.left(true);
1985 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1986 if (eitherArtifactData.isLeft()) {
1987 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1988 data = Base64.encodeBase64(data);
1989 payloadWrapper.setInnerElement(data);
1991 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1992 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1993 result = Either.right(responseFormat);
1999 @SuppressWarnings("unchecked")
2000 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2001 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2002 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2003 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2004 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2006 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2007 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2008 if (eitherHeatEnvProperties.isRight()) {
2009 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2010 errorWrapper.setInnerElement(responseFormat);
2011 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2012 } else if (eitherHeatProperties.isRight()) {
2013 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2014 errorWrapper.setInnerElement(responseFormat);
2015 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2017 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2018 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2019 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2020 if (heatEnvPropertiesKeys.size() > 0) {
2021 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2022 errorWrapper.setInnerElement(responseFormat);
2027 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2028 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2029 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2031 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2032 errorWrapper.setInnerElement(responseFormat);
2033 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2037 @SuppressWarnings("restriction")
2038 public boolean isValidXml(byte[] xmlToParse) {
2039 XMLReader parser = new SAXParser();
2041 parser.setFeature("http://apache.org/xml/features/validation/schema", false);
2042 } catch (SAXNotRecognizedException e) {
2043 e.printStackTrace();
2044 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2046 } catch (SAXNotSupportedException e) {
2047 e.printStackTrace();
2048 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2051 boolean isXmlValid = true;
2053 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2054 } catch (IOException | SAXException e) {
2055 log.debug("Xml is invalid : {}", e.getMessage(), e);
2061 public boolean isValidJson(byte[] jsonToParse) {
2062 String parsed = new String(jsonToParse);
2064 gson.fromJson(parsed, Object.class);
2065 } catch (Exception e) {
2066 log.debug("Json is invalid : {}", e.getMessage(), e);
2072 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2073 boolean typeArtifactFound = false;
2074 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2075 // (parentType == NodeTypeEnum.Resource) ?
2076 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2077 // parentComponent).iterator()
2078 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2080 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2082 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2083 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2084 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2086 if (typeArtifactFound) {
2087 String parentName = parentComponent.getName();
2088 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2090 errorWrapper.setInnerElement(responseFormat);
2091 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2096 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2097 boolean artifactNameFound = false;
2098 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2099 // (parentType == NodeTypeEnum.Resource) ?
2100 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2101 // parentComponent).iterator()
2102 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2104 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2106 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2107 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2109 if (artifactNameFound) {
2110 String parentName = parentComponent.getName();
2111 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2113 errorWrapper.setInnerElement(responseFormat);
2114 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2119 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2120 ComponentTypeEnum componentType) {
2121 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2122 if (res.isRight()) {
2123 ResponseFormat responseFormat;
2124 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2125 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2127 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2129 errorWrapper.setInnerElement(responseFormat);
2133 ArtifactDefinition heatArtifact = res.left().value();
2134 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2135 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2136 // while (!heatFound && parentArtifactsItr.hasNext()) {
2137 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2138 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2139 // heatFound = true;
2140 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2141 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2143 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2144 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2148 // if (!heatFound) {
2149 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2150 // errorWrapper.setInnerElement(responseFormat);
2151 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2156 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2157 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2158 // timeout > 0 for HEAT artifacts
2159 Integer timeout = artifactInfo.getTimeout();
2160 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2161 if (timeout == null) {
2162 artifactInfo.setTimeout(defaultTimeout);
2163 // HEAT artifact but timeout is invalid
2164 } else if (timeout < 1) {
2165 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2168 // US649856 - Allow several HEAT files on Resource
2170 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2171 * Either.right(errorWrapper.getInnerElement()); } }
2174 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2175 return Either.left(true);
2178 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2179 String listToString = (typeList != null) ? typeList.toString() : "";
2180 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2181 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2182 String resourceTypeName = resourceType.name();
2183 if (typeList != null && typeList.contains(resourceTypeName)) {
2184 either = Either.left(true);
2189 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2190 if (artifactInfo.getHeatParameters() != null) {
2191 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2192 String parameterType = heatParam.getType();
2193 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2194 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2195 if (heatParameterType == null) {
2196 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2197 return Either.right(responseFormat);
2200 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2201 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2202 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2203 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2204 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2205 return Either.right(responseFormat);
2209 return Either.left(artifactInfo);
2212 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2213 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2214 if (parentComponent.getDeploymentArtifacts() != null) {
2215 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2216 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2217 if (getRI.isRight()) {
2218 return deploymentArtifacts;
2220 ComponentInstance ri = getRI.left().value();
2221 if (ri.getDeploymentArtifacts() != null) {
2222 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2224 } else if (parentComponent.getDeploymentArtifacts() != null) {
2225 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2228 return deploymentArtifacts;
2231 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2232 // on create if null add informational to current
2233 if (artifactInfo.getArtifactGroupType() == null) {
2234 artifactInfo.setArtifactGroupType(type);
2236 if (artifactInfo.getUniqueId() != null) {
2237 log.error("artifact uniqid cannot be set ignoring");
2239 artifactInfo.setUniqueId(null);
2241 if (artifactInfo.getArtifactRef() != null) {
2242 log.error("artifact ref cannot be set ignoring");
2244 artifactInfo.setArtifactRef(null);
2246 if (artifactInfo.getArtifactRepository() != null) {
2247 log.error("artifact repository cannot be set ignoring");
2249 artifactInfo.setArtifactRepository(null);
2251 if (artifactInfo.getUserIdCreator() != null) {
2252 log.error("creator uuid cannot be set ignoring");
2254 artifactInfo.setArtifactCreator(user.getUserId());
2256 if (artifactInfo.getUserIdLastUpdater() != null) {
2257 log.error("userId of last updater cannot be set ignoring");
2259 artifactInfo.setUserIdLastUpdater(user.getUserId());
2261 if (artifactInfo.getCreatorFullName() != null) {
2262 log.error("creator Full name cannot be set ignoring");
2264 String fullName = user.getFirstName() + " " + user.getLastName();
2265 artifactInfo.setUpdaterFullName(fullName);
2267 if (artifactInfo.getUpdaterFullName() != null) {
2268 log.error("updater Full name cannot be set ignoring");
2270 artifactInfo.setUpdaterFullName(fullName);
2272 if (artifactInfo.getCreationDate() != null) {
2273 log.error("Creation Date cannot be set ignoring");
2275 long time = System.currentTimeMillis();
2276 artifactInfo.setCreationDate(time);
2278 if (artifactInfo.getLastUpdateDate() != null) {
2279 log.error("Last Update Date cannot be set ignoring");
2281 artifactInfo.setLastUpdateDate(time);
2283 if (artifactInfo.getEsId() != null) {
2284 log.error("es id cannot be set ignoring");
2286 artifactInfo.setEsId(null);
2291 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2292 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2293 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2294 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2295 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2296 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2299 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2300 String id = artifactId;
2301 if (artifactId == null || artifactId.isEmpty()) {
2302 String uniqueId = null;
2303 if (interfaceName != null && operationName != null) {
2304 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2306 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2308 artifactInfo.setUniqueId(uniqueId);
2309 artifactInfo.setEsId(uniqueId);
2312 artifactInfo.setUniqueId(artifactId);
2313 artifactInfo.setEsId(artifactId);
2318 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2319 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2320 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2321 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2322 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2325 boolean artifactTypeExist = false;
2326 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2327 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2329 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2330 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2333 allArtifactTypes = elementOperation.getAllArtifactTypes();
2335 if (allArtifactTypes.isRight()) {
2336 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2337 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2338 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2341 for (ArtifactType type : allArtifactTypes.left().value()) {
2342 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2343 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2344 artifactTypeExist = true;
2349 if (!artifactTypeExist) {
2350 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2351 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2352 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2355 return Either.left(ActionStatus.OK);
2358 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2360 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2361 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2363 if (parentType.equals(NodeTypeEnum.Service)) {
2364 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2365 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2366 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2368 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2370 if (deploymentArtifacts != null) {
2371 for (String artifactType : deploymentArtifacts.keySet()) {
2372 ArtifactType artifactT = new ArtifactType();
2373 artifactT.setName(artifactType);
2374 artifactTypes.add(artifactT);
2376 return Either.left(artifactTypes);
2378 return Either.right(ActionStatus.GENERAL_ERROR);
2383 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2384 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2385 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2387 return Either.left(true);
2391 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2392 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2393 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2396 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2397 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2398 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2400 artifactInfo.setArtifactName(normalizeFileName);
2402 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2403 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2406 return Either.left(true);
2409 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2410 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2411 log.info("artifact type is missing operation ignored");
2412 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2415 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2416 log.info("artifact type cannot be changed operation ignored");
2417 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2419 return Either.left(true);
2422 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2423 if (artifactInfo.getArtifactGroupType() == null) {
2424 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2427 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2428 log.info("artifact group type cannot be changed. operation failed");
2429 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2431 return Either.left(artifactInfo);
2434 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2436 // on update if null add informational to current
2437 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2438 currentArtifact.setArtifactGroupType(type);
2441 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2442 log.error("artifact uniqid cannot be set ignoring");
2444 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2446 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2447 log.error("artifact ref cannot be set ignoring");
2449 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2451 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2452 log.error("artifact repository cannot be set ignoring");
2454 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2456 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2457 log.error("creator uuid cannot be set ignoring");
2459 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2461 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2462 log.error("artifact creator cannot be set ignoring");
2464 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2466 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2467 log.error("userId of last updater cannot be set ignoring");
2469 artifactInfo.setUserIdLastUpdater(user.getUserId());
2471 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2472 log.error("creator Full name cannot be set ignoring");
2474 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2476 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2477 log.error("updater Full name cannot be set ignoring");
2479 String fullName = user.getFirstName() + " " + user.getLastName();
2480 artifactInfo.setUpdaterFullName(fullName);
2482 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2483 log.error("Creation Date cannot be set ignoring");
2485 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2487 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2488 log.error("Last Update Date cannot be set ignoring");
2490 long time = System.currentTimeMillis();
2491 artifactInfo.setLastUpdateDate(time);
2493 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2494 log.error("es id cannot be set ignoring");
2496 artifactInfo.setEsId(currentArtifact.getUniqueId());
2498 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2499 log.error(" Artifact Display Name cannot be set ignoring");
2501 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2503 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2504 log.debug("serviceApi cannot be set. ignoring.");
2506 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2508 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2509 log.debug("artifact group cannot be set. ignoring.");
2511 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2513 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2515 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2516 log.debug("artifact UUID cannot be set. ignoring.");
2518 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2520 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2521 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2525 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2527 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2528 for (HeatParameterDefinition parameter : heatParameters) {
2529 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2531 if (currentParam != null) {
2533 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2534 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2535 parameter.setName(currentParam.getName());
2537 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2538 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2539 parameter.setDefaultValue(currentParam.getDefaultValue());
2541 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2542 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2543 parameter.setType(currentParam.getType());
2545 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2546 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2547 parameter.setDescription(currentParam.getDescription());
2550 // check and set current value
2551 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2552 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2553 parameter.setCurrentValue(currentParam.getDefaultValue());
2559 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2561 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2562 for (HeatParameterDefinition param : currentParameters) {
2563 currentParamsMap.put(param.getUniqueId(), param);
2565 return currentParamsMap;
2568 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2569 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2570 log.debug("Artifact url cannot be empty.");
2571 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2573 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2575 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2578 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2579 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2582 return Either.left(true);
2585 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2586 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2587 log.debug("Artifact description cannot be empty.");
2588 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2590 String description = artifactInfo.getDescription();
2591 description = ValidationUtils.removeNoneUtf8Chars(description);
2592 description = ValidationUtils.normaliseWhitespace(description);
2593 description = ValidationUtils.stripOctets(description);
2594 description = ValidationUtils.removeHtmlTagsOnly(description);
2595 if (!ValidationUtils.validateIsEnglish(description)) {
2596 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2598 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2599 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2601 artifactInfo.setDescription(description);
2602 return Either.left(true);
2605 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2606 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2607 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2608 String prevArtifactId = null;
2609 String currArtifactId = artifactId;
2611 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2612 Either<ArtifactDefinition, Operation> insideEither = null;
2614 if (artifactData == null) {
2615 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2616 log.debug("Failed to create artifact object for ES.");
2617 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2618 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2619 resultOp = Either.right(responseFormat);
2622 log.trace("Try to update entry on graph");
2623 String artifactUniqueId = null;
2624 ArtifactDefinition artifactDefinition = artifactInfo;
2625 StorageOperationStatus error = null;
2627 boolean isLeft = false;
2628 if (interfaceType != null && operationName != null) {
2629 // lifecycle artifact
2631 * Operation operation = convertToOperation(artifactInfo, operationName);
2633 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2635 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2637 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2640 log.debug("Enty on graph is updated. Update artifact in ES");
2642 // Changing previous and current artifactId for auditing
2643 prevArtifactId = currArtifactId;
2644 currArtifactId = artifactDefinition.getUniqueId();
2646 NodeTypeEnum convertParentType = convertParentType(componentType);
2648 if (decodedPayload == null) {
2649 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2650 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2651 // Either<ESArtifactData, ResourceUploadStatus>
2652 // artifactfromES = daoUploader.getArtifact(artifactId);
2653 if (artifactFromCassandra.isRight()) {
2654 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2655 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2656 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2657 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2658 resultOp = Either.right(responseFormat);
2661 // clone data to new artifact
2662 artifactData.setData(artifactFromCassandra.left().value().getData());
2663 artifactData.setId(artifactFromCassandra.left().value().getId());
2666 if (artifactDefinition.getEsId() == null) {
2667 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2668 artifactData.setId(artifactDefinition.getUniqueId());
2672 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2673 isLeft = result.isLeft();
2675 artifactUniqueId = result.left().value().getUniqueId();
2676 artifactDefinition = result.left().value();
2677 String artifactType = artifactInfo.getArtifactType();
2678 if (NodeTypeEnum.Resource == convertParentType
2679 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2681 if (!artifactUniqueId.equals(artifactId)) {
2682 // need to update the generated id in heat env
2683 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2684 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2685 if (findFirst.isPresent()) {
2686 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2687 artifactEnvInfo.setArtifactChecksum(null);
2688 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2693 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2695 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2696 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2701 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2703 insideEither = Either.left(result.left().value());
2704 resultOp = Either.left(insideEither);
2705 if (error != StorageOperationStatus.OK) {
2710 error = result.right().value();
2714 // create new entry in ES
2716 if (artifactData.getData() != null) {
2717 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2718 artifactData.setId(artifactDefinition.getEsId());
2719 res = saveArtifacts(artifactData, parentId, false);
2725 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2726 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2727 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2728 // resultOp = Either.left(result.left().value());
2731 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2732 log.debug("Failed to save the artifact.");
2733 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2734 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2735 resultOp = Either.right(responseFormat);
2743 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2744 log.trace("Starting payload handling");
2745 byte[] payload = artifactInfo.getPayloadData();
2746 byte[] decodedPayload = null;
2748 if (payload != null && payload.length != 0) {
2749 // the generated artifacts were already decoded by the handler
2750 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2751 if (decodedPayload.length == 0) {
2752 log.debug("Failed to decode the payload.");
2753 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2754 return Either.right(responseFormat);
2757 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
2758 artifactInfo.setArtifactChecksum(checkSum);
2759 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2761 // Specific payload validations of different types
2762 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2763 if (isDeploymentArtifact(artifactInfo)) {
2764 log.trace("Starting deployment artifacts payload validation");
2765 String artifactType = artifactInfo.getArtifactType();
2766 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2767 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2768 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2769 if (isValidPayload.isLeft()) {
2770 isValidPayload = extractHeatParameters(artifactInfo);
2772 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2773 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2774 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
2775 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2777 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2779 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2780 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2781 String artifactFileName = artifactInfo.getArtifactName();
2782 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2783 switch (fileExtension) {
2785 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2788 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2792 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2797 if (isValidPayload.isRight()) {
2798 ResponseFormat responseFormat = isValidPayload.right().value();
2799 return Either.right(responseFormat);
2802 } // null/empty payload is normal if called from metadata update ONLY.
2803 // The validation of whether this is metadata/payload update case is
2804 // currently done separately
2806 if (!isArtifactMetadataUpdate) {
2807 log.debug("Payload is missing.");
2808 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2809 return Either.right(responseFormat);
2812 log.trace("Ended payload handling");
2813 return Either.left(decodedPayload);
2816 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2817 // Basic YAML validation
2818 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2819 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2820 log.debug("Invalid YAML format");
2821 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2822 return Either.right(responseFormat);
2824 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2825 // HEAT specific YAML validation
2826 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2827 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2828 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2829 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2830 return Either.right(responseFormat);
2834 return Either.left(true);
2837 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2838 Either<Boolean, ResponseFormat> res = Either.left(true);
2839 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2840 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2841 log.debug("Invalid YAML format");
2842 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2843 res = Either.right(responseFormat);
2849 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
2850 boolean isXmlValid = isValidXml(payload);
2852 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2853 log.debug("Invalid XML content");
2854 return Either.right(responseFormat);
2856 return Either.left(true);
2859 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2860 boolean isJsonValid = isValidJson(payload);
2862 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2863 log.debug("Invalid JSON content");
2864 return Either.right(responseFormat);
2866 return Either.left(true);
2869 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2870 if (opState == null || opState.isRight()) {
2871 titanDao.rollback();
2877 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2878 boolean inTransaction) {
2879 User user = new User();
2880 user.setUserId(userUserId);
2881 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2882 if (parent.isRight()) {
2883 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2884 return Either.right(responseFormat);
2886 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2887 false, inTransaction);
2888 if (handleDelete.isRight()) {
2889 return Either.right(handleDelete.right().value());
2891 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2892 return Either.left(result.right().value());
2896 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2898 if (artifacts != null && !artifacts.isEmpty()) {
2899 for (ArtifactDefinition artifactDefinition : artifacts) {
2900 String esId = artifactDefinition.getEsId();
2901 if (esId != null && !esId.isEmpty()) {
2902 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2903 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2904 return deleteIfNotOnGraph;
2909 return StorageOperationStatus.OK;
2912 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2913 Operation op = new Operation();
2914 long time = System.currentTimeMillis();
2915 op.setCreationDate(time);
2917 String artifactName = artifactInfo.getArtifactName();
2918 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2920 op.setImplementation(artifactInfo);
2921 op.setLastUpdateDate(time);
2925 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2926 String newArtifactName = operationName + "_" + artifactName;
2927 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2928 return newArtifactName;
2931 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2932 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2933 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2934 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2935 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2937 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2938 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2939 // // last one. need to delete in ES
2940 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2941 // artifactCassandraDao.deleteArtifact(artifactEsId);
2942 // return StorageOperationStatus.OK;
2944 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2948 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2949 // return StorageOperationStatus.OK;
2953 return StorageOperationStatus.OK;
2957 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2959 // General validation
2960 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2961 log.debug("One of the function parameteres is null");
2962 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2965 // Normalizing artifact name
2966 artifactName = ValidationUtils.normalizeFileName(artifactName);
2968 // Resource validation
2969 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2970 if (validateResourceNameAndVersion.isRight()) {
2971 return Either.right(validateResourceNameAndVersion.right().value());
2974 Resource resource = validateResourceNameAndVersion.left().value();
2975 String resourceId = resource.getUniqueId();
2977 // Service validation
2978 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2979 if (validateServiceNameAndVersion.isRight()) {
2980 return Either.right(validateServiceNameAndVersion.right().value());
2983 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2984 if (artifacts == null || artifacts.isEmpty()) {
2985 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2986 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2989 ArtifactDefinition deploymentArtifact = null;
2991 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2992 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2993 log.debug("Found deployment artifact {}", artifactName);
2994 deploymentArtifact = artifactDefinition;
2999 if (deploymentArtifact == null) {
3000 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3001 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3004 // Downloading the artifact
3005 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
3006 if (downloadArtifactEither.isRight()) {
3007 log.debug("Download artifact {} failed", artifactName);
3008 return Either.right(downloadArtifactEither.right().value());
3010 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3011 return Either.left(downloadArtifactEither.left().value().getRight());
3015 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3017 // General validation
3018 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3019 log.debug("One of the function parameteres is null");
3020 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3023 // Normalizing artifact name
3024 artifactName = ValidationUtils.normalizeFileName(artifactName);
3026 // Resource validation
3028 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3029 * Either.right(validateResourceNameAndVersion.right().value()); }
3031 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3034 // Service validation
3035 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3036 if (validateServiceNameAndVersion.isRight()) {
3037 return Either.right(validateServiceNameAndVersion.right().value());
3040 Service service = validateServiceNameAndVersion.left().value();
3042 // ResourceInstance validation
3043 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3044 if (validateResourceInstance.isRight()) {
3045 return Either.right(validateResourceInstance.right().value());
3048 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3050 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3052 final String finalArtifactName = artifactName;
3053 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3055 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3056 ArtifactDefinition deployableArtifact;
3058 if (!hasDeploymentArtifacts) {
3059 log.debug("Deployment artifact with name {} not found", artifactName);
3060 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3063 log.debug("Found deployment artifact {}", artifactName);
3064 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3065 // Downloading the artifact
3066 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service );
3068 if (downloadArtifactEither.isRight()) {
3069 log.debug("Download artifact {} failed", artifactName);
3070 return Either.right(downloadArtifactEither.right().value());
3072 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3073 return Either.left(downloadArtifactEither.left().value().getRight());
3076 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3078 List<ComponentInstance> riList = service.getComponentInstances();
3079 for (ComponentInstance ri : riList) {
3080 if (ri.getNormalizedName().equals(resourceInstanceName))
3081 return Either.left(ri);
3084 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3087 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3089 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3090 if (serviceListBySystemName.isRight()) {
3091 log.debug("Couldn't fetch any service with name {}", serviceName);
3092 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3094 List<Service> serviceList = serviceListBySystemName.left().value();
3095 if (serviceList == null || serviceList.isEmpty()) {
3096 log.debug("Couldn't fetch any service with name {}", serviceName);
3097 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3100 Service foundService = null;
3101 for (Service service : serviceList) {
3102 if (service.getVersion().equals(serviceVersion)) {
3103 log.trace("Found service with version {}", serviceVersion);
3104 foundService = service;
3109 if (foundService == null) {
3110 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3111 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3113 return Either.left(foundService);
3116 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3118 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3119 if (resourceListBySystemName.isRight()) {
3120 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3121 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3123 return Either.left(resourceListBySystemName.left().value());
3126 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3128 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3129 if (serviceName == null || serviceVersion == null || artifactName == null) {
3130 log.debug("One of the function parameteres is null");
3131 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3134 // Normalizing artifact name
3135 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3137 // Service validation
3138 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3139 if (validateServiceNameAndVersion.isRight()) {
3140 return Either.right(validateServiceNameAndVersion.right().value());
3143 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3145 // Looking for deployment or tosca artifacts
3146 Service service = validateServiceNameAndVersion.left().value();
3148 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3149 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3150 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3153 Optional<ArtifactDefinition> foundArtifactOptl = null;
3155 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3156 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3157 // filters artifact by name
3158 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3160 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3161 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3162 // filters TOSCA artifact by name
3163 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3165 if (!foundArtifactOptl.isPresent()) {
3166 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3167 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3169 log.debug("Found deployment artifact {}", normalizedArtifactName);
3170 // Downloading the artifact
3171 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service);
3172 if (downloadArtifactEither.isRight()) {
3173 log.debug("Download artifact {} failed", normalizedArtifactName);
3174 return Either.right(downloadArtifactEither.right().value());
3176 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3177 return Either.left(downloadArtifactEither.left().value().getRight());
3180 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3181 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3182 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3183 if (artifactById.isRight()) {
3184 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3185 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3186 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3188 ArtifactDefinition artifactDefinition = artifactById.left().value();
3189 if (artifactDefinition == null) {
3190 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3191 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3194 return downloadArtifact(artifactDefinition, null);
3197 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3198 boolean found = false;
3199 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3200 if (artifactsS != null) {
3201 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3202 if (entry.getValue().getUniqueId().equals(artifactId)) {
3208 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3209 if (!found && deploymentArtifactsS != null) {
3210 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3211 if (entry.getValue().getUniqueId().equals(artifactId)) {
3217 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3218 if (!found && toscaArtifactsS != null) {
3219 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3220 if (entry.getValue().getUniqueId().equals(artifactId)) {
3226 switch (component.getComponentType()) {
3228 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3229 if (!found && interfaces != null) {
3230 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3231 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3232 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3233 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3242 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3243 if (!found && apiArtifacts != null) {
3244 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3245 if (entry.getValue().getUniqueId().equals(artifactId)) {
3259 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3261 boolean found = false;
3262 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3263 ComponentInstance resourceInstance = null;
3264 for (ComponentInstance ri : resourceInstances) {
3265 if (ri.getUniqueId().equals(resourceInstanceId)) {
3266 resourceInstance = ri;
3270 if (resourceInstance != null) {
3271 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3272 if (artifacts != null) {
3273 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3274 if (entry.getValue().getUniqueId().equals(artifactId)) {
3281 artifacts = resourceInstance.getArtifacts();
3282 if (artifacts != null) {
3283 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3284 if (entry.getValue().getUniqueId().equals(artifactId)) {
3295 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3296 String containerComponentType, boolean inTransaction) {
3298 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3299 componentForAudit.getNodeType();
3301 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3303 if (componentResult.isRight()) {
3304 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3305 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3306 log.debug("Service not found, serviceId {}", componentId);
3307 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3308 return Either.right(responseFormat);
3310 return Either.left(componentResult.left().value());
3313 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3314 ComponentTypeEnum componentType) {
3315 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3316 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3317 if (canWork.isRight()) {
3318 String uniqueId = component.getUniqueId();
3319 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3320 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3321 return Either.right(canWork.right().value());
3324 return Either.left(true);
3327 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3329 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3330 String role = user.getRole();
3331 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3332 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3333 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3334 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3335 return Either.right(responseFormat);
3338 return Either.left(true);
3341 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3342 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3344 if (validateUserExists.isRight()) {
3345 User user = new User();
3346 user.setUserId(userId);
3347 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3348 return Either.right(validateUserExists.right().value());
3350 return Either.left(validateUserExists.left().value());
3353 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3354 AuditingActionEnum auditingAction = null;
3355 switch (operation.getArtifactOperationEnum()) {
3357 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3360 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3363 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3366 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3371 return auditingAction;
3374 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) {
3375 String esArtifactId = artifactDefinition.getEsId();
3376 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3377 if (artifactfromES.isRight()) {
3378 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3379 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3380 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3381 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3382 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName());
3383 handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null);
3385 return Either.right(responseFormat);
3388 ESArtifactData esArtifactData = artifactfromES.left().value();
3389 byte[] data = esArtifactData.getDataAsArray();
3391 log.debug("Artifact data from ES is null");
3392 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3394 String artifactName = artifactDefinition.getArtifactName();
3395 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3396 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3399 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3400 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3401 return artifactData;
3404 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3406 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3408 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3409 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3411 log.info("Failed to save artifact {}.", artifactData.getId());
3417 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3418 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3421 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3422 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3425 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3426 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3427 if (user.isRight()) {
3428 ResponseFormat responseFormat;
3429 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3430 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3431 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3433 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3434 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3436 return Either.right(responseFormat);
3439 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3440 return Either.left(artifactDefinition);
3443 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3444 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3446 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3447 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3448 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3450 artifactInfo.setArtifactDisplayName(artifactName);
3451 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3452 artifactInfo.setArtifactType(artifactType);
3453 artifactInfo.setDescription(artifactDescription);
3454 artifactInfo.setArtifactGroupType(groupType);
3455 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3457 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3459 return artifactInfo;
3462 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3463 String uniqueId = null;
3465 if (resourceId != null) {
3466 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3467 artifactInfo.setUniqueId(uniqueId);
3469 artifactInfo.setUserIdCreator(user.getUserId());
3470 String fullName = user.getFullName();
3471 artifactInfo.setUpdaterFullName(fullName);
3473 long time = System.currentTimeMillis();
3475 artifactInfo.setCreatorFullName(fullName);
3476 artifactInfo.setCreationDate(time);
3478 artifactInfo.setLastUpdateDate(time);
3479 artifactInfo.setUserIdLastUpdater(user.getUserId());
3481 artifactInfo.setMandatory(true);
3484 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3485 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3488 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3489 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3492 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3494 byte[] payload = payloadStr.getBytes();
3496 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3497 return Either.left(artifactData);
3502 * @param artifactDefinition
3505 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3506 boolean shouldLock, String instanceId) {
3507 String payload = generateHeatEnvPayload(artifactDefinition);
3508 String prevUUID = artifactDefinition.getArtifactUUID();
3509 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3510 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3511 if (generateResult.isLeft()) {
3512 ArtifactDefinition updatedArtDef = generateResult.left().value();
3513 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3514 List<ComponentInstance> componentInstances = component.getComponentInstances();
3515 if (componentInstances != null) {
3516 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3517 if (findFirst.isPresent()) {
3518 ComponentInstance relevantInst = findFirst.get();
3519 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3521 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3522 updatedGroupInstances.forEach(gi -> {
3523 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3524 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3526 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3527 if (status.isRight()) {
3528 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3529 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3530 return Either.right(responseFormat);
3538 return generateResult;
3541 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3542 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3543 StringBuilder sb = new StringBuilder();
3544 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3545 sb.append("parameters:\n");
3546 if (heatParameters != null) {
3547 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3549 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3551 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3553 String heatValue = heatParameterDefinition.getCurrentValue();
3554 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3555 heatValue = heatParameterDefinition.getDefaultValue();
3556 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3557 empltyHeatValues.add(heatParameterDefinition);
3561 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3565 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3568 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3570 case COMMA_DELIMITED_LIST:
3572 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3575 String value = heatValue;
3576 boolean starts = value.startsWith("\"");
3577 boolean ends = value.endsWith("\"");
3578 if (!(starts && ends)) {
3579 starts = value.startsWith("'");
3580 ends = value.endsWith("'");
3581 if (!(starts && ends)) {
3582 value = "\"" + value + "\"";
3585 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3592 if (!empltyHeatValues.isEmpty()) {
3593 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3594 empltyHeatValues.forEach(hv -> {
3595 sb.append(" ").append(hv.getName()).append(":");
3596 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3597 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3598 sb.append(" \"\"").append("\n");
3600 sb.append(" ").append("\n");
3605 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3608 String result = sb.toString().replaceAll("\\\\n", "\n");
3615 * @param artifactDefinition
3619 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3620 User modifier, boolean shouldLock, String instanceId) {
3621 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3622 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3626 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3627 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3629 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3630 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3632 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3633 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3634 ESArtifactData artifactData = null;
3636 if (artifactDataRes.isLeft()) {
3637 artifactData = artifactDataRes.left().value();
3639 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3640 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3641 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3643 return Either.right(artifactDataRes.right().value());
3645 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
3647 String esArtifactId = artifactDefinition.getEsId();
3648 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3649 ESArtifactData esArtifactData;
3650 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3651 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3652 if (artifactfromES.isRight()) {
3653 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3654 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3655 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3656 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3657 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3659 esArtifactData = artifactfromES.left().value();
3660 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
3662 oldCheckSum = artifactDefinition.getArtifactChecksum();
3665 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3668 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3669 if (lockComponent.isRight()) {
3670 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3671 return Either.right(lockComponent.right().value());
3675 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3677 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3678 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3679 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3680 if (updateArifactDefinitionStatus.isRight()) {
3681 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3682 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3683 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3684 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3686 return Either.right(responseFormat);
3690 oldCheckSum = artifactDefinition.getArtifactChecksum();
3691 artifactDefinition.setArtifactChecksum(newCheckSum);
3692 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3693 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3694 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3695 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3697 log.trace("Update Payload ", artifactDefinition.getEsId());
3699 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3701 artifactDefinition = updateArifactDefinitionStatus.left().value();
3702 artifactData.setId(artifactDefinition.getUniqueId());
3703 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3705 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3707 log.debug("Artifact Saved In ES {}", artifactData.getId());
3708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3709 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3710 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3713 titanDao.rollback();
3714 log.info("Failed to save artifact {}.", artifactData.getId());
3715 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3716 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3717 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3719 return Either.right(responseFormat);
3722 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3723 log.debug("Failed To update artifact {}", artifactData.getId());
3724 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3725 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3727 return Either.right(responseFormat);
3732 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3737 return Either.left(artifactDefinition);
3740 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3741 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3742 convertParentType(componentType);
3743 String parentId = parent.getUniqueId();
3744 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3745 ArtifactDefinition currArtifact = artifactInfo;
3747 if (origMd5 != null) {
3748 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3749 if (validateMd5.isRight()) {
3750 ResponseFormat responseFormat = validateMd5.right().value();
3751 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3752 return Either.right(responseFormat);
3755 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3756 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3757 if (deploymentValidationResult.isRight()) {
3758 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3759 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3760 return Either.right(responseFormat);
3763 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3764 if (payloadEither.isRight()) {
3765 ResponseFormat responseFormat = payloadEither.right().value();
3766 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3767 return Either.right(responseFormat);
3769 } else { // duplicate
3770 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3771 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3772 return Either.right(responseFormat);
3778 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3779 if (lockComponent.isRight()) {
3780 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3781 return Either.right(lockComponent.right().value());
3784 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3786 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3791 if (resultOp == null || resultOp.isRight()) {
3792 log.debug("all changes rollback");
3793 if (false == inTransaction)
3794 titanDao.rollback();
3796 log.debug("all changes committed");
3797 if (false == inTransaction)
3801 componentType = parent.getComponentType();
3802 NodeTypeEnum nodeType = componentType.getNodeType();
3803 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3804 // graphLockOperation.unlockComponent(parentId, parentType);
3808 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3809 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3811 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3812 Either<ArtifactDefinition, Operation> insideEither = null;
3814 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3816 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3817 if (getRI.isRight()) {
3818 return Either.right(getRI.right().value());
3820 ComponentInstance ri = getRI.left().value();
3821 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3822 if (getArtifactRes.isRight()) {
3823 return Either.right(getArtifactRes.right().value());
3825 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3827 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3829 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3830 return Either.right(responseFormat);
3832 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3833 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3834 new ArrayList<HeatParameterDefinition>();
3837 if (origMd5 != null) {
3838 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3839 updatedHeatEnvParams, currArtifact.getArtifactName());
3840 if (uploadParamsValidationResult.isRight()) {
3841 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3842 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3843 return Either.right(responseFormat);
3845 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3848 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3849 if (validateAndConvertHeatParamers.isRight()) {
3850 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3851 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3852 return Either.right(responseFormat);
3855 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3857 // fill reduced heat env parameters List for updating
3858 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3859 paramName = heatEnvParam.getName();
3860 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3861 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3862 String updatedParamValue = heatEnvParam.getCurrentValue();
3863 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3864 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3865 } else if (updatedParamValue != null) {
3866 currHeatParam.setCurrentValue(updatedParamValue);
3871 //currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3872 currArtifact.setListHeatParameters(currentHeatEnvParams);
3874 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3875 if (updateArifactRes.isRight()) {
3876 log.debug("Failed to update artifact on graph - {}", artifactId);
3877 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3878 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3879 return Either.right(responseFormat);
3881 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3882 if (error != StorageOperationStatus.OK) {
3883 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3884 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3885 return Either.right(responseFormat);
3888 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3889 if (error != StorageOperationStatus.OK) {
3890 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3891 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3892 return Either.right(responseFormat);
3898 insideEither = Either.left(currArtifact);
3899 resultOp = Either.left(insideEither);
3900 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3901 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3905 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3906 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3908 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3909 Either<ArtifactDefinition, Operation> insideEither = null;
3911 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3913 String currentHeatId = currHeatArtifact.getUniqueId();
3915 String esArtifactId = currHeatArtifact.getEsId();
3916 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3917 if (artifactfromES.isRight()) {
3918 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3919 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3920 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3921 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3922 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3925 ESArtifactData esArtifactData = artifactfromES.left().value();
3926 byte[] data = esArtifactData.getDataAsArray();
3929 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3931 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3932 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3933 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3935 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3938 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3940 paramName = heatEnvParam.getName();
3941 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3942 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3944 String updatedParamValue = heatEnvParam.getCurrentValue();
3945 if (updatedParamValue == null)
3946 updatedParamValue = heatEnvParam.getDefaultValue();
3947 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3948 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3949 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3950 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3951 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3952 return Either.right(responseFormat);
3955 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3956 newHeatEnvParams.add(currHeatParam);
3961 if (!newHeatEnvParams.isEmpty()) {
3962 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3963 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3965 if (operationStatus.isRight()) {
3966 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3968 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3969 return Either.right(responseFormat);
3972 updatedHeatArt = operationStatus.left().value();
3974 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3975 esArtifactData.setId(updatedHeatArt.getEsId());
3976 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3979 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3980 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3981 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3982 // resultOp = Either.left(result.left().value());
3985 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3986 log.debug("Failed to save the artifact.");
3987 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3988 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3989 resultOp = Either.right(responseFormat);
3993 insideEither = Either.left(updatedHeatArt);
3996 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3997 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3998 artifactEnvInfo.setArtifactChecksum(null);
3999 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
4001 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
4004 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4005 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
4006 if (result != ActionStatus.OK) {
4007 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4008 return Either.right(responseFormat);
4012 if (updatedHeatEnvParams.isEmpty()) {
4013 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
4015 resultOp = Either.left(insideEither);
4016 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4017 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4022 private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4023 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4024 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4025 return Either.right(responseFormat);
4029 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4030 StorageOperationStatus error = StorageOperationStatus.OK;
4031 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4032 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4033 // List<GroupInstance> associatedGroups = null;
4034 List<String> groupInstancesId = null;
4035 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4036 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4038 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4039 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4040 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4046 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4047 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4049 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4050 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4051 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4052 return Either.right(responseFormat);
4055 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4056 String paramName = uploadedHeatParam.getName();
4057 boolean isExistsInHeat = false;
4058 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4059 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4061 isExistsInHeat = true;
4062 uploadedHeatParam.setType(currHeatParam.getType());
4063 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4064 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4065 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4069 if (!isExistsInHeat) {
4070 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4071 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4072 return Either.right(responseFormat);
4075 return Either.left(updatedHeatEnvParams);
4078 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4079 ResponseFormat responseFormat = null;
4080 List<ComponentInstance> ris = component.getComponentInstances();
4081 for (ComponentInstance ri : ris) {
4082 if (riID.equals(ri.getUniqueId())) {
4083 return Either.left(ri);
4086 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4087 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4088 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4089 return Either.right(responseFormat);
4092 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4093 ResponseFormat responseFormat = null;
4094 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4095 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4096 if (artifactId.equals(artifact.getUniqueId())) {
4097 return Either.left(artifact);
4100 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4101 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4102 return Either.right(responseFormat);
4105 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4106 ArtifactDefinition ret;
4107 if (eitherArtifact.isLeft()) {
4108 ret = eitherArtifact.left().value();
4110 ret = eitherArtifact.right().value().getImplementationArtifact();
4116 * downloads artifact of component by UUIDs
4118 * @param componentType
4119 * @param componentUuid
4120 * @param artifactUUID
4121 * @param auditAdditionalParam
4124 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4125 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4126 Either<byte[], ResponseFormat> result;
4127 byte[] downloadedArtifact = null;
4128 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4129 if (errorWrapper.isEmpty()) {
4130 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4131 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4133 if (errorWrapper.isEmpty()) {
4134 result = Either.left(downloadedArtifact);
4136 result = Either.right(errorWrapper.getInnerElement());
4142 * downloads an artifact of resource instance of component by UUIDs
4144 * @param componentType
4145 * @param componentUuid
4146 * @param resourceName
4147 * @param artifactUUID
4148 * @param auditAdditionalParam
4151 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4152 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4153 Either<byte[], ResponseFormat> result;
4154 byte[] downloadedArtifact = null;
4155 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4156 if (errorWrapper.isEmpty()) {
4157 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4159 if (errorWrapper.isEmpty()) {
4160 result = Either.left(downloadedArtifact);
4162 result = Either.right(errorWrapper.getInnerElement());
4168 * uploads an artifact to a component by UUID
4172 * @param componentType
4173 * @param componentUuid
4174 * @param additionalParams
4178 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4179 ArtifactOperationInfo operation) {
4180 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4181 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4182 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4183 ArtifactDefinition uploadArtifact = null;
4184 Component component = null;
4185 String componentId = null;
4186 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4187 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4188 String userId = request.getHeader(Constants.USER_ID_HEADER);
4190 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4191 if (getComponentRes.isRight()) {
4192 StorageOperationStatus status = getComponentRes.right().value();
4193 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4194 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4196 if (errorWrapper.isEmpty()) {
4197 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4198 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4200 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4201 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4202 if (component != null) {
4203 componentId = component.getUniqueId();
4204 componentName = component.getName();
4207 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4209 if (errorWrapper.isEmpty()) {
4210 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4211 if (actionResult.isRight()) {
4212 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4213 errorWrapper.setInnerElement(actionResult.right().value());
4216 if (errorWrapper.isEmpty()) {
4217 uploadArtifact = actionResult.left().value().left().value();
4218 uploadArtifactResult = Either.left(uploadArtifact);
4220 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4222 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4223 return uploadArtifactResult;
4227 * upload an artifact to a resource instance by UUID
4231 * @param componentType
4232 * @param componentUuid
4233 * @param resourceInstanceName
4234 * @param additionalParams
4238 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4239 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4240 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4241 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4242 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4243 ArtifactDefinition uploadArtifact = null;
4244 Component component = null;
4245 String componentInstanceId;
4247 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4248 String userId = request.getHeader(Constants.USER_ID_HEADER);
4250 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4251 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4252 if (getComponentRes.isRight()) {
4253 StorageOperationStatus status = getComponentRes.right().value();
4254 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4255 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4257 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4258 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4260 if (errorWrapper.isEmpty()) {
4261 if (component == null) {
4262 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4264 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4267 if (errorWrapper.isEmpty()) {
4268 componentInstanceId = componentRiPair.getRight().getUniqueId();
4269 componentId = componentRiPair.getLeft().getUniqueId();
4270 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4272 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4273 if (actionResult.isRight()) {
4274 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4275 errorWrapper.setInnerElement(actionResult.right().value());
4278 if (errorWrapper.isEmpty()) {
4279 uploadArtifact = actionResult.left().value().left().value();
4280 uploadArtifactResult = Either.left(uploadArtifact);
4282 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4284 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4285 return uploadArtifactResult;
4289 * updates an artifact on a component by UUID
4293 * @param componentType
4294 * @param componentUuid
4295 * @param artifactUUID
4296 * @param additionalParams
4301 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4302 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4303 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4304 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4305 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4306 ArtifactDefinition updateArtifact = null;
4307 Component component = null;
4308 String componentId = null;
4309 String artifactId = null;
4310 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4311 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4312 String userId = request.getHeader(Constants.USER_ID_HEADER);
4314 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4315 if (getComponentRes.isRight()) {
4316 StorageOperationStatus status = getComponentRes.right().value();
4317 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4318 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4320 if (errorWrapper.isEmpty()) {
4321 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4322 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4324 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4325 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4326 if (component != null) {
4327 componentId = component.getUniqueId();
4328 componentName = component.getName();
4331 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4333 if (errorWrapper.isEmpty()) {
4334 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4336 if (errorWrapper.isEmpty()) {
4337 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4338 if (actionResult.isRight()) {
4339 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4340 errorWrapper.setInnerElement(actionResult.right().value());
4343 if (errorWrapper.isEmpty()) {
4344 updateArtifact = actionResult.left().value().left().value();
4345 updateArtifactResult = Either.left(updateArtifact);
4348 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4350 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4351 return updateArtifactResult;
4355 * updates an artifact on a resource instance by UUID
4359 * @param componentType
4360 * @param componentUuid
4361 * @param resourceInstanceName
4362 * @param artifactUUID
4363 * @param additionalParams
4368 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4369 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4371 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4372 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4373 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4374 ArtifactDefinition updateArtifact = null;
4375 Component component = null;
4376 String componentInstanceId = null;
4377 String componentId = null;
4378 String artifactId = null;
4379 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4380 String userId = request.getHeader(Constants.USER_ID_HEADER);
4382 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4383 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4384 if (getComponentRes.isRight()) {
4385 StorageOperationStatus status = getComponentRes.right().value();
4386 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4387 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4389 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4390 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4392 if (errorWrapper.isEmpty()) {
4393 if (component == null) {
4394 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4396 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4399 if (errorWrapper.isEmpty()) {
4400 componentInstanceId = componentRiPair.getRight().getUniqueId();
4401 componentId = componentRiPair.getLeft().getUniqueId();
4402 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4404 if (errorWrapper.isEmpty()) {
4405 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4407 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4408 if (actionResult.isRight()) {
4409 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4410 errorWrapper.setInnerElement(actionResult.right().value());
4413 if (errorWrapper.isEmpty()) {
4414 updateArtifact = actionResult.left().value().left().value();
4415 updateArtifactResult = Either.left(updateArtifact);
4417 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4419 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4420 return updateArtifactResult;
4424 * deletes an artifact on a component by UUID
4427 * @param componentType
4428 * @param componentUuid
4429 * @param artifactUUID
4430 * @param additionalParams
4435 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4436 ArtifactOperationInfo operation) {
4438 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4439 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4440 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4441 ArtifactDefinition deleteArtifact = null;
4442 Component component = null;
4443 String componentId = null;
4444 String artifactId = null;
4445 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4446 String userId = request.getHeader(Constants.USER_ID_HEADER);
4448 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4449 if (getComponentRes.isRight()) {
4450 StorageOperationStatus status = getComponentRes.right().value();
4451 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4452 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4454 if (errorWrapper.isEmpty()) {
4455 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4456 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4457 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4458 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4459 if (component != null) {
4460 componentId = component.getUniqueId();
4461 componentName = component.getName();
4464 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4466 if (errorWrapper.isEmpty()) {
4467 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4469 if (errorWrapper.isEmpty()) {
4470 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4471 if (actionResult.isRight()) {
4472 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4473 errorWrapper.setInnerElement(actionResult.right().value());
4476 if (errorWrapper.isEmpty()) {
4477 deleteArtifact = actionResult.left().value().left().value();
4478 deleteArtifactResult = Either.left(deleteArtifact);
4480 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4482 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4483 return deleteArtifactResult;
4487 * deletes an artifact from a resource instance by UUID
4490 * @param componentType
4491 * @param componentUuid
4492 * @param resourceInstanceName
4493 * @param artifactUUID
4494 * @param additionalParams
4499 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4500 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4502 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4503 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4504 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4505 ArtifactDefinition deleteArtifact = null;
4506 Component component = null;
4507 String componentInstanceId = null;
4508 String componentId = null;
4509 String artifactId = null;
4510 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4511 String userId = request.getHeader(Constants.USER_ID_HEADER);
4512 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4513 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4514 if (getComponentRes.isRight()) {
4515 StorageOperationStatus status = getComponentRes.right().value();
4516 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4517 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4519 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4520 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4522 if (errorWrapper.isEmpty()) {
4523 if (component == null) {
4524 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4526 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4529 if (errorWrapper.isEmpty()) {
4530 componentInstanceId = componentRiPair.getRight().getUniqueId();
4531 componentId = componentRiPair.getLeft().getUniqueId();
4532 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4534 if (errorWrapper.isEmpty()) {
4536 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4538 if (actionResult.isRight()) {
4539 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4540 errorWrapper.setInnerElement(actionResult.right().value());
4543 if (errorWrapper.isEmpty()) {
4544 deleteArtifact = actionResult.left().value().left().value();
4545 deleteArtifactResult = Either.left(deleteArtifact);
4547 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4549 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4550 return deleteArtifactResult;
4553 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4554 String artifactId = null;
4555 ArtifactDefinition foundArtifact = null;
4556 if (instance.getDeploymentArtifacts() != null) {
4557 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4559 if (foundArtifact == null && instance.getArtifacts() != null) {
4560 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4562 if (foundArtifact == null) {
4563 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4564 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4566 artifactId = foundArtifact.getUniqueId();
4571 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4572 Map<String, String> existingEnvVersions) {
4573 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4577 @SuppressWarnings("unchecked")
4578 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4579 Map<String, String> existingEnvVersions, boolean overrideId) {
4580 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4581 if (deploymentResourceArtifacts == null) {
4582 log.debug("no deployment artifacts are configured for generated artifacts");
4583 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4585 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4586 if (placeHolderData == null) {
4587 log.debug("no env type {} are configured for generated artifacts", envType);
4588 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4591 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4592 String parentIdParam = parentId;
4594 parentIdParam = null;
4596 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4597 if (createArtifactPlaceHolder.isRight()) {
4598 return Either.right(createArtifactPlaceHolder.right().value());
4600 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4602 // fix for migration only!!!! create heat env placeholder according to heat id.
4603 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4606 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4607 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4608 artifactHeatEnv.setTimeout(0);
4609 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4610 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4611 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4612 // clone heat parameters in case of heat env only not VF heat env
4613 if (envType.equals(HEAT_ENV_NAME)) {
4614 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4616 ArtifactDefinition artifactDefinition;
4617 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4618 if (parentType != NodeTypeEnum.ResourceInstance) {
4619 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4620 if (addHeatEnvArtifact.isRight()) {
4621 log.debug("failed to create heat env artifact on resource instance");
4622 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4624 artifactDefinition = createArtifactPlaceHolder.left().value();
4626 artifactDefinition = artifactHeatEnv;
4627 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4630 if (artifact.getHeatParameters() != null) {
4631 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4632 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4633 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4634 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4635 heatEnvParameters.add(heatEnvParameter);
4637 artifactDefinition.setListHeatParameters(heatEnvParameters);
4641 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4642 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4643 ComponentTypeEnum componentType = component.getComponentType();
4644 if (parentType == NodeTypeEnum.ResourceInstance) {
4645 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4647 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4648 return Either.left(artifactDefinition);
4651 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4652 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4653 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4654 String name = heatArtifact.getArtifactName();
4657 name = heatArtifact.getArtifactLabel();
4658 fileName = name + "." + envExtension;
4660 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4662 heatEnvArtifact.setArtifactName(fileName);
4665 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4666 if (null != existingEnvVersions) {
4667 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4668 if (null != prevVersion) {
4669 heatEnvArtifact.setArtifactVersion(prevVersion);
4675 * Handles Artifacts Request For Inner Component
4677 * @param artifactsToHandle
4680 * @param vfcsNewCreatedArtifacts
4683 * @param inTransaction
4686 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4687 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4689 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4690 ComponentTypeEnum componentType = component.getComponentType();
4691 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4692 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4693 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4697 for (ArtifactDefinition artifact : artifactsToHandle) {
4698 originData = buildJsonStringForCsarVfcArtifact(artifact);
4699 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
4700 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4701 if (actionResult.isRight()) {
4702 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4703 errorWrapper.setInnerElement(actionResult.right().value());
4704 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4705 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4709 uploadedArtifacts.add(actionResult.left().value().left().value());
4711 if (errorWrapper.isEmpty()) {
4712 handleArtifactsResult = Either.left(uploadedArtifacts);
4714 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4716 } catch (Exception e) {
4717 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4718 handleArtifactsResult = Either.right(responseFormat);
4719 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4721 return handleArtifactsResult;
4724 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4725 ComponentInstance componentInstance = null;
4726 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4727 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4728 if (errorWrapper.isEmpty()) {
4729 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4730 if (componentInstance == null) {
4731 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4732 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4735 return componentInstance;
4738 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4740 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4741 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4742 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4743 if (componentInstance == null) {
4744 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4745 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4747 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4749 return relatedComponentComponentInstancePair;
4752 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4753 ComponentInstance componentInstance;
4754 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4755 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4756 if (errorWrapper.isEmpty()) {
4757 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4758 if (componentInstance == null) {
4759 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4760 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4762 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4765 return relatedComponentComponentInstancePair;
4768 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4770 byte[] downloadedArtifact = null;
4771 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4772 List<ArtifactDefinition> artifactsList = null;
4773 ArtifactDefinition deploymentArtifact = null;
4774 if (artifacts != null && !artifacts.isEmpty()) {
4775 artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4777 if (artifactsList == null || artifactsList.isEmpty()) {
4778 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4779 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4781 if (errorWrapper.isEmpty()) {
4782 deploymentArtifact = artifactsList.get(0);
4783 downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
4784 if (downloadArtifactEither.isRight()) {
4785 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4786 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4789 if (errorWrapper.isEmpty()) {
4790 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4791 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4793 return downloadedArtifact;
4796 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4797 Component component = null;
4798 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4799 if (getComponentRes.isRight()) {
4800 StorageOperationStatus status = getComponentRes.right().value();
4801 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4802 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4804 component = getComponentRes.left().value();
4809 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4810 Component component = null;
4811 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4812 if (getComponentRes.isRight()) {
4813 StorageOperationStatus status = getComponentRes.right().value();
4814 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4815 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4817 List<Component> value = getComponentRes.left().value();
4818 if (value.isEmpty()){
4819 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4820 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4821 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4823 component = value.get(0);
4829 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4830 String artifactId = null;
4831 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4832 StorageOperationStatus storageStatus;
4833 ArtifactDefinition latestArtifact = null;
4834 List<ArtifactDefinition> artifacts = null;
4835 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4836 if (getArtifactsRes.isRight()) {
4837 storageStatus = getArtifactsRes.right().value();
4838 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4839 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4840 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4842 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4844 if (errorWrapper.isEmpty()) {
4845 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4846 if (artifacts == null || artifacts.isEmpty()) {
4847 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4848 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4851 if (errorWrapper.isEmpty()) {
4852 latestArtifact = artifacts.stream().max((a1, a2) -> {
4853 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4854 if (compareRes == 0) {
4855 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4859 if (latestArtifact == null) {
4860 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4861 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4864 if (errorWrapper.isEmpty()) {
4865 artifactId = latestArtifact.getUniqueId();
4870 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4872 Component component = null;
4873 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4874 if (getUserRes.isRight()) {
4875 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4876 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4878 if (errorWrapper.isEmpty()) {
4879 User modifier = getUserRes.left().value();
4880 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4881 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4882 if (checkoutRes.isRight()) {
4883 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4884 errorWrapper.setInnerElement(checkoutRes.right().value());
4886 component = checkoutRes.left().value();
4892 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4893 if (artifact == null) {
4894 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4895 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4896 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4897 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4900 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4901 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4902 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4906 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4907 Map<String, Object> json = new HashMap<>();
4908 String artifactName = artifact.getArtifactName();
4909 json.put(Constants.ARTIFACT_NAME, artifactName);
4910 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4911 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4912 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4913 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4914 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4915 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4916 return gson.toJson(json);