2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.function.Predicate;
37 import java.util.function.Supplier;
38 import java.util.stream.Collectors;
40 import javax.servlet.http.HttpServletRequest;
42 import org.apache.commons.codec.binary.Base64;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.apache.commons.collections.MapUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
47 import org.openecomp.sdc.be.components.ArtifactsResolver;
48 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
49 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
52 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
55 import org.openecomp.sdc.be.config.ConfigurationManager;
56 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
59 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
60 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
61 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
62 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.ArtifactType;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentParametersView;
71 import org.openecomp.sdc.be.model.GroupDefinition;
72 import org.openecomp.sdc.be.model.GroupInstance;
73 import org.openecomp.sdc.be.model.HeatParameterDefinition;
74 import org.openecomp.sdc.be.model.InterfaceDefinition;
75 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
76 import org.openecomp.sdc.be.model.LifecycleStateEnum;
77 import org.openecomp.sdc.be.model.Operation;
78 import org.openecomp.sdc.be.model.Resource;
79 import org.openecomp.sdc.be.model.Service;
80 import org.openecomp.sdc.be.model.User;
81 import org.openecomp.sdc.be.model.heat.HeatParameterType;
82 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
83 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
84 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
85 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
86 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
87 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
88 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
89 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
90 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
91 import org.openecomp.sdc.be.resources.data.ESArtifactData;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
94 import org.openecomp.sdc.be.servlets.RepresentationUtils;
95 import org.openecomp.sdc.be.tosca.CsarUtils;
96 import org.openecomp.sdc.be.tosca.ToscaError;
97 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
98 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
99 import org.openecomp.sdc.be.user.IUserBusinessLogic;
100 import org.openecomp.sdc.be.user.Role;
101 import org.openecomp.sdc.be.user.UserBusinessLogic;
102 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
103 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
104 import org.openecomp.sdc.common.api.Constants;
105 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
106 import org.openecomp.sdc.common.datastructure.Wrapper;
107 import org.openecomp.sdc.common.util.GeneralUtility;
108 import org.openecomp.sdc.common.util.ValidationUtils;
109 import org.openecomp.sdc.common.util.YamlToObjectConverter;
110 import org.openecomp.sdc.exception.ResponseFormat;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
113 import org.springframework.beans.factory.annotation.Autowired;
114 import org.xml.sax.*;
115 import org.yaml.snakeyaml.Yaml;
117 import com.google.gson.Gson;
118 import com.google.gson.GsonBuilder;
119 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
121 import fj.data.Either;
123 @org.springframework.stereotype.Component("artifactBusinessLogic")
124 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
125 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
126 private static final String ARTIFACT_DESCRIPTION = "artifact description";
127 private static final String ARTIFACT_LABEL = "artifact label";
128 private static final String ARTIFACT_URL = "artifact url";
129 private static final String ARTIFACT_NAME = "artifact name";
130 private static final String ARTIFACT_PAYLOAD = "artifact payload";
132 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
133 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
134 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
136 public static final String HEAT_ENV_NAME = "heatEnv";
137 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
138 public static final String HEAT_ENV_SUFFIX = "env";
139 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
141 // private static Integer defaultHeatTimeout;
142 // private static final Integer NON_HEAT_TIMEOUT = 0;
143 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
144 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
146 @javax.annotation.Resource
147 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
148 @javax.annotation.Resource
149 private IUserAdminOperation userOperaton;
151 @javax.annotation.Resource
152 private IElementOperation elementOperation;
154 @javax.annotation.Resource
155 private ResourceBusinessLogic resourceBusinessLogic;
157 @javax.annotation.Resource
158 private ServiceBusinessLogic serviceBusinessLogic;
160 @javax.annotation.Resource
161 private UserBusinessLogic userAdminManager;
163 @javax.annotation.Resource
164 private IHeatParametersOperation heatParametersOperation;
167 private ArtifactCassandraDao artifactCassandraDao;
170 private ToscaExportHandler toscaExportUtils;
173 private CsarUtils csarUtils;
176 private LifecycleBusinessLogic lifecycleBusinessLogic;
179 private IUserBusinessLogic userBusinessLogic;
181 NodeTemplateOperation nodeTemplateOperation;
184 private ArtifactsResolver artifactsResolver;
186 public ArtifactsBusinessLogic() {
187 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
188 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
189 // defaultHeatTimeout = 60;
193 public static enum ArtifactOperationEnum {
194 Create(), Update(), Delete(), Download();
197 public class ArtifactOperationInfo {
199 private ArtifactOperationEnum artifactOperationEnum;
200 private boolean isExternalApi;
201 private boolean ignoreLifecycleState;
203 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
204 this.artifactOperationEnum = artifactOperationEnum;
205 this.isExternalApi = isExternalApi;
206 this.ignoreLifecycleState = ignoreLifecycleState;
209 public boolean isExternalApi() {
210 return isExternalApi;
213 public boolean ignoreLifecycleState() {
214 return ignoreLifecycleState;
217 public ArtifactOperationEnum getArtifactOperationEnum() {
218 return artifactOperationEnum;
224 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
225 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
226 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
229 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
230 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
232 // step 1 - detect auditing type
233 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
234 // step 2 - check header
235 if (userId == null) {
236 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
237 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
238 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
239 return Either.right(responseFormat);
241 // step 3 - check user existence
242 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
243 if (userResult.isRight()) {
244 return Either.right(userResult.right().value());
247 // step 4 - check user's role
248 User user = userResult.left().value();
249 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
250 if (validateUserRole.isRight()) {
251 return Either.right(validateUserRole.right().value());
255 // 5. check service/resource existence
256 // 6. check service/resource check out
257 // 7. user is owner of checkout state
258 org.openecomp.sdc.be.model.Component component = null;
259 // ComponentInstance resourceInstance = null;
260 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
261 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
262 if (validateComponent.isRight()) {
263 return Either.right(validateComponent.right().value());
265 component = validateComponent.left().value();
266 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
267 if (validateWorkOnResource.isRight()) {
268 return Either.right(validateWorkOnResource.right().value());
271 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
272 shouldLock, inTransaction, true);
278 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
279 * For regular usage use <br>
280 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
284 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
285 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
286 Component parent = component;
287 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
289 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
290 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
292 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
293 if (errorWrapper.isEmpty()) {
295 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
297 result = Either.right(errorWrapper.getInnerElement());
302 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
303 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
304 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
305 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
306 if (validateArtifact.isRight()) {
307 ResponseFormat responseFormat = validateArtifact.right().value();
308 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
309 errorWrapper.setInnerElement(validateArtifact.right().value());
311 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
312 artifactInfo = validateArtifact.left().value();
313 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
320 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
321 Wrapper<ResponseFormat> errorWrapper) {
322 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
324 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
325 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
326 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
327 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
329 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
330 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
331 if (eitherGenerated.isRight()) {
332 errorWrapper.setInnerElement(eitherGenerated.right().value());
338 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
339 boolean needGenerate;
340 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
341 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
345 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
346 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
349 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
350 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
352 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
353 if (generated.isRight()) {
356 byte[] decodedPayload = artifactDefinition.getPayloadData();
357 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
358 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
359 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
360 shouldLock, inTransaction);
364 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
365 log.debug("tosca artifact generation");
366 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
367 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
369 if (generated.isRight()) {
370 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
372 return Either.right(generated.right().value());
374 byte[] value = generated.left().value();
375 artifactInfo.setPayload(value);
378 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
379 if (exportComponent.isRight()) {
380 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
381 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
382 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
383 return Either.right(responseFormat);
385 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
386 String payload = exportComponent.left().value().getMainYaml();
387 artifactInfo.setPayloadData(payload);
389 return Either.left(Either.left(artifactInfo));
392 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
393 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
394 if (interfaceName != null && operationName != null) {
395 interfaceName = interfaceName.toLowerCase();
396 operationName = operationName.toLowerCase();
398 switch (operation.getArtifactOperationEnum()) {
400 if (artifactGenerationRequired(parent, artifactInfo)) {
401 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
403 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
405 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
407 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
408 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
409 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
410 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
411 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
412 if (needUpdateGroup && result.isLeft()) {
413 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
414 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
415 if (error != ActionStatus.OK) {
416 result = Either.right(componentsUtils.getResponseFormat(error));
420 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
421 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
424 if (result == null) {
425 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
426 if (needUpdateGroup && result.isLeft()) {
427 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
429 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
430 if (error != ActionStatus.OK) {
431 result = Either.right(componentsUtils.getResponseFormat(error));
437 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
442 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
443 List<GroupDefinition> groups = parent.getGroups();
444 if (groups != null && !groups.isEmpty()) {
445 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
446 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
447 groupToUpdate.forEach(g -> {
448 g.getArtifacts().remove(artifactInfo.getUniqueId());
449 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
450 g.getArtifacts().add(artAfterUpdate.getUniqueId());
451 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
453 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
454 if (status.isRight()) {
455 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
456 return componentsUtils.convertFromStorageResponse(status.right().value());
460 return ActionStatus.OK;
463 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
464 List<GroupDefinition> groups = parent.getGroups();
465 if (groups != null && !groups.isEmpty()) {
466 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
467 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
468 groupToUpdate.forEach(g -> {
469 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
470 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
471 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
472 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
473 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
474 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
476 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
477 if (status.isRight()) {
478 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
479 return componentsUtils.convertFromStorageResponse(status.right().value());
483 return ActionStatus.OK;
486 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
487 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
488 List<GroupInstance> groupInstances = null;
489 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
490 if (componentInstOp.isPresent()) {
491 groupInstances = componentInstOp.get().getGroupInstances();
493 if (CollectionUtils.isNotEmpty(groupInstances)) {
494 boolean isUpdated = false;
495 for (GroupInstance groupInstance : groupInstances) {
497 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
498 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
499 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
502 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
503 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
504 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
508 updatedGroupInstances.add(groupInstance);
512 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
513 if (status.isRight()) {
514 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
515 return componentsUtils.convertFromStorageResponse(status.right().value());
517 return ActionStatus.OK;
520 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
521 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
522 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
523 result = generateToscaArtifact(parent, artifactInfo, false, false);
525 String heatArtifactId = artifactInfo.getGeneratedFromId();
526 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
527 if (heatRes.isRight()) {
528 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
529 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
530 return Either.right(responseFormat);
532 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
533 artifactInfo.setPayloadData(generatedPayload);
534 result = Either.left(Either.left(artifactInfo));
539 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
540 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
541 convertParentType(componentType);
542 String parentId = parent.getUniqueId();
543 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
544 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
546 if (origMd5 != null) {
547 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
548 if (validateMd5.isRight()) {
549 ResponseFormat responseFormat = validateMd5.right().value();
550 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
551 return Either.right(responseFormat);
554 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
556 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
557 if (payloadEither.isRight()) {
558 ResponseFormat responseFormat = payloadEither.right().value();
559 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
560 return Either.right(responseFormat);
562 } else { // duplicate
563 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
564 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
565 return Either.right(responseFormat);
571 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
572 if (lockComponent.isRight()) {
573 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
574 return Either.right(lockComponent.right().value());
577 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
579 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
584 if (resultOp == null || resultOp.isRight()) {
585 log.debug("all changes rollback");
586 if (false == inTransaction)
589 log.debug("all changes committed");
590 if (false == inTransaction)
594 componentType = parent.getComponentType();
595 NodeTypeEnum nodeType = componentType.getNodeType();
596 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
597 // graphLockOperation.unlockComponent(parentId, parentType);
606 * @param componentType
611 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
612 if (artifactGenerationRequired(component, csarArtifact)) {
613 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
615 if (generated.isRight()) {
616 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
618 return Either.right(generated.right().value());
620 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
622 return downloadArtifact(csarArtifact);
625 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
626 // perform all validation in common flow
627 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
628 null, parentId, containerComponentType);
629 if (result.isRight()) {
630 return Either.right(result.right().value());
632 ArtifactDefinition artifactDefinition;
633 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
634 if (insideValue.isLeft()) {
635 artifactDefinition = insideValue.left().value();
637 artifactDefinition = insideValue.right().value().getImplementationArtifact();
639 // for tosca artifacts and heat env on VF level generated on download without saving
640 if (artifactDefinition.getPayloadData() != null) {
641 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
643 return downloadArtifact(artifactDefinition);
646 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
648 // detect auditing type
649 Map<String, ArtifactDefinition> resMap = null;
650 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
655 if (userId == null) {
656 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
657 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
659 resultOp = Either.right(responseFormat);
663 // check user existence
667 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
668 if (userResult.isRight()) {
670 resultOp = Either.right(userResult.right().value());
674 userResult.left().value();
677 // 5. check service/resource existence
678 // 6. check service/resource check out
679 // 7. user is owner of checkout state
680 org.openecomp.sdc.be.model.Component component = null;
681 // ComponentInstance resourceInstance = null;
682 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
683 ComponentParametersView componentFilter = new ComponentParametersView();
684 componentFilter.disableAll();
685 componentFilter.setIgnoreArtifacts(false);
686 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
687 componentFilter.setIgnoreComponentInstances(false);
689 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
691 if (validateComponent.isRight()) {
692 resultOp = Either.right(validateComponent.right().value());
695 component = validateComponent.left().value();
696 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
697 if (lockComponent.isRight()) {
699 resultOp = Either.right(lockComponent.right().value());
704 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
706 if (groupType == null) {
707 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
708 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
710 resultOp = Either.right(responseFormat);
714 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
715 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
716 if (list != null && !list.isEmpty()) {
717 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
719 resMap = new HashMap<>();
721 resultOp = Either.left(resMap);
725 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
726 if (artifactsMapStatus.isRight()) {
727 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
728 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
729 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
730 resultOp = Either.right(responseFormat);
732 resMap = new HashMap<>();
733 resultOp = Either.left(resMap);
736 resMap = artifactsMapStatus.left().value();
737 resultOp = Either.left(resMap);
743 if (resultOp == null || resultOp.isRight()) {
744 log.debug("all changes rollback");
747 log.debug("all changes committed");
752 componentType = component.getComponentType();
753 NodeTypeEnum nodeType = componentType.getNodeType();
754 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
755 // graphLockOperation.unlockComponent(parentId, parentType);
760 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
761 boolean inTransaction) {
763 // check artifact existence
764 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
765 if (artifactResult.isRight()) {
766 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
767 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
768 log.debug("addArtifact - artifact {} not found", artifactId);
769 return Either.right(responseFormat);
772 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
773 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
774 return Either.right(responseFormat);
778 // check artifact belong to component
779 boolean found = false;
780 switch (componentType) {
783 found = checkArtifactInComponent(component, artifactId);
785 case RESOURCE_INSTANCE:
786 found = checkArtifactInResourceInstance(component, componentId, artifactId);
792 // String component =
793 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
795 String componentName = componentType.name().toLowerCase();
796 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
797 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
798 return Either.right(responseFormat);
800 return Either.left(artifactResult.left().value());
803 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
804 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
806 String artifactId = null;
809 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
810 if (payloadEither.isRight()) {
811 return Either.right(payloadEither.right().value());
813 byte[] decodedPayload = payloadEither.left().value();
814 convertParentType(componentType);
817 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
818 if (lockComponent.isRight()) {
819 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
820 return Either.right(lockComponent.right().value());
823 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
826 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
830 unlockComponent(resultOp, parent, inTransaction);
837 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
838 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
840 convertParentType(componentType);
844 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
846 if (lockComponent.isRight()) {
847 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
848 return Either.right(lockComponent.right().value());
852 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
854 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
859 unlockComponent(resultOp, parent, inTransaction);
864 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
865 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
867 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
869 if (payloadEither.isRight()) {
870 return Either.right(payloadEither.right().value());
872 byte[] decodedPayload = payloadEither.left().value();
874 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
877 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
878 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
880 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
881 if (validateMd5.isRight()) {
882 ResponseFormat responseFormat = validateMd5.right().value();
883 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
884 return Either.right(responseFormat);
888 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
889 if (validateResult.isRight()) {
890 ResponseFormat responseFormat = validateResult.right().value();
891 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
892 return Either.right(validateResult.right().value());
895 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
896 if (payloadEither.isRight()) {
897 ResponseFormat responseFormat = payloadEither.right().value();
898 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
899 log.debug("Error during handle payload");
900 return Either.right(responseFormat);
903 // validate heat parameters. this part must be after the parameters are
904 // extracted in "handlePayload"
905 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
906 if (validateAndConvertHeatParamers.isRight()) {
907 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
908 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
909 log.debug("Error during handle payload");
910 return Either.right(responseFormat);
912 return payloadEither;
915 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
916 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
918 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
922 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
926 user.setUserId("UNKNOWN");
928 switch (componentTypeEnum) {
931 Resource resource = (Resource) component;
932 if (resource == null) {
933 // In that case, component ID should be instead of name
934 resource = new Resource();
935 resource.setName(componentId);
937 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
941 Service service = (Service) component;
942 if (service == null) {
943 // In that case, component ID should be instead of name
944 service = new Service();
945 service.setName(componentId);
947 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
950 case RESOURCE_INSTANCE:
951 if (resourceInstanceName == null) {
952 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
954 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
955 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
963 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
964 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
965 String resourceInstanceName = null;
966 if (resourceInstance != null) {
967 resourceInstanceName = resourceInstance.getName();
969 return resourceInstanceName;
972 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
973 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
974 // Putting together artifact info
975 String artifactData = buildAuditingArtifactData(artifactDefinition);
976 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
977 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
978 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
979 return auditingFields;
984 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
985 StringBuilder sb = new StringBuilder();
986 if (artifactDefinition != null) {
987 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
988 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
991 if (artifactDefinition.getArtifactVersion() != null) {
993 sb.append(artifactDefinition.getArtifactVersion());
998 if (artifactDefinition.getArtifactUUID() != null) {
999 sb.append(artifactDefinition.getArtifactUUID());
1004 return sb.toString();
1007 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1009 if (origMd5 != null) {
1010 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
1012 if (false == encodeBase64Str.equals(origMd5)) {
1013 log.debug("The calculated md5 is different then the received one");
1014 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1017 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1018 log.debug("Missing md5 header during artifact create");
1019 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1022 if (payload != null && payload.length != 0) {
1023 log.debug("Cannot have payload while md5 header is missing");
1024 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1027 return Either.left(true);
1030 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1031 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1033 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1034 if (artifactById.isRight()) {
1035 return Either.right(artifactById.right().value());
1037 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1039 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1040 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1041 if (validateInformationalArtifactRes.isRight()) {
1042 return Either.right(validateInformationalArtifactRes.right().value());
1044 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1045 if (validateAndSetArtifactname.isRight()) {
1046 return Either.right(validateAndSetArtifactname.right().value());
1048 if (operationName != null && interfaceName != null) {
1049 operationName = operationName.toLowerCase();
1050 interfaceName = interfaceName.toLowerCase();
1052 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
1053 if (logicalNameStatus.isRight()) {
1054 return Either.right(logicalNameStatus.right().value());
1056 // This is a patch to block possibility of updating service api fields
1057 // through other artifacts flow
1059 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1060 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1062 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1065 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1066 if (currentArtifactInfo != null) {
1067 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1070 // artifactGroupType is not allowed to be updated
1071 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1072 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1073 if (validateGroupType.isRight()) {
1074 return Either.right(validateGroupType.right().value());
1078 NodeTypeEnum parentType = convertParentType(componentType);
1081 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
1083 if (isDeploymentArtifact(artifactInfo)) {
1084 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1085 if (deploymentValidationResult.isRight()) {
1086 return Either.right(deploymentValidationResult.right().value());
1089 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1092 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1093 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1097 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1098 if (descriptionResult.isRight()) {
1099 return Either.right(descriptionResult.right().value());
1102 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1103 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1104 if (validateServiceApiType.isRight()) {
1105 return Either.right(validateServiceApiType.right().value());
1107 // Change of type is not allowed and should be ignored
1109 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1111 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1112 if (validateUrl.isRight()) {
1113 return Either.right(validateUrl.right().value());
1116 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1117 if (validateUpdate.isRight()) {
1118 log.debug("serviceApi first update cnnot be without payload.");
1119 return Either.right(validateUpdate.right().value());
1122 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1123 if (validateArtifactType.isRight()) {
1124 return Either.right(validateArtifactType.right().value());
1126 if (artifactInfo.getApiUrl() != null) {
1127 artifactInfo.setApiUrl(null);
1128 log.error("Artifact URL cannot be set through this API - ignoring");
1131 if (artifactInfo.getServiceApi() != null) {
1132 if (artifactInfo.getServiceApi()) {
1133 artifactInfo.setServiceApi(false);
1134 log.error("Artifact service API flag cannot be changed - ignoring");
1139 return Either.left(artifactInfo);
1142 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1143 if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
1144 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1145 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1146 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1150 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1152 Either<ArtifactDefinition, ResponseFormat> result = null;
1153 ArtifactDefinition foundArtifact = null;
1154 if (StringUtils.isNotEmpty(artifactId)) {
1155 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1157 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1158 log.debug("Artifact {} already exist", artifactId);
1159 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1161 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1162 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1163 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1165 if (result == null) {
1166 result = Either.left(foundArtifact);
1171 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1172 ArtifactDefinition foundArtifact;
1173 if (parentComponent.getUniqueId().equals(parentId)) {
1174 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1176 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1177 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1179 return foundArtifact;
1182 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1183 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1184 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1185 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1186 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1187 if (artifactType == null) {
1188 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1189 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1190 String artifactTypeName = artifactType.getType();
1191 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1192 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1193 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1194 if (!validArtifactTypes.contains(artifactTypeName)) {
1195 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1197 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1198 if (!validResourceType.contains(parentResourceType.name())) {
1199 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1203 return validationResult;
1206 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1207 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1208 return NodeTypeEnum.Resource;
1209 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1210 return NodeTypeEnum.ResourceInstance;
1212 return NodeTypeEnum.Service;
1216 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1217 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1219 NodeTypeEnum parentType = convertParentType(componentType);
1220 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1221 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1222 ArtifactDefinition foundArtifact = null;
1223 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1224 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1225 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1226 boolean isDuplicated = false;
1228 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1231 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1232 if (lockComponent.isRight()) {
1233 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1234 resultOp = Either.right(lockComponent.right().value());
1237 if (resultOp == null) {
1238 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1239 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1240 if (getContainerRes.isRight()) {
1241 log.debug("Failed to fetch the container component {}. ", parentId);
1242 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1243 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1244 resultOp = Either.right(responseFormat);
1247 if (resultOp == null) {
1248 fetchedContainerComponent = getContainerRes.left().value();
1249 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1250 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1251 if (getArtifactRes.isRight()) {
1252 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1253 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1254 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1255 resultOp = Either.right(responseFormat);
1257 foundArtifact = getArtifactRes.left().value().getLeft();
1258 esId = foundArtifact.getEsId();
1261 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1262 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1263 if (needCloneRes.isRight()) {
1264 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1265 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1266 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1267 resultOp = Either.right(responseFormat);
1270 if (resultOp == null) {
1271 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1272 if (updatedArtifactRes.isRight()) {
1273 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1274 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1275 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1276 resultOp = Either.right(responseFormat);
1278 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1282 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1283 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1284 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1285 if (cassandraStatus != CassandraOperationStatus.OK) {
1286 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1287 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1288 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1289 resultOp = Either.right(responseFormat);
1292 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1294 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1295 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1296 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1297 if (status.isRight()) {
1298 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1299 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1300 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1301 resultOp = Either.right(responseFormat);
1305 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1306 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1307 if (status != StorageOperationStatus.OK) {
1308 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1309 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1310 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1311 resultOp = Either.right(responseFormat);
1314 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1315 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1316 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1317 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1318 if (status.isRight()) {
1319 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1320 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1321 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1322 resultOp = Either.right(responseFormat);
1326 if (resultOp == null) {
1327 resultOp = Either.left(Either.left(foundArtifact));
1328 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1333 unlockComponent(resultOp, parent, inTransaction);
1338 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1339 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1340 boolean isUpdated = false;
1341 if (groups != null) {
1342 for (GroupDefinition group : groups) {
1344 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1345 group.getArtifacts().remove(artifactId);
1348 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1349 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1353 updatedGroups.add(group);
1357 return updatedGroups;
1360 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1361 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1362 if (CollectionUtils.isNotEmpty(groupInstances)) {
1363 boolean isUpdated = false;
1364 for (GroupInstance groupInstance : groupInstances) {
1366 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1367 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1370 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1371 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1375 updatedGroupInstances.add(groupInstance);
1379 return updatedGroupInstances;
1382 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1384 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1385 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1386 String componentId = component.getUniqueId();
1387 String instanceId = componentId.equals(parentId) ? null : parentId;
1389 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1390 resetMandatoryArtifactFields(foundArtifact);
1391 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true);
1392 } else if (cloneIsNeeded) {
1393 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1394 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1396 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1397 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1402 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1404 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1405 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1406 ComponentInstance foundInstance = null;
1407 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1408 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1409 if (!componentInstanceOpt.isPresent()) {
1410 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1412 foundInstance = componentInstanceOpt.get();
1413 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1416 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1418 if (result == null) {
1419 if (artifacts.containsKey(artifactId)) {
1420 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1422 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1428 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1429 Map<String, ArtifactDefinition> currArtifacts;
1430 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1431 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1432 if (MapUtils.isNotEmpty(currArtifacts)) {
1433 artifacts.putAll(currArtifacts);
1436 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1437 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1438 if (MapUtils.isNotEmpty(currArtifacts)) {
1439 artifacts.putAll(currArtifacts);
1442 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1443 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1444 if (MapUtils.isNotEmpty(currArtifacts)) {
1445 artifacts.putAll(currArtifacts);
1450 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1451 Map<String, ArtifactDefinition> currArtifacts;
1452 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1453 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1454 if (MapUtils.isNotEmpty(currArtifacts)) {
1455 artifacts.putAll(currArtifacts);
1458 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1459 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1460 if (MapUtils.isNotEmpty(currArtifacts)) {
1461 artifacts.putAll(currArtifacts);
1466 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1467 StorageOperationStatus result;
1468 switch (cassandraStatus) {
1470 result = StorageOperationStatus.OK;
1473 result = StorageOperationStatus.NOT_FOUND;
1475 case CLUSTER_NOT_CONNECTED:
1476 case KEYSPACE_NOT_CONNECTED:
1477 result = StorageOperationStatus.CONNECTION_FAILURE;
1480 result = StorageOperationStatus.GENERAL_ERROR;
1486 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1487 if (fetchedArtifact != null) {
1488 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1489 fetchedArtifact.setEsId(null);
1490 fetchedArtifact.setArtifactName(null);
1491 fetchedArtifact.setDescription(null);
1492 fetchedArtifact.setApiUrl(null);
1493 fetchedArtifact.setArtifactChecksum(null);
1494 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1495 fetchedArtifact.setArtifactUUID(null);
1496 long time = System.currentTimeMillis();
1497 fetchedArtifact.setPayloadUpdateDate(time);
1498 fetchedArtifact.setHeatParameters(null);
1499 fetchedArtifact.setHeatParamsUpdateDate(null);
1503 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1504 StorageOperationStatus error = StorageOperationStatus.OK;
1505 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1506 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1507 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1512 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1513 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1514 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1515 if (artifactById.isRight()) {
1516 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1517 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1518 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1519 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1520 return Either.right(responseFormat);
1522 ArtifactDefinition artifactDefinition = artifactById.left().value();
1523 if (artifactDefinition == null) {
1524 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1525 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1526 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1527 return Either.right(responseFormat);
1529 if(artifactDefinition.getPayloadData() == null) {
1530 log.debug("Empty payload data returned from DB by artifat id {}", artifactId);
1531 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
1532 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1533 return Either.right(responseFormat);
1536 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1537 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1538 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1539 return Either.left(insideEither);
1542 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1543 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1544 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1545 // in case of update artifact must be
1546 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1547 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1548 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1550 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1551 log.debug("Artifact {} already exist", artifactId);
1552 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1554 ArtifactDefinition currentArtifactInfo = null;
1555 if (artifactById.isLeft()) {
1556 // get previous value
1557 currentArtifactInfo = artifactById.left().value();
1559 return Either.left(currentArtifactInfo);
1562 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1563 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
1565 String artifactLabel = artifactInfo.getArtifactLabel();
1566 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1567 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1568 log.debug("missing artifact logical name for component {}", componentId);
1569 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1571 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1573 if (operationName != null) {
1574 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1575 log.debug("artifact label cannot be set {}", artifactLabel);
1576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1578 artifactLabel = operationName;
1581 String displayName = artifactInfo.getArtifactDisplayName();
1582 if (displayName == null || displayName.isEmpty())
1583 displayName = artifactLabel;
1584 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1585 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1586 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1587 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1589 artifactInfo.setArtifactDisplayName(displayName);
1591 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1592 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1593 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1595 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1597 if (artifactLabel.isEmpty()) {
1598 log.debug("missing normalized artifact logical name for component {}", componentId);
1599 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1602 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1603 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1604 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1606 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1607 log.debug("Non unique Artifact label : {}", artifactLabel);
1608 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1611 artifactInfo.setArtifactLabel(artifactLabel);
1613 return Either.left(ActionStatus.OK);
1616 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1617 boolean isUnique = true;
1618 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1619 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1620 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1622 artifacts = artifactToscaOperation.getArtifacts(componentId);
1625 if (artifacts.isLeft()) {
1626 for (String label : artifacts.left().value().keySet()) {
1627 if (label.equals(artifactLabel)) {
1633 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1634 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
1635 if (allInterfacesOfResource.isLeft()) {
1636 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1637 for (Operation operation : interace.getOperationsMap().values()) {
1638 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1649 // ***************************************************************
1651 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1652 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1654 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1655 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1656 Either<ArtifactDefinition, Operation> insideEither = null;
1657 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1658 String instanceId = null;
1659 String instanceName = null;
1660 if (foundInstance != null) {
1661 instanceId = foundInstance.getUniqueId();
1662 instanceName = foundInstance.getName();
1664 if (artifactData == null) {
1665 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1666 log.debug("Failed to create artifact object for ES.");
1667 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1668 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1669 resultOp = Either.right(responseFormat);
1673 // set on graph object id of artifact in ES!
1674 artifactInfo.setEsId(artifactData.getId());
1676 boolean isLeft = false;
1677 String artifactUniqueId = null;
1678 StorageOperationStatus error = null;
1679 if (interfaceType != null && operationName != null) {
1680 // lifecycle artifact
1681 Operation operation = convertToOperation(artifactInfo, operationName);
1683 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1685 isLeft = result.isLeft();
1687 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1688 result.left().value().getImplementation();
1690 insideEither = Either.right(result.left().value());
1691 resultOp = Either.left(insideEither);
1693 error = result.right().value();
1696 // information/deployment/api aritfacts
1697 log.trace("Try to create entry on graph");
1698 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1699 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1701 isLeft = result.isLeft();
1703 artifactUniqueId = result.left().value().getUniqueId();
1704 result.left().value();
1706 insideEither = Either.left(result.left().value());
1707 resultOp = Either.left(insideEither);
1709 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1710 if (error != StorageOperationStatus.OK) {
1715 error = result.right().value();
1719 boolean res = saveArtifacts(artifactData, parentId, false);
1720 // String uniqueId = artifactDefinition.getUniqueId();
1723 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1725 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1726 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1729 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1730 log.debug("Failed to save the artifact.");
1731 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1732 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1734 resultOp = Either.right(responseFormat);
1738 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1739 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1740 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1741 resultOp = Either.right(responseFormat);
1747 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1748 ComponentInstance foundInstance = null;
1749 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1750 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1752 return foundInstance;
1755 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1757 Either<Boolean, ResponseFormat> result = Either.left(true);
1758 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1760 validateArtifactTypeExists(responseWrapper, artifactInfo);
1762 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1764 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1766 if (responseWrapper.isEmpty()) {
1767 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1770 if (responseWrapper.isEmpty()) {
1771 // Common code for all types
1772 // not allowed to change artifactType
1774 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1775 if (validateServiceApiType.isRight()) {
1776 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1780 if (responseWrapper.isEmpty()) {
1781 if (parentType.equals(NodeTypeEnum.Resource)) {
1782 // if (parentComponent instanceof Resource) {
1783 Resource resource = (Resource) parentComponent;
1784 ResourceTypeEnum resourceType = resource.getResourceType();
1785 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1786 if (config == null) {
1787 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1789 List<String> myList = config.getValidForResourceTypes();
1790 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1791 if (either.isRight()) {
1792 responseWrapper.setInnerElement(either.right().value());
1797 if (responseWrapper.isEmpty()) {
1798 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1801 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1802 String artifactName = artifactInfo.getArtifactName();
1803 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1804 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1808 if (responseWrapper.isEmpty()) {
1809 switch (artifactType) {
1813 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1817 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1818 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1821 case DCAE_INVENTORY_TOSCA:
1822 case DCAE_INVENTORY_JSON:
1823 case DCAE_INVENTORY_POLICY:
1824 // Validation is done in handle payload.
1825 case DCAE_INVENTORY_DOC:
1826 case DCAE_INVENTORY_BLUEPRINT:
1827 case DCAE_INVENTORY_EVENT:
1828 // No specific validation
1830 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1836 if (!responseWrapper.isEmpty()) {
1837 result = Either.right(responseWrapper.getInnerElement());
1842 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1843 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1844 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1845 responseWrapper.setInnerElement(responseFormat);
1846 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1850 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1851 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1852 if (parentType.equals(NodeTypeEnum.Resource)) {
1853 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1854 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1855 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1857 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1859 return resourceDeploymentArtifacts;
1862 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1863 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1864 if (artifactType == null) {
1865 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1866 responseWrapper.setInnerElement(responseFormat);
1867 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1871 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1872 ArtifactTypeConfig retConfig = null;
1873 String fileType = artifactType.getType();
1874 if (parentType.equals(NodeTypeEnum.Resource)) {
1875 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1876 } else if (parentType.equals(NodeTypeEnum.Service)) {
1877 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1878 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1879 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1884 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1885 // extract heat parameters
1886 if (artifactInfo.getPayloadData() != null) {
1887 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1888 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1889 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1890 log.info("failed to parse heat parameters ");
1891 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1892 return Either.right(responseFormat);
1893 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1894 artifactInfo.setListHeatParameters(heatParameters.left().value());
1897 return Either.left(true);
1902 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1903 String fileType = artifactType.getType();
1904 List<String> acceptedTypes = null;
1905 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1906 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1907 log.debug("parent type of artifact can be either resource or service");
1908 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1912 if (deploymentAcceptedTypes == null) {
1913 log.debug("parent type of artifact can be either resource or service");
1914 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1917 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1920 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1922 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1923 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1924 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1925 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1928 String artifactName = artifactInfo.getArtifactName();
1929 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1930 // Pavel - File extension validation is case-insensitive - Ella,
1932 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1933 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1934 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1939 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1941 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1942 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1943 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1945 if (errorWrapper.isEmpty()) {
1946 validateValidYaml(errorWrapper, artifactInfo);
1949 if (errorWrapper.isEmpty()) {
1950 // Validate Heat Exist
1951 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1954 // if (errorWrapper.isEmpty() && isCreate) {
1955 // // Validate Only Single HeatEnv Artifact
1956 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1959 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1960 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1963 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1964 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1968 Either<Boolean, ResponseFormat> eitherResponse;
1969 if (errorWrapper.isEmpty()) {
1970 eitherResponse = Either.left(true);
1972 eitherResponse = Either.right(errorWrapper.getInnerElement());
1974 return eitherResponse;
1977 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1978 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1979 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1980 if (fillArtifactPayload.isRight()) {
1981 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1982 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1985 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1989 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1990 Either<Boolean, ResponseFormat> result = Either.left(true);
1991 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1992 if (eitherArtifactData.isLeft()) {
1993 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1994 data = Base64.encodeBase64(data);
1995 payloadWrapper.setInnerElement(data);
1997 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1998 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1999 result = Either.right(responseFormat);
2005 @SuppressWarnings("unchecked")
2006 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2007 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2008 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2009 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2010 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2012 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2013 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2014 if (eitherHeatEnvProperties.isRight()) {
2015 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2016 errorWrapper.setInnerElement(responseFormat);
2017 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2018 } else if (eitherHeatProperties.isRight()) {
2019 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2020 errorWrapper.setInnerElement(responseFormat);
2021 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2023 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2024 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2025 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2026 if (heatEnvPropertiesKeys.size() > 0) {
2027 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2028 errorWrapper.setInnerElement(responseFormat);
2033 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2034 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2035 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2037 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2038 errorWrapper.setInnerElement(responseFormat);
2039 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2043 @SuppressWarnings("restriction")
2044 public boolean isValidXml(byte[] xmlToParse) {
2045 XMLReader parser = new SAXParser();
2047 parser.setFeature("http://apache.org/xml/features/validation/schema", false);
2048 } catch (SAXNotRecognizedException e) {
2049 e.printStackTrace();
2050 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2052 } catch (SAXNotSupportedException e) {
2053 e.printStackTrace();
2054 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2057 boolean isXmlValid = true;
2059 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2060 } catch (IOException | SAXException e) {
2061 log.debug("Xml is invalid : {}", e.getMessage(), e);
2067 public boolean isValidJson(byte[] jsonToParse) {
2068 String parsed = new String(jsonToParse);
2070 gson.fromJson(parsed, Object.class);
2071 } catch (Exception e) {
2072 log.debug("Json is invalid : {}", e.getMessage(), e);
2078 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2079 boolean typeArtifactFound = false;
2080 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2081 // (parentType == NodeTypeEnum.Resource) ?
2082 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2083 // parentComponent).iterator()
2084 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2086 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2088 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2089 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2090 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2092 if (typeArtifactFound) {
2093 String parentName = parentComponent.getName();
2094 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2096 errorWrapper.setInnerElement(responseFormat);
2097 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2102 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2103 boolean artifactNameFound = false;
2104 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2105 // (parentType == NodeTypeEnum.Resource) ?
2106 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2107 // parentComponent).iterator()
2108 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2110 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2112 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2113 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2115 if (artifactNameFound) {
2116 String parentName = parentComponent.getName();
2117 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2119 errorWrapper.setInnerElement(responseFormat);
2120 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2125 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2126 ComponentTypeEnum componentType) {
2127 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2128 if (res.isRight()) {
2129 ResponseFormat responseFormat;
2130 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2131 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2133 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2135 errorWrapper.setInnerElement(responseFormat);
2139 ArtifactDefinition heatArtifact = res.left().value();
2140 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2141 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2142 // while (!heatFound && parentArtifactsItr.hasNext()) {
2143 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2144 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2145 // heatFound = true;
2146 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2147 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2149 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2150 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2154 // if (!heatFound) {
2155 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2156 // errorWrapper.setInnerElement(responseFormat);
2157 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2162 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2163 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2164 // timeout > 0 for HEAT artifacts
2165 Integer timeout = artifactInfo.getTimeout();
2166 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2167 if (timeout == null) {
2168 artifactInfo.setTimeout(defaultTimeout);
2169 // HEAT artifact but timeout is invalid
2170 } else if (timeout < 1) {
2171 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2174 // US649856 - Allow several HEAT files on Resource
2176 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2177 * Either.right(errorWrapper.getInnerElement()); } }
2180 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2181 return Either.left(true);
2184 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2185 String listToString = (typeList != null) ? typeList.toString() : "";
2186 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2187 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2188 String resourceTypeName = resourceType.name();
2189 if (typeList != null && typeList.contains(resourceTypeName)) {
2190 either = Either.left(true);
2195 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2196 if (artifactInfo.getHeatParameters() != null) {
2197 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2198 String parameterType = heatParam.getType();
2199 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2200 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2201 if (heatParameterType == null) {
2202 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2203 return Either.right(responseFormat);
2206 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2207 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2208 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2209 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2210 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2211 return Either.right(responseFormat);
2215 return Either.left(artifactInfo);
2218 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2219 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2220 if (parentComponent.getDeploymentArtifacts() != null) {
2221 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2222 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2223 if (getRI.isRight()) {
2224 return deploymentArtifacts;
2226 ComponentInstance ri = getRI.left().value();
2227 if (ri.getDeploymentArtifacts() != null) {
2228 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2230 } else if (parentComponent.getDeploymentArtifacts() != null) {
2231 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2234 return deploymentArtifacts;
2237 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2238 // on create if null add informational to current
2239 if (artifactInfo.getArtifactGroupType() == null) {
2240 artifactInfo.setArtifactGroupType(type);
2242 if (artifactInfo.getUniqueId() != null) {
2243 log.error("artifact uniqid cannot be set ignoring");
2245 artifactInfo.setUniqueId(null);
2247 if (artifactInfo.getArtifactRef() != null) {
2248 log.error("artifact ref cannot be set ignoring");
2250 artifactInfo.setArtifactRef(null);
2252 if (artifactInfo.getArtifactRepository() != null) {
2253 log.error("artifact repository cannot be set ignoring");
2255 artifactInfo.setArtifactRepository(null);
2257 if (artifactInfo.getUserIdCreator() != null) {
2258 log.error("creator uuid cannot be set ignoring");
2260 artifactInfo.setArtifactCreator(user.getUserId());
2262 if (artifactInfo.getUserIdLastUpdater() != null) {
2263 log.error("userId of last updater cannot be set ignoring");
2265 artifactInfo.setUserIdLastUpdater(user.getUserId());
2267 if (artifactInfo.getCreatorFullName() != null) {
2268 log.error("creator Full name cannot be set ignoring");
2270 String fullName = user.getFirstName() + " " + user.getLastName();
2271 artifactInfo.setUpdaterFullName(fullName);
2273 if (artifactInfo.getUpdaterFullName() != null) {
2274 log.error("updater Full name cannot be set ignoring");
2276 artifactInfo.setUpdaterFullName(fullName);
2278 if (artifactInfo.getCreationDate() != null) {
2279 log.error("Creation Date cannot be set ignoring");
2281 long time = System.currentTimeMillis();
2282 artifactInfo.setCreationDate(time);
2284 if (artifactInfo.getLastUpdateDate() != null) {
2285 log.error("Last Update Date cannot be set ignoring");
2287 artifactInfo.setLastUpdateDate(time);
2289 if (artifactInfo.getEsId() != null) {
2290 log.error("es id cannot be set ignoring");
2292 artifactInfo.setEsId(null);
2297 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2298 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2299 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2300 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2301 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2302 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2305 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2306 String id = artifactId;
2307 if (artifactId == null || artifactId.isEmpty()) {
2308 String uniqueId = null;
2309 if (interfaceName != null && operationName != null) {
2310 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2312 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2314 artifactInfo.setUniqueId(uniqueId);
2315 artifactInfo.setEsId(uniqueId);
2318 artifactInfo.setUniqueId(artifactId);
2319 artifactInfo.setEsId(artifactId);
2324 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2325 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2326 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2327 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2328 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2331 boolean artifactTypeExist = false;
2332 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2333 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2335 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2336 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2339 allArtifactTypes = elementOperation.getAllArtifactTypes();
2341 if (allArtifactTypes.isRight()) {
2342 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2343 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2344 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2347 for (ArtifactType type : allArtifactTypes.left().value()) {
2348 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2349 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2350 artifactTypeExist = true;
2355 if (!artifactTypeExist) {
2356 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2357 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2358 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2361 return Either.left(ActionStatus.OK);
2364 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2366 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2367 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2369 if (parentType.equals(NodeTypeEnum.Service)) {
2370 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2371 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2372 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2374 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2376 if (deploymentArtifacts != null) {
2377 for (String artifactType : deploymentArtifacts.keySet()) {
2378 ArtifactType artifactT = new ArtifactType();
2379 artifactT.setName(artifactType);
2380 artifactTypes.add(artifactT);
2382 return Either.left(artifactTypes);
2384 return Either.right(ActionStatus.GENERAL_ERROR);
2389 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2390 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2391 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2393 return Either.left(true);
2397 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2398 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2399 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2402 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2403 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2404 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2406 artifactInfo.setArtifactName(normalizeFileName);
2408 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2409 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2412 return Either.left(true);
2415 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2416 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2417 log.info("artifact type is missing operation ignored");
2418 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2421 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2422 log.info("artifact type cannot be changed operation ignored");
2423 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2425 return Either.left(true);
2428 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2429 if (artifactInfo.getArtifactGroupType() == null) {
2430 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2433 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2434 log.info("artifact group type cannot be changed. operation failed");
2435 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2437 return Either.left(artifactInfo);
2440 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2442 // on update if null add informational to current
2443 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2444 currentArtifact.setArtifactGroupType(type);
2447 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2448 log.error("artifact uniqid cannot be set ignoring");
2450 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2452 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2453 log.error("artifact ref cannot be set ignoring");
2455 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2457 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2458 log.error("artifact repository cannot be set ignoring");
2460 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2462 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2463 log.error("creator uuid cannot be set ignoring");
2465 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2467 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2468 log.error("artifact creator cannot be set ignoring");
2470 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2472 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2473 log.error("userId of last updater cannot be set ignoring");
2475 artifactInfo.setUserIdLastUpdater(user.getUserId());
2477 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2478 log.error("creator Full name cannot be set ignoring");
2480 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2482 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2483 log.error("updater Full name cannot be set ignoring");
2485 String fullName = user.getFirstName() + " " + user.getLastName();
2486 artifactInfo.setUpdaterFullName(fullName);
2488 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2489 log.error("Creation Date cannot be set ignoring");
2491 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2493 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2494 log.error("Last Update Date cannot be set ignoring");
2496 long time = System.currentTimeMillis();
2497 artifactInfo.setLastUpdateDate(time);
2499 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2500 log.error("es id cannot be set ignoring");
2502 artifactInfo.setEsId(currentArtifact.getUniqueId());
2504 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2505 log.error(" Artifact Display Name cannot be set ignoring");
2507 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2509 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2510 log.debug("serviceApi cannot be set. ignoring.");
2512 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2514 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2515 log.debug("artifact group cannot be set. ignoring.");
2517 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2519 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2521 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2522 log.debug("artifact UUID cannot be set. ignoring.");
2524 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2526 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2527 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2531 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2533 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2534 for (HeatParameterDefinition parameter : heatParameters) {
2535 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2537 if (currentParam != null) {
2539 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2540 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2541 parameter.setName(currentParam.getName());
2543 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2544 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2545 parameter.setDefaultValue(currentParam.getDefaultValue());
2547 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2548 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2549 parameter.setType(currentParam.getType());
2551 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2552 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2553 parameter.setDescription(currentParam.getDescription());
2556 // check and set current value
2557 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2558 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2559 parameter.setCurrentValue(currentParam.getDefaultValue());
2565 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2567 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2568 for (HeatParameterDefinition param : currentParameters) {
2569 currentParamsMap.put(param.getUniqueId(), param);
2571 return currentParamsMap;
2574 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2575 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2576 log.debug("Artifact url cannot be empty.");
2577 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2579 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2581 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2582 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2584 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2585 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2588 return Either.left(true);
2591 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2592 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2593 log.debug("Artifact description cannot be empty.");
2594 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2596 String description = artifactInfo.getDescription();
2597 description = ValidationUtils.removeNoneUtf8Chars(description);
2598 description = ValidationUtils.normaliseWhitespace(description);
2599 description = ValidationUtils.stripOctets(description);
2600 description = ValidationUtils.removeHtmlTagsOnly(description);
2601 if (!ValidationUtils.validateIsEnglish(description)) {
2602 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2604 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2605 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2607 artifactInfo.setDescription(description);
2608 return Either.left(true);
2611 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2612 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2613 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2614 String prevArtifactId = null;
2615 String currArtifactId = artifactId;
2617 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2618 Either<ArtifactDefinition, Operation> insideEither = null;
2620 if (artifactData == null) {
2621 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2622 log.debug("Failed to create artifact object for ES.");
2623 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2624 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2625 resultOp = Either.right(responseFormat);
2628 log.trace("Try to update entry on graph");
2629 String artifactUniqueId = null;
2630 ArtifactDefinition artifactDefinition = artifactInfo;
2631 StorageOperationStatus error = null;
2633 boolean isLeft = false;
2634 if (interfaceType != null && operationName != null) {
2635 // lifecycle artifact
2637 * Operation operation = convertToOperation(artifactInfo, operationName);
2639 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2641 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2643 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2646 log.debug("Enty on graph is updated. Update artifact in ES");
2648 // Changing previous and current artifactId for auditing
2649 prevArtifactId = currArtifactId;
2650 currArtifactId = artifactDefinition.getUniqueId();
2652 NodeTypeEnum convertParentType = convertParentType(componentType);
2654 if (decodedPayload == null) {
2655 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2656 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2657 // Either<ESArtifactData, ResourceUploadStatus>
2658 // artifactfromES = daoUploader.getArtifact(artifactId);
2659 if (artifactFromCassandra.isRight()) {
2660 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2661 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2662 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2663 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2664 resultOp = Either.right(responseFormat);
2667 // clone data to new artifact
2668 artifactData.setData(artifactFromCassandra.left().value().getData());
2669 artifactData.setId(artifactFromCassandra.left().value().getId());
2672 if (artifactDefinition.getEsId() == null) {
2673 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2674 artifactData.setId(artifactDefinition.getUniqueId());
2678 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2679 isLeft = result.isLeft();
2681 artifactUniqueId = result.left().value().getUniqueId();
2682 artifactDefinition = result.left().value();
2683 String artifactType = artifactInfo.getArtifactType();
2684 if (NodeTypeEnum.Resource == convertParentType
2685 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2687 if (!artifactUniqueId.equals(artifactId)) {
2688 // need to update the generated id in heat env
2689 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2690 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2691 if (findFirst.isPresent()) {
2692 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2693 artifactEnvInfo.setArtifactChecksum(null);
2694 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2699 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2701 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2702 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2707 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2709 insideEither = Either.left(result.left().value());
2710 resultOp = Either.left(insideEither);
2711 if (error != StorageOperationStatus.OK) {
2716 error = result.right().value();
2720 // create new entry in ES
2722 if (artifactData.getData() != null) {
2723 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2724 artifactData.setId(artifactDefinition.getEsId());
2725 res = saveArtifacts(artifactData, parentId, false);
2731 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2732 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2733 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2734 // resultOp = Either.left(result.left().value());
2737 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2738 log.debug("Failed to save the artifact.");
2739 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2740 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2741 resultOp = Either.right(responseFormat);
2749 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2750 log.trace("Starting payload handling");
2751 byte[] payload = artifactInfo.getPayloadData();
2752 byte[] decodedPayload = null;
2754 if (payload != null && payload.length != 0) {
2755 // the generated artifacts were already decoded by the handler
2756 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2757 if (decodedPayload.length == 0) {
2758 log.debug("Failed to decode the payload.");
2759 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2760 return Either.right(responseFormat);
2763 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2764 artifactInfo.setArtifactChecksum(checkSum);
2765 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2767 // Specific payload validations of different types
2768 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2769 if (isDeploymentArtifact(artifactInfo)) {
2770 log.trace("Starting deployment artifacts payload validation");
2771 String artifactType = artifactInfo.getArtifactType();
2772 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2773 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2774 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2775 if (isValidPayload.isLeft()) {
2776 isValidPayload = extractHeatParameters(artifactInfo);
2778 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2779 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2780 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
2781 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2783 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2785 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2786 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2787 String artifactFileName = artifactInfo.getArtifactName();
2788 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2789 switch (fileExtension) {
2791 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2794 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2798 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2803 if (isValidPayload.isRight()) {
2804 ResponseFormat responseFormat = isValidPayload.right().value();
2805 return Either.right(responseFormat);
2808 } // null/empty payload is normal if called from metadata update ONLY.
2809 // The validation of whether this is metadata/payload update case is
2810 // currently done separately
2812 if (!isArtifactMetadataUpdate) {
2813 log.debug("Payload is missing.");
2814 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2815 return Either.right(responseFormat);
2818 log.trace("Ended payload handling");
2819 return Either.left(decodedPayload);
2822 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2823 // Basic YAML validation
2824 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2825 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2826 log.debug("Invalid YAML format");
2827 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2828 return Either.right(responseFormat);
2830 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2831 // HEAT specific YAML validation
2832 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2833 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2834 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2835 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2836 return Either.right(responseFormat);
2840 return Either.left(true);
2843 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2844 Either<Boolean, ResponseFormat> res = Either.left(true);
2845 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2846 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2847 log.debug("Invalid YAML format");
2848 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2849 res = Either.right(responseFormat);
2855 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
2856 boolean isXmlValid = isValidXml(payload);
2858 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2859 log.debug("Invalid XML content");
2860 return Either.right(responseFormat);
2862 return Either.left(true);
2865 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2866 boolean isJsonValid = isValidJson(payload);
2868 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2869 log.debug("Invalid JSON content");
2870 return Either.right(responseFormat);
2872 return Either.left(true);
2875 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2876 if (opState == null || opState.isRight()) {
2877 titanDao.rollback();
2883 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2884 boolean inTransaction) {
2885 User user = new User();
2886 user.setUserId(userUserId);
2887 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2888 if (parent.isRight()) {
2889 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2890 return Either.right(responseFormat);
2892 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2893 false, inTransaction);
2894 if (handleDelete.isRight()) {
2895 return Either.right(handleDelete.right().value());
2897 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2898 return Either.left(result.right().value());
2902 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2904 if (artifacts != null && !artifacts.isEmpty()) {
2905 for (ArtifactDefinition artifactDefinition : artifacts) {
2906 String esId = artifactDefinition.getEsId();
2907 if (esId != null && !esId.isEmpty()) {
2908 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2909 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2910 return deleteIfNotOnGraph;
2915 return StorageOperationStatus.OK;
2918 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2919 Operation op = new Operation();
2920 long time = System.currentTimeMillis();
2921 op.setCreationDate(time);
2923 String artifactName = artifactInfo.getArtifactName();
2924 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2926 op.setImplementation(artifactInfo);
2927 op.setLastUpdateDate(time);
2931 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2932 String newArtifactName = operationName + "_" + artifactName;
2933 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2934 return newArtifactName;
2937 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2938 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2939 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2940 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2941 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2943 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2944 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2945 // // last one. need to delete in ES
2946 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2947 // artifactCassandraDao.deleteArtifact(artifactEsId);
2948 // return StorageOperationStatus.OK;
2950 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2954 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2955 // return StorageOperationStatus.OK;
2959 return StorageOperationStatus.OK;
2963 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2965 // General validation
2966 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2967 log.debug("One of the function parameteres is null");
2968 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2971 // Normalizing artifact name
2972 artifactName = ValidationUtils.normalizeFileName(artifactName);
2974 // Resource validation
2975 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2976 if (validateResourceNameAndVersion.isRight()) {
2977 return Either.right(validateResourceNameAndVersion.right().value());
2980 Resource resource = validateResourceNameAndVersion.left().value();
2981 String resourceId = resource.getUniqueId();
2983 // Service validation
2984 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2985 if (validateServiceNameAndVersion.isRight()) {
2986 return Either.right(validateServiceNameAndVersion.right().value());
2989 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2990 if (artifacts == null || artifacts.isEmpty()) {
2991 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2992 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2995 ArtifactDefinition deploymentArtifact = null;
2997 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2998 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2999 log.debug("Found deployment artifact {}", artifactName);
3000 deploymentArtifact = artifactDefinition;
3005 if (deploymentArtifact == null) {
3006 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3007 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3010 // Downloading the artifact
3011 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3012 if (downloadArtifactEither.isRight()) {
3013 log.debug("Download artifact {} failed", artifactName);
3014 return Either.right(downloadArtifactEither.right().value());
3016 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3017 return Either.left(downloadArtifactEither.left().value().getRight());
3021 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3023 // General validation
3024 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3025 log.debug("One of the function parameteres is null");
3026 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3029 // Normalizing artifact name
3030 artifactName = ValidationUtils.normalizeFileName(artifactName);
3032 // Resource validation
3034 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3035 * Either.right(validateResourceNameAndVersion.right().value()); }
3037 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3040 // Service validation
3041 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3042 if (validateServiceNameAndVersion.isRight()) {
3043 return Either.right(validateServiceNameAndVersion.right().value());
3046 Service service = validateServiceNameAndVersion.left().value();
3048 // ResourceInstance validation
3049 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3050 if (validateResourceInstance.isRight()) {
3051 return Either.right(validateResourceInstance.right().value());
3054 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3056 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3058 final String finalArtifactName = artifactName;
3059 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3061 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3062 ArtifactDefinition deployableArtifact;
3064 if (!hasDeploymentArtifacts) {
3065 log.debug("Deployment artifact with name {} not found", artifactName);
3066 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3069 log.debug("Found deployment artifact {}", artifactName);
3070 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3071 // Downloading the artifact
3072 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3074 if (downloadArtifactEither.isRight()) {
3075 log.debug("Download artifact {} failed", artifactName);
3076 return Either.right(downloadArtifactEither.right().value());
3078 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3079 return Either.left(downloadArtifactEither.left().value().getRight());
3082 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3084 List<ComponentInstance> riList = service.getComponentInstances();
3085 for (ComponentInstance ri : riList) {
3086 if (ri.getNormalizedName().equals(resourceInstanceName))
3087 return Either.left(ri);
3090 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3093 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3095 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3096 if (serviceListBySystemName.isRight()) {
3097 log.debug("Couldn't fetch any service with name {}", serviceName);
3098 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3100 List<Service> serviceList = serviceListBySystemName.left().value();
3101 if (serviceList == null || serviceList.isEmpty()) {
3102 log.debug("Couldn't fetch any service with name {}", serviceName);
3103 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3106 Service foundService = null;
3107 for (Service service : serviceList) {
3108 if (service.getVersion().equals(serviceVersion)) {
3109 log.trace("Found service with version {}", serviceVersion);
3110 foundService = service;
3115 if (foundService == null) {
3116 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3117 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3119 return Either.left(foundService);
3122 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3124 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3125 if (resourceListBySystemName.isRight()) {
3126 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3127 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3129 return Either.left(resourceListBySystemName.left().value());
3132 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3134 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3135 if (serviceName == null || serviceVersion == null || artifactName == null) {
3136 log.debug("One of the function parameteres is null");
3137 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3140 // Normalizing artifact name
3141 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3143 // Service validation
3144 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3145 if (validateServiceNameAndVersion.isRight()) {
3146 return Either.right(validateServiceNameAndVersion.right().value());
3149 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3151 // Looking for deployment or tosca artifacts
3152 Service service = validateServiceNameAndVersion.left().value();
3154 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3155 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3156 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3159 Optional<ArtifactDefinition> foundArtifactOptl = null;
3161 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3162 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3163 // filters artifact by name
3164 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3166 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3167 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3168 // filters TOSCA artifact by name
3169 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3171 if (!foundArtifactOptl.isPresent()) {
3172 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3173 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3175 log.debug("Found deployment artifact {}", normalizedArtifactName);
3176 // Downloading the artifact
3177 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
3178 if (downloadArtifactEither.isRight()) {
3179 log.debug("Download artifact {} failed", normalizedArtifactName);
3180 return Either.right(downloadArtifactEither.right().value());
3182 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3183 return Either.left(downloadArtifactEither.left().value().getRight());
3186 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3187 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3188 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3189 if (artifactById.isRight()) {
3190 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3191 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3192 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3194 ArtifactDefinition artifactDefinition = artifactById.left().value();
3195 if (artifactDefinition == null) {
3196 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3197 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3200 return downloadArtifact(artifactDefinition);
3203 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3204 boolean found = false;
3205 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3206 if (artifactsS != null) {
3207 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3208 if (entry.getValue().getUniqueId().equals(artifactId)) {
3214 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3215 if (!found && deploymentArtifactsS != null) {
3216 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3217 if (entry.getValue().getUniqueId().equals(artifactId)) {
3223 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3224 if (!found && toscaArtifactsS != null) {
3225 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3226 if (entry.getValue().getUniqueId().equals(artifactId)) {
3232 switch (component.getComponentType()) {
3234 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3235 if (!found && interfaces != null) {
3236 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3237 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3238 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3239 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3248 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3249 if (!found && apiArtifacts != null) {
3250 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3251 if (entry.getValue().getUniqueId().equals(artifactId)) {
3265 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3267 boolean found = false;
3268 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3269 ComponentInstance resourceInstance = null;
3270 for (ComponentInstance ri : resourceInstances) {
3271 if (ri.getUniqueId().equals(resourceInstanceId)) {
3272 resourceInstance = ri;
3276 if (resourceInstance != null) {
3277 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3278 if (artifacts != null) {
3279 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3280 if (entry.getValue().getUniqueId().equals(artifactId)) {
3287 artifacts = resourceInstance.getArtifacts();
3288 if (artifacts != null) {
3289 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3290 if (entry.getValue().getUniqueId().equals(artifactId)) {
3301 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3302 String containerComponentType, boolean inTransaction) {
3304 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3305 componentForAudit.getNodeType();
3307 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3309 if (componentResult.isRight()) {
3310 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3311 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3312 log.debug("Service not found, serviceId {}", componentId);
3313 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3314 return Either.right(responseFormat);
3316 return Either.left(componentResult.left().value());
3319 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3320 ComponentTypeEnum componentType) {
3321 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3322 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3323 if (canWork.isRight()) {
3324 String uniqueId = component.getUniqueId();
3325 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3326 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3327 return Either.right(canWork.right().value());
3330 return Either.left(true);
3333 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3335 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3336 String role = user.getRole();
3337 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3338 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3339 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3340 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3341 return Either.right(responseFormat);
3344 return Either.left(true);
3347 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3348 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3350 if (validateUserExists.isRight()) {
3351 User user = new User();
3352 user.setUserId(userId);
3353 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3354 return Either.right(validateUserExists.right().value());
3356 return Either.left(validateUserExists.left().value());
3359 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3360 AuditingActionEnum auditingAction = null;
3361 switch (operation.getArtifactOperationEnum()) {
3363 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3366 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3369 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3372 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3377 return auditingAction;
3380 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3381 String esArtifactId = artifactDefinition.getEsId();
3382 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3383 if (artifactfromES.isRight()) {
3384 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3385 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3386 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3387 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3388 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3391 ESArtifactData esArtifactData = artifactfromES.left().value();
3392 byte[] data = esArtifactData.getDataAsArray();
3394 log.debug("Artifact data from ES is null");
3395 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3397 String artifactName = artifactDefinition.getArtifactName();
3398 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3399 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3402 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3403 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3404 return artifactData;
3407 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3409 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3411 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3412 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3414 log.info("Failed to save artifact {}.", artifactData.getId());
3420 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3421 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3424 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3425 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3428 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3429 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3430 if (user.isRight()) {
3431 ResponseFormat responseFormat;
3432 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3433 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3434 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3436 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3437 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3439 return Either.right(responseFormat);
3442 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3443 return Either.left(artifactDefinition);
3446 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3447 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3449 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3450 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3451 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3453 artifactInfo.setArtifactDisplayName(artifactName);
3454 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3455 artifactInfo.setArtifactType(artifactType);
3456 artifactInfo.setDescription(artifactDescription);
3457 artifactInfo.setArtifactGroupType(groupType);
3458 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3460 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3462 return artifactInfo;
3465 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3466 String uniqueId = null;
3468 if (resourceId != null) {
3469 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3470 artifactInfo.setUniqueId(uniqueId);
3472 artifactInfo.setUserIdCreator(user.getUserId());
3473 String fullName = user.getFullName();
3474 artifactInfo.setUpdaterFullName(fullName);
3476 long time = System.currentTimeMillis();
3478 artifactInfo.setCreatorFullName(fullName);
3479 artifactInfo.setCreationDate(time);
3481 artifactInfo.setLastUpdateDate(time);
3482 artifactInfo.setUserIdLastUpdater(user.getUserId());
3484 artifactInfo.setMandatory(true);
3487 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3488 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3491 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3492 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3495 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3497 byte[] payload = payloadStr.getBytes();
3499 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3500 return Either.left(artifactData);
3505 * @param artifactDefinition
3508 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3509 boolean shouldLock, String instanceId) {
3510 String payload = generateHeatEnvPayload(artifactDefinition);
3511 String prevUUID = artifactDefinition.getArtifactUUID();
3512 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3513 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3514 if (generateResult.isLeft()) {
3515 ArtifactDefinition updatedArtDef = generateResult.left().value();
3516 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3517 List<ComponentInstance> componentInstances = component.getComponentInstances();
3518 if (componentInstances != null) {
3519 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3520 if (findFirst.isPresent()) {
3521 ComponentInstance relevantInst = findFirst.get();
3522 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3524 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3525 updatedGroupInstances.forEach(gi -> {
3526 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3527 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3529 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3530 if (status.isRight()) {
3531 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3532 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3533 return Either.right(responseFormat);
3541 return generateResult;
3544 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3545 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3546 StringBuilder sb = new StringBuilder();
3547 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3548 sb.append("parameters:\n");
3549 if (heatParameters != null) {
3550 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3552 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3554 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3556 String heatValue = heatParameterDefinition.getCurrentValue();
3557 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3558 heatValue = heatParameterDefinition.getDefaultValue();
3559 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3560 empltyHeatValues.add(heatParameterDefinition);
3564 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3568 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3571 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3573 case COMMA_DELIMITED_LIST:
3575 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3578 String value = heatValue;
3579 boolean starts = value.startsWith("\"");
3580 boolean ends = value.endsWith("\"");
3581 if (!(starts && ends)) {
3582 starts = value.startsWith("'");
3583 ends = value.endsWith("'");
3584 if (!(starts && ends)) {
3585 value = "\"" + value + "\"";
3588 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3595 if (!empltyHeatValues.isEmpty()) {
3596 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3597 empltyHeatValues.forEach(hv -> {
3598 sb.append(" ").append(hv.getName()).append(":");
3599 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3600 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3601 sb.append(" \"\"").append("\n");
3603 sb.append(" ").append("\n");
3608 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3611 String result = sb.toString().replaceAll("\\\\n", "\n");
3618 * @param artifactDefinition
3622 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3623 User modifier, boolean shouldLock, String instanceId) {
3624 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3625 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3629 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3630 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3632 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3633 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3635 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3636 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3637 ESArtifactData artifactData = null;
3639 if (artifactDataRes.isLeft()) {
3640 artifactData = artifactDataRes.left().value();
3642 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3643 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3644 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3646 return Either.right(artifactDataRes.right().value());
3648 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3650 String esArtifactId = artifactDefinition.getEsId();
3651 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3652 ESArtifactData esArtifactData;
3653 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3654 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3655 if (artifactfromES.isRight()) {
3656 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3657 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3658 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3659 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3660 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3662 esArtifactData = artifactfromES.left().value();
3663 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3665 oldCheckSum = artifactDefinition.getArtifactChecksum();
3668 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3671 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3672 if (lockComponent.isRight()) {
3673 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3674 return Either.right(lockComponent.right().value());
3678 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3680 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3681 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3682 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3683 if (updateArifactDefinitionStatus.isRight()) {
3684 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3685 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3686 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3687 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3689 return Either.right(responseFormat);
3693 oldCheckSum = artifactDefinition.getArtifactChecksum();
3694 artifactDefinition.setArtifactChecksum(newCheckSum);
3695 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3696 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3697 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3698 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3700 log.trace("Update Payload ", artifactDefinition.getEsId());
3702 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3704 artifactDefinition = updateArifactDefinitionStatus.left().value();
3705 artifactData.setId(artifactDefinition.getUniqueId());
3706 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3708 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3710 log.debug("Artifact Saved In ES {}", artifactData.getId());
3711 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3712 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3713 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3716 titanDao.rollback();
3717 log.info("Failed to save artifact {}.", artifactData.getId());
3718 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3719 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3720 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3722 return Either.right(responseFormat);
3725 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3726 log.debug("Failed To update artifact {}", artifactData.getId());
3727 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3728 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3730 return Either.right(responseFormat);
3735 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3740 return Either.left(artifactDefinition);
3743 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3744 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3745 convertParentType(componentType);
3746 String parentId = parent.getUniqueId();
3747 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3748 ArtifactDefinition currArtifact = artifactInfo;
3750 if (origMd5 != null) {
3751 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3752 if (validateMd5.isRight()) {
3753 ResponseFormat responseFormat = validateMd5.right().value();
3754 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3755 return Either.right(responseFormat);
3758 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3759 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3760 if (deploymentValidationResult.isRight()) {
3761 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3762 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3763 return Either.right(responseFormat);
3766 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3767 if (payloadEither.isRight()) {
3768 ResponseFormat responseFormat = payloadEither.right().value();
3769 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3770 return Either.right(responseFormat);
3772 } else { // duplicate
3773 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3774 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3775 return Either.right(responseFormat);
3781 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3782 if (lockComponent.isRight()) {
3783 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3784 return Either.right(lockComponent.right().value());
3787 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3789 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3794 if (resultOp == null || resultOp.isRight()) {
3795 log.debug("all changes rollback");
3796 if (false == inTransaction)
3797 titanDao.rollback();
3799 log.debug("all changes committed");
3800 if (false == inTransaction)
3804 componentType = parent.getComponentType();
3805 NodeTypeEnum nodeType = componentType.getNodeType();
3806 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3807 // graphLockOperation.unlockComponent(parentId, parentType);
3811 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3812 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3814 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3815 Either<ArtifactDefinition, Operation> insideEither = null;
3817 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3819 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3820 if (getRI.isRight()) {
3821 return Either.right(getRI.right().value());
3823 ComponentInstance ri = getRI.left().value();
3824 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3825 if (getArtifactRes.isRight()) {
3826 return Either.right(getArtifactRes.right().value());
3828 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3830 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3831 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3832 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3833 return Either.right(responseFormat);
3835 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3836 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3837 new ArrayList<HeatParameterDefinition>();
3840 if (origMd5 != null) {
3841 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3842 updatedHeatEnvParams, currArtifact.getArtifactName());
3843 if (uploadParamsValidationResult.isRight()) {
3844 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3845 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3846 return Either.right(responseFormat);
3848 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3851 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3852 if (validateAndConvertHeatParamers.isRight()) {
3853 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3854 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3855 return Either.right(responseFormat);
3858 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3860 // fill reduced heat env parameters List for updating
3861 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3862 paramName = heatEnvParam.getName();
3863 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3864 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3865 String updatedParamValue = heatEnvParam.getCurrentValue();
3866 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3867 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3868 } else if (updatedParamValue != null) {
3869 currHeatParam.setCurrentValue(updatedParamValue);
3874 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3875 currArtifact.setListHeatParameters(currentHeatEnvParams);
3877 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3878 if (updateArifactRes.isRight()) {
3879 log.debug("Failed to update artifact on graph - {}", artifactId);
3880 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3881 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3882 return Either.right(responseFormat);
3884 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3885 if (error != StorageOperationStatus.OK) {
3886 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3887 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3888 return Either.right(responseFormat);
3891 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3892 if (error != StorageOperationStatus.OK) {
3893 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3894 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3895 return Either.right(responseFormat);
3901 insideEither = Either.left(currArtifact);
3902 resultOp = Either.left(insideEither);
3903 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3904 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3908 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3909 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3911 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3912 Either<ArtifactDefinition, Operation> insideEither = null;
3914 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3916 String currentHeatId = currHeatArtifact.getUniqueId();
3918 String esArtifactId = currHeatArtifact.getEsId();
3919 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3920 if (artifactfromES.isRight()) {
3921 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3922 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3923 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3924 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3925 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3928 ESArtifactData esArtifactData = artifactfromES.left().value();
3929 byte[] data = esArtifactData.getDataAsArray();
3932 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3934 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3935 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3936 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3938 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3941 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3943 paramName = heatEnvParam.getName();
3944 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3945 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3947 String updatedParamValue = heatEnvParam.getCurrentValue();
3948 if (updatedParamValue == null)
3949 updatedParamValue = heatEnvParam.getDefaultValue();
3950 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3951 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3952 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3954 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3955 return Either.right(responseFormat);
3958 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3959 newHeatEnvParams.add(currHeatParam);
3964 if (!newHeatEnvParams.isEmpty()) {
3965 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3966 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3968 if (operationStatus.isRight()) {
3969 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3971 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3972 return Either.right(responseFormat);
3975 updatedHeatArt = operationStatus.left().value();
3977 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3978 esArtifactData.setId(updatedHeatArt.getEsId());
3979 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3982 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3983 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3984 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3985 // resultOp = Either.left(result.left().value());
3988 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3989 log.debug("Failed to save the artifact.");
3990 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3991 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3992 resultOp = Either.right(responseFormat);
3996 insideEither = Either.left(updatedHeatArt);
3999 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4000 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4001 artifactEnvInfo.setArtifactChecksum(null);
4002 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
4004 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
4007 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4008 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
4009 if (result != ActionStatus.OK) {
4010 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4011 return Either.right(responseFormat);
4015 if (updatedHeatEnvParams.isEmpty()) {
4016 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
4018 resultOp = Either.left(insideEither);
4019 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4020 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4025 private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4026 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4027 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4028 return Either.right(responseFormat);
4032 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4033 StorageOperationStatus error = StorageOperationStatus.OK;
4034 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4035 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4036 // List<GroupInstance> associatedGroups = null;
4037 List<String> groupInstancesId = null;
4038 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4039 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4041 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4042 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4043 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4049 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4050 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4052 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4053 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4054 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4055 return Either.right(responseFormat);
4058 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4059 String paramName = uploadedHeatParam.getName();
4060 boolean isExistsInHeat = false;
4061 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4062 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4064 isExistsInHeat = true;
4065 uploadedHeatParam.setType(currHeatParam.getType());
4066 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4067 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4068 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4072 if (!isExistsInHeat) {
4073 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4074 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4075 return Either.right(responseFormat);
4078 return Either.left(updatedHeatEnvParams);
4081 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4082 ResponseFormat responseFormat = null;
4083 List<ComponentInstance> ris = component.getComponentInstances();
4084 for (ComponentInstance ri : ris) {
4085 if (riID.equals(ri.getUniqueId())) {
4086 return Either.left(ri);
4089 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4090 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4091 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4092 return Either.right(responseFormat);
4095 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4096 ResponseFormat responseFormat = null;
4097 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4098 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4099 if (artifactId.equals(artifact.getUniqueId())) {
4100 return Either.left(artifact);
4103 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4104 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4105 return Either.right(responseFormat);
4108 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4109 ArtifactDefinition ret;
4110 if (eitherArtifact.isLeft()) {
4111 ret = eitherArtifact.left().value();
4113 ret = eitherArtifact.right().value().getImplementationArtifact();
4119 * downloads artifact of component by UUIDs
4121 * @param componentType
4122 * @param componentUuid
4123 * @param artifactUUID
4124 * @param auditAdditionalParam
4127 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4128 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4129 Either<byte[], ResponseFormat> result;
4130 byte[] downloadedArtifact = null;
4131 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4132 if (errorWrapper.isEmpty()) {
4133 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4134 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4136 if (errorWrapper.isEmpty()) {
4137 result = Either.left(downloadedArtifact);
4139 result = Either.right(errorWrapper.getInnerElement());
4145 * downloads an artifact of resource instance of component by UUIDs
4147 * @param componentType
4148 * @param componentUuid
4149 * @param resourceName
4150 * @param artifactUUID
4151 * @param auditAdditionalParam
4154 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4155 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4156 Either<byte[], ResponseFormat> result;
4157 byte[] downloadedArtifact = null;
4158 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4159 if (errorWrapper.isEmpty()) {
4160 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4162 if (errorWrapper.isEmpty()) {
4163 result = Either.left(downloadedArtifact);
4165 result = Either.right(errorWrapper.getInnerElement());
4171 * uploads an artifact to a component by UUID
4175 * @param componentType
4176 * @param componentUuid
4177 * @param additionalParams
4181 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4182 ArtifactOperationInfo operation) {
4183 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4184 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4185 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4186 ArtifactDefinition uploadArtifact = null;
4187 Component component = null;
4188 String componentId = null;
4189 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4190 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4191 String userId = request.getHeader(Constants.USER_ID_HEADER);
4193 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4194 if (getComponentRes.isRight()) {
4195 StorageOperationStatus status = getComponentRes.right().value();
4196 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4197 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4199 if (errorWrapper.isEmpty()) {
4200 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4201 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4203 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4204 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4205 if (component != null) {
4206 componentId = component.getUniqueId();
4207 componentName = component.getName();
4210 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4212 if (errorWrapper.isEmpty()) {
4213 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4214 if (actionResult.isRight()) {
4215 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4216 errorWrapper.setInnerElement(actionResult.right().value());
4219 if (errorWrapper.isEmpty()) {
4220 uploadArtifact = actionResult.left().value().left().value();
4221 uploadArtifactResult = Either.left(uploadArtifact);
4223 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4225 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4226 return uploadArtifactResult;
4230 * upload an artifact to a resource instance by UUID
4234 * @param componentType
4235 * @param componentUuid
4236 * @param resourceInstanceName
4237 * @param additionalParams
4241 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4242 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4243 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4244 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4245 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4246 ArtifactDefinition uploadArtifact = null;
4247 Component component = null;
4248 String componentInstanceId;
4250 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4251 String userId = request.getHeader(Constants.USER_ID_HEADER);
4253 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4254 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4255 if (getComponentRes.isRight()) {
4256 StorageOperationStatus status = getComponentRes.right().value();
4257 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4258 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4260 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4261 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4263 if (errorWrapper.isEmpty()) {
4264 if (component == null) {
4265 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4267 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4270 if (errorWrapper.isEmpty()) {
4271 componentInstanceId = componentRiPair.getRight().getUniqueId();
4272 componentId = componentRiPair.getLeft().getUniqueId();
4273 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4275 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4276 if (actionResult.isRight()) {
4277 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4278 errorWrapper.setInnerElement(actionResult.right().value());
4281 if (errorWrapper.isEmpty()) {
4282 uploadArtifact = actionResult.left().value().left().value();
4283 uploadArtifactResult = Either.left(uploadArtifact);
4285 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4287 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4288 return uploadArtifactResult;
4292 * updates an artifact on a component by UUID
4296 * @param componentType
4297 * @param componentUuid
4298 * @param artifactUUID
4299 * @param additionalParams
4304 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4305 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4306 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4307 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4308 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4309 ArtifactDefinition updateArtifact = null;
4310 Component component = null;
4311 String componentId = null;
4312 String artifactId = null;
4313 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4314 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4315 String userId = request.getHeader(Constants.USER_ID_HEADER);
4317 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4318 if (getComponentRes.isRight()) {
4319 StorageOperationStatus status = getComponentRes.right().value();
4320 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4321 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4323 if (errorWrapper.isEmpty()) {
4324 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4325 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4327 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4328 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4329 if (component != null) {
4330 componentId = component.getUniqueId();
4331 componentName = component.getName();
4334 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4336 if (errorWrapper.isEmpty()) {
4337 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4339 if (errorWrapper.isEmpty()) {
4340 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4341 if (actionResult.isRight()) {
4342 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4343 errorWrapper.setInnerElement(actionResult.right().value());
4346 if (errorWrapper.isEmpty()) {
4347 updateArtifact = actionResult.left().value().left().value();
4348 updateArtifactResult = Either.left(updateArtifact);
4351 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4353 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4354 return updateArtifactResult;
4358 * updates an artifact on a resource instance by UUID
4362 * @param componentType
4363 * @param componentUuid
4364 * @param resourceInstanceName
4365 * @param artifactUUID
4366 * @param additionalParams
4371 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4372 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4374 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4375 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4376 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4377 ArtifactDefinition updateArtifact = null;
4378 Component component = null;
4379 String componentInstanceId = null;
4380 String componentId = null;
4381 String artifactId = null;
4382 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4383 String userId = request.getHeader(Constants.USER_ID_HEADER);
4385 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4386 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4387 if (getComponentRes.isRight()) {
4388 StorageOperationStatus status = getComponentRes.right().value();
4389 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4390 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4392 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4393 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4395 if (errorWrapper.isEmpty()) {
4396 if (component == null) {
4397 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4399 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4402 if (errorWrapper.isEmpty()) {
4403 componentInstanceId = componentRiPair.getRight().getUniqueId();
4404 componentId = componentRiPair.getLeft().getUniqueId();
4405 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4407 if (errorWrapper.isEmpty()) {
4408 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4410 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4411 if (actionResult.isRight()) {
4412 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4413 errorWrapper.setInnerElement(actionResult.right().value());
4416 if (errorWrapper.isEmpty()) {
4417 updateArtifact = actionResult.left().value().left().value();
4418 updateArtifactResult = Either.left(updateArtifact);
4420 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4422 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4423 return updateArtifactResult;
4427 * deletes an artifact on a component by UUID
4430 * @param componentType
4431 * @param componentUuid
4432 * @param artifactUUID
4433 * @param additionalParams
4438 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4439 ArtifactOperationInfo operation) {
4441 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4442 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4443 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4444 ArtifactDefinition deleteArtifact = null;
4445 Component component = null;
4446 String componentId = null;
4447 String artifactId = null;
4448 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4449 String userId = request.getHeader(Constants.USER_ID_HEADER);
4451 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4452 if (getComponentRes.isRight()) {
4453 StorageOperationStatus status = getComponentRes.right().value();
4454 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4455 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4457 if (errorWrapper.isEmpty()) {
4458 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4459 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4460 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4461 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4462 if (component != null) {
4463 componentId = component.getUniqueId();
4464 componentName = component.getName();
4467 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4469 if (errorWrapper.isEmpty()) {
4470 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4472 if (errorWrapper.isEmpty()) {
4473 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4474 if (actionResult.isRight()) {
4475 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4476 errorWrapper.setInnerElement(actionResult.right().value());
4479 if (errorWrapper.isEmpty()) {
4480 deleteArtifact = actionResult.left().value().left().value();
4481 deleteArtifactResult = Either.left(deleteArtifact);
4483 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4485 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4486 return deleteArtifactResult;
4490 * deletes an artifact from a resource instance by UUID
4493 * @param componentType
4494 * @param componentUuid
4495 * @param resourceInstanceName
4496 * @param artifactUUID
4497 * @param additionalParams
4502 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4503 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4505 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4506 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4507 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4508 ArtifactDefinition deleteArtifact = null;
4509 Component component = null;
4510 String componentInstanceId = null;
4511 String componentId = null;
4512 String artifactId = null;
4513 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4514 String userId = request.getHeader(Constants.USER_ID_HEADER);
4515 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4516 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4517 if (getComponentRes.isRight()) {
4518 StorageOperationStatus status = getComponentRes.right().value();
4519 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4520 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4522 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4523 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4525 if (errorWrapper.isEmpty()) {
4526 if (component == null) {
4527 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4529 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4532 if (errorWrapper.isEmpty()) {
4533 componentInstanceId = componentRiPair.getRight().getUniqueId();
4534 componentId = componentRiPair.getLeft().getUniqueId();
4535 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4537 if (errorWrapper.isEmpty()) {
4539 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4541 if (actionResult.isRight()) {
4542 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4543 errorWrapper.setInnerElement(actionResult.right().value());
4546 if (errorWrapper.isEmpty()) {
4547 deleteArtifact = actionResult.left().value().left().value();
4548 deleteArtifactResult = Either.left(deleteArtifact);
4550 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4552 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4553 return deleteArtifactResult;
4556 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4557 String artifactId = null;
4558 ArtifactDefinition foundArtifact = null;
4559 if (instance.getDeploymentArtifacts() != null) {
4560 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4562 if (foundArtifact == null && instance.getArtifacts() != null) {
4563 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4565 if (foundArtifact == null) {
4566 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4567 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4569 artifactId = foundArtifact.getUniqueId();
4574 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4575 Map<String, String> existingEnvVersions) {
4576 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4580 @SuppressWarnings("unchecked")
4581 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4582 Map<String, String> existingEnvVersions, boolean overrideId) {
4583 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4584 if (deploymentResourceArtifacts == null) {
4585 log.debug("no deployment artifacts are configured for generated artifacts");
4586 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4588 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4589 if (placeHolderData == null) {
4590 log.debug("no env type {} are configured for generated artifacts", envType);
4591 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4594 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4595 String parentIdParam = parentId;
4597 parentIdParam = null;
4599 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4600 if (createArtifactPlaceHolder.isRight()) {
4601 return Either.right(createArtifactPlaceHolder.right().value());
4603 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4605 // fix for migration only!!!! create heat env placeholder according to heat id.
4606 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4609 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4610 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4611 artifactHeatEnv.setTimeout(0);
4612 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4613 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4614 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4615 // clone heat parameters in case of heat env only not VF heat env
4616 if (envType.equals(HEAT_ENV_NAME)) {
4617 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4619 ArtifactDefinition artifactDefinition;
4620 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4621 if (parentType != NodeTypeEnum.ResourceInstance) {
4622 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4623 if (addHeatEnvArtifact.isRight()) {
4624 log.debug("failed to create heat env artifact on resource instance");
4625 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4627 artifactDefinition = createArtifactPlaceHolder.left().value();
4629 artifactDefinition = artifactHeatEnv;
4630 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4633 if (artifact.getHeatParameters() != null) {
4634 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4635 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4636 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4637 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4638 heatEnvParameters.add(heatEnvParameter);
4640 artifactDefinition.setListHeatParameters(heatEnvParameters);
4644 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4645 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4646 ComponentTypeEnum componentType = component.getComponentType();
4647 if (parentType == NodeTypeEnum.ResourceInstance) {
4648 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4650 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4651 return Either.left(artifactDefinition);
4654 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4655 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4656 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4657 String name = heatArtifact.getArtifactName();
4660 name = heatArtifact.getArtifactLabel();
4661 fileName = name + "." + envExtension;
4663 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4665 heatEnvArtifact.setArtifactName(fileName);
4668 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4669 if (null != existingEnvVersions) {
4670 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4671 if (null != prevVersion) {
4672 heatEnvArtifact.setArtifactVersion(prevVersion);
4678 * Handles Artifacts Request For Inner Component
4680 * @param artifactsToHandle
4683 * @param vfcsNewCreatedArtifacts
4686 * @param inTransaction
4689 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4690 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4692 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4693 ComponentTypeEnum componentType = component.getComponentType();
4694 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4695 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4696 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4700 for (ArtifactDefinition artifact : artifactsToHandle) {
4701 originData = buildJsonStringForCsarVfcArtifact(artifact);
4702 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4703 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4704 if (actionResult.isRight()) {
4705 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4706 errorWrapper.setInnerElement(actionResult.right().value());
4707 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4708 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4712 uploadedArtifacts.add(actionResult.left().value().left().value());
4714 if (errorWrapper.isEmpty()) {
4715 handleArtifactsResult = Either.left(uploadedArtifacts);
4717 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4719 } catch (Exception e) {
4720 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4721 handleArtifactsResult = Either.right(responseFormat);
4722 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4724 return handleArtifactsResult;
4727 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4728 ComponentInstance componentInstance = null;
4729 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4730 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4731 if (errorWrapper.isEmpty()) {
4732 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4733 if (componentInstance == null) {
4734 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4735 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4738 return componentInstance;
4741 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4743 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4744 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4745 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4746 if (componentInstance == null) {
4747 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4748 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4750 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4752 return relatedComponentComponentInstancePair;
4755 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4756 ComponentInstance componentInstance;
4757 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4758 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4759 if (errorWrapper.isEmpty()) {
4760 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4761 if (componentInstance == null) {
4762 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4763 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4765 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4768 return relatedComponentComponentInstancePair;
4771 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4773 byte[] downloadedArtifact = null;
4774 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4775 List<ArtifactDefinition> artifactsList = null;
4776 ArtifactDefinition deploymentArtifact = null;
4777 if (artifacts != null && !artifacts.isEmpty()) {
4778 artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4780 if (artifactsList == null || artifactsList.isEmpty()) {
4781 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4782 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4784 if (errorWrapper.isEmpty()) {
4785 deploymentArtifact = artifactsList.get(0);
4786 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4787 if (downloadArtifactEither.isRight()) {
4788 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4789 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4792 if (errorWrapper.isEmpty()) {
4793 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4794 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4796 return downloadedArtifact;
4799 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4800 Component component = null;
4801 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4802 if (getComponentRes.isRight()) {
4803 StorageOperationStatus status = getComponentRes.right().value();
4804 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4805 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4807 component = getComponentRes.left().value();
4812 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4813 Component component = null;
4814 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4815 if (getComponentRes.isRight()) {
4816 StorageOperationStatus status = getComponentRes.right().value();
4817 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4818 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4820 List<Component> value = getComponentRes.left().value();
4821 if (value.isEmpty()){
4822 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4823 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4824 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4826 component = value.get(0);
4832 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4833 String artifactId = null;
4834 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4835 StorageOperationStatus storageStatus;
4836 ArtifactDefinition latestArtifact = null;
4837 List<ArtifactDefinition> artifacts = null;
4838 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4839 if (getArtifactsRes.isRight()) {
4840 storageStatus = getArtifactsRes.right().value();
4841 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4842 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4843 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4845 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4847 if (errorWrapper.isEmpty()) {
4848 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4849 if (artifacts == null || artifacts.isEmpty()) {
4850 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4851 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4854 if (errorWrapper.isEmpty()) {
4855 latestArtifact = artifacts.stream().max((a1, a2) -> {
4856 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4857 if (compareRes == 0) {
4858 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4862 if (latestArtifact == null) {
4863 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4864 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4867 if (errorWrapper.isEmpty()) {
4868 artifactId = latestArtifact.getUniqueId();
4873 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4875 Component component = null;
4876 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4877 if (getUserRes.isRight()) {
4878 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4879 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4881 if (errorWrapper.isEmpty()) {
4882 User modifier = getUserRes.left().value();
4883 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4884 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4885 if (checkoutRes.isRight()) {
4886 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4887 errorWrapper.setInnerElement(checkoutRes.right().value());
4889 component = checkoutRes.left().value();
4895 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4896 if (artifact == null) {
4897 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4898 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4899 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4900 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4903 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4904 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4905 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4909 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4910 Map<String, Object> json = new HashMap<>();
4911 String artifactName = artifact.getArtifactName();
4912 json.put(Constants.ARTIFACT_NAME, artifactName);
4913 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4914 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4915 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4916 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4917 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4918 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4919 return gson.toJson(json);