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(), Link();
196 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
197 return (operation.equals(Create) || operation.equals(Link));
202 public class ArtifactOperationInfo {
204 private ArtifactOperationEnum artifactOperationEnum;
205 private boolean isExternalApi;
206 private boolean ignoreLifecycleState;
208 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
209 this.artifactOperationEnum = artifactOperationEnum;
210 this.isExternalApi = isExternalApi;
211 this.ignoreLifecycleState = ignoreLifecycleState;
214 public boolean isExternalApi() {
215 return isExternalApi;
218 public boolean ignoreLifecycleState() {
219 return ignoreLifecycleState;
222 public ArtifactOperationEnum getArtifactOperationEnum() {
223 return artifactOperationEnum;
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) {
231 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
234 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
235 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
237 // step 1 - detect auditing type
238 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
239 // step 2 - check header
240 if (userId == null) {
241 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
242 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
243 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
244 return Either.right(responseFormat);
246 // step 3 - check user existence
247 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
248 if (userResult.isRight()) {
249 return Either.right(userResult.right().value());
252 // step 4 - check user's role
253 User user = userResult.left().value();
254 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
255 if (validateUserRole.isRight()) {
256 return Either.right(validateUserRole.right().value());
260 // 5. check service/resource existence
261 // 6. check service/resource check out
262 // 7. user is owner of checkout state
263 org.openecomp.sdc.be.model.Component component = null;
264 // ComponentInstance resourceInstance = null;
265 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
266 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
267 if (validateComponent.isRight()) {
268 return Either.right(validateComponent.right().value());
270 component = validateComponent.left().value();
271 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
272 if (validateWorkOnResource.isRight()) {
273 return Either.right(validateWorkOnResource.right().value());
276 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
277 shouldLock, inTransaction, true);
283 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
284 * For regular usage use <br>
285 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
289 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
290 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
291 Component parent = component;
292 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
294 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
295 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
297 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
298 if (errorWrapper.isEmpty()) {
300 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
302 result = Either.right(errorWrapper.getInnerElement());
307 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
308 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
309 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
310 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
311 if (validateArtifact.isRight()) {
312 ResponseFormat responseFormat = validateArtifact.right().value();
313 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
314 errorWrapper.setInnerElement(validateArtifact.right().value());
316 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
317 artifactInfo = validateArtifact.left().value();
318 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
325 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
326 Wrapper<ResponseFormat> errorWrapper) {
327 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
329 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
330 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
331 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
332 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
334 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
335 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
336 if (eitherGenerated.isRight()) {
337 errorWrapper.setInnerElement(eitherGenerated.right().value());
343 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
344 boolean needGenerate;
345 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
346 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
350 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
351 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
354 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
355 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
357 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
358 if (generated.isRight()) {
361 byte[] decodedPayload = artifactDefinition.getPayloadData();
362 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
363 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
364 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
365 shouldLock, inTransaction);
369 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
370 log.debug("tosca artifact generation");
371 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
372 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
374 if (generated.isRight()) {
375 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
377 return Either.right(generated.right().value());
379 byte[] value = generated.left().value();
380 artifactInfo.setPayload(value);
383 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
384 if (exportComponent.isRight()) {
385 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
386 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
387 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
388 return Either.right(responseFormat);
390 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
391 String payload = exportComponent.left().value().getMainYaml();
392 artifactInfo.setPayloadData(payload);
394 return Either.left(Either.left(artifactInfo));
397 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
398 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
399 if (interfaceName != null && operationName != null) {
400 interfaceName = interfaceName.toLowerCase();
401 operationName = operationName.toLowerCase();
403 switch (operation.getArtifactOperationEnum()) {
405 if (artifactGenerationRequired(parent, artifactInfo)) {
406 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
408 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
410 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
412 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
413 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
414 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
415 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
416 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
417 if (needUpdateGroup && result.isLeft()) {
418 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
419 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
420 if (error != ActionStatus.OK) {
421 result = Either.right(componentsUtils.getResponseFormat(error));
425 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
426 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
429 if (result == null) {
430 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
431 if (needUpdateGroup && result.isLeft()) {
432 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
434 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
435 if (error != ActionStatus.OK) {
436 result = Either.right(componentsUtils.getResponseFormat(error));
442 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
447 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
448 List<GroupDefinition> groups = parent.getGroups();
449 if (groups != null && !groups.isEmpty()) {
450 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
451 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
452 groupToUpdate.forEach(g -> {
453 g.getArtifacts().remove(artifactInfo.getUniqueId());
454 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
455 g.getArtifacts().add(artAfterUpdate.getUniqueId());
456 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
458 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
459 if (status.isRight()) {
460 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
461 return componentsUtils.convertFromStorageResponse(status.right().value());
465 return ActionStatus.OK;
468 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
469 List<GroupDefinition> groups = parent.getGroups();
470 if (groups != null && !groups.isEmpty()) {
471 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
472 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
473 groupToUpdate.forEach(g -> {
474 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
475 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
476 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
477 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
478 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
479 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
481 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
482 if (status.isRight()) {
483 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
484 return componentsUtils.convertFromStorageResponse(status.right().value());
488 return ActionStatus.OK;
491 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
492 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
493 List<GroupInstance> groupInstances = null;
494 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
495 if (componentInstOp.isPresent()) {
496 groupInstances = componentInstOp.get().getGroupInstances();
498 if (CollectionUtils.isNotEmpty(groupInstances)) {
499 boolean isUpdated = false;
500 for (GroupInstance groupInstance : groupInstances) {
502 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
503 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
504 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
507 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
508 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
509 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
513 updatedGroupInstances.add(groupInstance);
517 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
518 if (status.isRight()) {
519 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
520 return componentsUtils.convertFromStorageResponse(status.right().value());
522 return ActionStatus.OK;
525 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
526 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
527 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
528 result = generateToscaArtifact(parent, artifactInfo, false, false);
530 String heatArtifactId = artifactInfo.getGeneratedFromId();
531 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
532 if (heatRes.isRight()) {
533 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
534 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
535 return Either.right(responseFormat);
537 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
538 artifactInfo.setPayloadData(generatedPayload);
539 result = Either.left(Either.left(artifactInfo));
544 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
545 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
546 convertParentType(componentType);
547 String parentId = parent.getUniqueId();
548 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
549 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
551 if (origMd5 != null) {
552 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
553 if (validateMd5.isRight()) {
554 ResponseFormat responseFormat = validateMd5.right().value();
555 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
556 return Either.right(responseFormat);
559 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
561 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
562 if (payloadEither.isRight()) {
563 ResponseFormat responseFormat = payloadEither.right().value();
564 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
565 return Either.right(responseFormat);
567 } else { // duplicate
568 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
569 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
570 return Either.right(responseFormat);
576 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
577 if (lockComponent.isRight()) {
578 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
579 return Either.right(lockComponent.right().value());
582 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
584 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
589 if (resultOp == null || resultOp.isRight()) {
590 log.debug("all changes rollback");
591 if (false == inTransaction)
594 log.debug("all changes committed");
595 if (false == inTransaction)
599 componentType = parent.getComponentType();
600 NodeTypeEnum nodeType = componentType.getNodeType();
601 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
602 // graphLockOperation.unlockComponent(parentId, parentType);
611 * @param componentType
616 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
617 if (artifactGenerationRequired(component, csarArtifact)) {
618 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
620 if (generated.isRight()) {
621 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
623 return Either.right(generated.right().value());
625 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
627 return downloadArtifact(csarArtifact, component);
630 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
631 // perform all validation in common flow
632 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
633 null, parentId, containerComponentType);
634 if (result.isRight()) {
635 return Either.right(result.right().value());
637 ArtifactDefinition artifactDefinition;
638 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
639 if (insideValue.isLeft()) {
640 artifactDefinition = insideValue.left().value();
642 artifactDefinition = insideValue.right().value().getImplementationArtifact();
644 // for tosca artifacts and heat env on VF level generated on download without saving
645 if (artifactDefinition.getPayloadData() != null) {
646 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
648 return downloadArtifact(artifactDefinition, null);
651 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
653 // detect auditing type
654 Map<String, ArtifactDefinition> resMap = null;
655 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
660 if (userId == null) {
661 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
662 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
664 resultOp = Either.right(responseFormat);
668 // check user existence
672 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
673 if (userResult.isRight()) {
675 resultOp = Either.right(userResult.right().value());
679 userResult.left().value();
682 // 5. check service/resource existence
683 // 6. check service/resource check out
684 // 7. user is owner of checkout state
685 org.openecomp.sdc.be.model.Component component = null;
686 // ComponentInstance resourceInstance = null;
687 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
688 ComponentParametersView componentFilter = new ComponentParametersView();
689 componentFilter.disableAll();
690 componentFilter.setIgnoreArtifacts(false);
691 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
692 componentFilter.setIgnoreComponentInstances(false);
694 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
696 if (validateComponent.isRight()) {
697 resultOp = Either.right(validateComponent.right().value());
700 component = validateComponent.left().value();
701 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
702 if (lockComponent.isRight()) {
704 resultOp = Either.right(lockComponent.right().value());
709 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
711 if (groupType == null) {
712 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
713 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
715 resultOp = Either.right(responseFormat);
719 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
720 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
721 if (list != null && !list.isEmpty()) {
722 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
724 resMap = new HashMap<>();
726 resultOp = Either.left(resMap);
730 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
731 if (artifactsMapStatus.isRight()) {
732 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
733 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
734 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
735 resultOp = Either.right(responseFormat);
737 resMap = new HashMap<>();
738 resultOp = Either.left(resMap);
741 resMap = artifactsMapStatus.left().value();
742 resultOp = Either.left(resMap);
748 if (resultOp == null || resultOp.isRight()) {
749 log.debug("all changes rollback");
752 log.debug("all changes committed");
757 componentType = component.getComponentType();
758 NodeTypeEnum nodeType = componentType.getNodeType();
759 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
760 // graphLockOperation.unlockComponent(parentId, parentType);
765 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
766 boolean inTransaction) {
768 // check artifact existence
769 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
770 if (artifactResult.isRight()) {
771 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
772 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
773 log.debug("addArtifact - artifact {} not found", artifactId);
774 return Either.right(responseFormat);
777 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
778 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
779 return Either.right(responseFormat);
783 // check artifact belong to component
784 boolean found = false;
785 switch (componentType) {
788 found = checkArtifactInComponent(component, artifactId);
790 case RESOURCE_INSTANCE:
791 found = checkArtifactInResourceInstance(component, componentId, artifactId);
797 // String component =
798 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
800 String componentName = componentType.name().toLowerCase();
801 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
802 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
803 return Either.right(responseFormat);
805 return Either.left(artifactResult.left().value());
808 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
809 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
811 String artifactId = null;
814 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
815 if (payloadEither.isRight()) {
816 return Either.right(payloadEither.right().value());
818 byte[] decodedPayload = payloadEither.left().value();
819 convertParentType(componentType);
822 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
823 if (lockComponent.isRight()) {
824 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
825 return Either.right(lockComponent.right().value());
828 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
831 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
835 unlockComponent(resultOp, parent, inTransaction);
842 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
843 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
845 convertParentType(componentType);
849 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
851 if (lockComponent.isRight()) {
852 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
853 return Either.right(lockComponent.right().value());
857 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
859 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
864 unlockComponent(resultOp, parent, inTransaction);
869 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
870 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
872 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
874 if (payloadEither.isRight()) {
875 return Either.right(payloadEither.right().value());
877 byte[] decodedPayload = payloadEither.left().value();
879 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
882 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
883 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
885 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
886 if (validateMd5.isRight()) {
887 ResponseFormat responseFormat = validateMd5.right().value();
888 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
889 return Either.right(responseFormat);
893 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
894 if (validateResult.isRight()) {
895 ResponseFormat responseFormat = validateResult.right().value();
896 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
897 return Either.right(validateResult.right().value());
900 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
901 if (payloadEither.isRight()) {
902 ResponseFormat responseFormat = payloadEither.right().value();
903 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
904 log.debug("Error during handle payload");
905 return Either.right(responseFormat);
908 // validate heat parameters. this part must be after the parameters are
909 // extracted in "handlePayload"
910 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
911 if (validateAndConvertHeatParamers.isRight()) {
912 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
913 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
914 log.debug("Error during handle payload");
915 return Either.right(responseFormat);
917 return payloadEither;
920 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
921 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
923 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
927 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
931 user.setUserId("UNKNOWN");
933 switch (componentTypeEnum) {
936 Resource resource = (Resource) component;
937 if (resource == null) {
938 // In that case, component ID should be instead of name
939 resource = new Resource();
940 resource.setName(componentId);
942 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
946 Service service = (Service) component;
947 if (service == null) {
948 // In that case, component ID should be instead of name
949 service = new Service();
950 service.setName(componentId);
952 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
955 case RESOURCE_INSTANCE:
956 if (resourceInstanceName == null) {
957 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
959 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
960 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
968 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
969 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
970 String resourceInstanceName = null;
971 if (resourceInstance != null) {
972 resourceInstanceName = resourceInstance.getName();
974 return resourceInstanceName;
977 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
978 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
979 // Putting together artifact info
980 String artifactData = buildAuditingArtifactData(artifactDefinition);
981 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
982 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
983 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
984 return auditingFields;
989 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
990 StringBuilder sb = new StringBuilder();
991 if (artifactDefinition != null) {
992 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
993 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
996 if (artifactDefinition.getArtifactVersion() != null) {
998 sb.append(artifactDefinition.getArtifactVersion());
1003 if (artifactDefinition.getArtifactUUID() != null) {
1004 sb.append(artifactDefinition.getArtifactUUID());
1009 return sb.toString();
1012 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1014 if (origMd5 != null) {
1015 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1017 if (false == encodeBase64Str.equals(origMd5)) {
1018 log.debug("The calculated md5 is different then the received one");
1019 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1022 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1023 log.debug("Missing md5 header during artifact create");
1024 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1027 if (payload != null && payload.length != 0) {
1028 log.debug("Cannot have payload while md5 header is missing");
1029 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1032 return Either.left(true);
1035 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1036 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1038 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1039 if (artifactById.isRight()) {
1040 return Either.right(artifactById.right().value());
1042 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1044 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1045 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1046 if (validateInformationalArtifactRes.isRight()) {
1047 return Either.right(validateInformationalArtifactRes.right().value());
1049 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1050 if (validateAndSetArtifactname.isRight()) {
1051 return Either.right(validateAndSetArtifactname.right().value());
1053 if (operationName != null && interfaceName != null) {
1054 operationName = operationName.toLowerCase();
1055 interfaceName = interfaceName.toLowerCase();
1057 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
1058 if (logicalNameStatus.isRight()) {
1059 return Either.right(logicalNameStatus.right().value());
1061 // This is a patch to block possibility of updating service api fields
1062 // through other artifacts flow
1064 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1065 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1067 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1070 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1071 if (currentArtifactInfo != null) {
1072 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1075 // artifactGroupType is not allowed to be updated
1076 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1077 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1078 if (validateGroupType.isRight()) {
1079 return Either.right(validateGroupType.right().value());
1083 NodeTypeEnum parentType = convertParentType(componentType);
1086 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
1088 if (isDeploymentArtifact(artifactInfo)) {
1089 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1090 if (deploymentValidationResult.isRight()) {
1091 return Either.right(deploymentValidationResult.right().value());
1094 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1097 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1098 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1102 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1103 if (descriptionResult.isRight()) {
1104 return Either.right(descriptionResult.right().value());
1107 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1108 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1109 if (validateServiceApiType.isRight()) {
1110 return Either.right(validateServiceApiType.right().value());
1112 // Change of type is not allowed and should be ignored
1114 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1116 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1117 if (validateUrl.isRight()) {
1118 return Either.right(validateUrl.right().value());
1121 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1122 if (validateUpdate.isRight()) {
1123 log.debug("serviceApi first update cnnot be without payload.");
1124 return Either.right(validateUpdate.right().value());
1127 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1128 if (validateArtifactType.isRight()) {
1129 return Either.right(validateArtifactType.right().value());
1131 if (artifactInfo.getApiUrl() != null) {
1132 artifactInfo.setApiUrl(null);
1133 log.error("Artifact URL cannot be set through this API - ignoring");
1136 if (artifactInfo.getServiceApi() != null) {
1137 if (artifactInfo.getServiceApi()) {
1138 artifactInfo.setServiceApi(false);
1139 log.error("Artifact service API flag cannot be changed - ignoring");
1144 return Either.left(artifactInfo);
1147 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1148 if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
1149 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1150 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1151 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1155 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1157 Either<ArtifactDefinition, ResponseFormat> result = null;
1158 ArtifactDefinition foundArtifact = null;
1159 if (StringUtils.isNotEmpty(artifactId)) {
1160 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1162 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1163 log.debug("Artifact {} already exist", artifactId);
1164 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1166 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1167 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1168 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1170 if (result == null) {
1171 result = Either.left(foundArtifact);
1176 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1177 ArtifactDefinition foundArtifact;
1178 if (parentComponent.getUniqueId().equals(parentId)) {
1179 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1181 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1182 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1184 return foundArtifact;
1187 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1188 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1189 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1190 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1191 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1192 if (artifactType == null) {
1193 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1194 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1195 String artifactTypeName = artifactType.getType();
1196 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1197 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1198 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1199 if (!validArtifactTypes.contains(artifactTypeName)) {
1200 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1202 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1203 if (!validResourceType.contains(parentResourceType.name())) {
1204 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1208 return validationResult;
1211 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1212 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1213 return NodeTypeEnum.Resource;
1214 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1215 return NodeTypeEnum.ResourceInstance;
1217 return NodeTypeEnum.Service;
1221 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1222 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1224 NodeTypeEnum parentType = convertParentType(componentType);
1225 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1226 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1227 ArtifactDefinition foundArtifact = null;
1228 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1229 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1230 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1231 boolean isDuplicated = false;
1233 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1236 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1237 if (lockComponent.isRight()) {
1238 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1239 resultOp = Either.right(lockComponent.right().value());
1242 if (resultOp == null) {
1243 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1244 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1245 if (getContainerRes.isRight()) {
1246 log.debug("Failed to fetch the container component {}. ", parentId);
1247 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1248 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1249 resultOp = Either.right(responseFormat);
1252 if (resultOp == null) {
1253 fetchedContainerComponent = getContainerRes.left().value();
1254 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1255 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1256 if (getArtifactRes.isRight()) {
1257 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1258 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1259 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1260 resultOp = Either.right(responseFormat);
1262 foundArtifact = getArtifactRes.left().value().getLeft();
1263 esId = foundArtifact.getEsId();
1266 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1267 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1268 if (needCloneRes.isRight()) {
1269 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1270 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1271 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1272 resultOp = Either.right(responseFormat);
1275 if (resultOp == null) {
1276 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1277 if (updatedArtifactRes.isRight()) {
1278 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1279 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1280 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1281 resultOp = Either.right(responseFormat);
1283 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1287 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1288 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1289 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1290 if (cassandraStatus != CassandraOperationStatus.OK) {
1291 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1292 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1293 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1294 resultOp = Either.right(responseFormat);
1297 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1299 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1300 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1301 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1302 if (status.isRight()) {
1303 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1304 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1305 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1306 resultOp = Either.right(responseFormat);
1310 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1311 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1312 if (status != StorageOperationStatus.OK) {
1313 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1314 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1315 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1316 resultOp = Either.right(responseFormat);
1319 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1320 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1321 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1322 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1323 if (status.isRight()) {
1324 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1325 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1326 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1327 resultOp = Either.right(responseFormat);
1331 if (resultOp == null) {
1332 resultOp = Either.left(Either.left(foundArtifact));
1333 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1338 unlockComponent(resultOp, parent, inTransaction);
1343 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1344 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1345 boolean isUpdated = false;
1346 if (groups != null) {
1347 for (GroupDefinition group : groups) {
1349 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1350 group.getArtifacts().remove(artifactId);
1353 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1354 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1358 updatedGroups.add(group);
1362 return updatedGroups;
1365 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1366 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1367 if (CollectionUtils.isNotEmpty(groupInstances)) {
1368 boolean isUpdated = false;
1369 for (GroupInstance groupInstance : groupInstances) {
1371 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1372 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1375 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1376 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1380 updatedGroupInstances.add(groupInstance);
1384 return updatedGroupInstances;
1387 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1389 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1390 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1391 String componentId = component.getUniqueId();
1392 String instanceId = componentId.equals(parentId) ? null : parentId;
1394 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1395 resetMandatoryArtifactFields(foundArtifact);
1396 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true);
1397 } else if (cloneIsNeeded) {
1398 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1399 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1401 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1402 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1407 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1409 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1410 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1411 ComponentInstance foundInstance = null;
1412 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1413 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1414 if (!componentInstanceOpt.isPresent()) {
1415 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1417 foundInstance = componentInstanceOpt.get();
1418 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1421 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1423 if (result == null) {
1424 if (artifacts.containsKey(artifactId)) {
1425 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1427 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1433 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1434 Map<String, ArtifactDefinition> currArtifacts;
1435 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1436 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1437 if (MapUtils.isNotEmpty(currArtifacts)) {
1438 artifacts.putAll(currArtifacts);
1441 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1442 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1443 if (MapUtils.isNotEmpty(currArtifacts)) {
1444 artifacts.putAll(currArtifacts);
1447 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1448 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1449 if (MapUtils.isNotEmpty(currArtifacts)) {
1450 artifacts.putAll(currArtifacts);
1455 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1456 Map<String, ArtifactDefinition> currArtifacts;
1457 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1458 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1459 if (MapUtils.isNotEmpty(currArtifacts)) {
1460 artifacts.putAll(currArtifacts);
1463 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1464 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1465 if (MapUtils.isNotEmpty(currArtifacts)) {
1466 artifacts.putAll(currArtifacts);
1471 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1472 StorageOperationStatus result;
1473 switch (cassandraStatus) {
1475 result = StorageOperationStatus.OK;
1478 result = StorageOperationStatus.NOT_FOUND;
1480 case CLUSTER_NOT_CONNECTED:
1481 case KEYSPACE_NOT_CONNECTED:
1482 result = StorageOperationStatus.CONNECTION_FAILURE;
1485 result = StorageOperationStatus.GENERAL_ERROR;
1491 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1492 if (fetchedArtifact != null) {
1493 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1494 fetchedArtifact.setEsId(null);
1495 fetchedArtifact.setArtifactName(null);
1496 fetchedArtifact.setDescription(null);
1497 fetchedArtifact.setApiUrl(null);
1498 fetchedArtifact.setArtifactChecksum(null);
1499 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1500 fetchedArtifact.setArtifactUUID(null);
1501 long time = System.currentTimeMillis();
1502 fetchedArtifact.setPayloadUpdateDate(time);
1503 fetchedArtifact.setHeatParameters(null);
1504 fetchedArtifact.setHeatParamsUpdateDate(null);
1508 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1509 StorageOperationStatus error = StorageOperationStatus.OK;
1510 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1511 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1512 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1517 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1518 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1519 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1520 if (artifactById.isRight()) {
1521 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1522 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1523 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1524 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1525 return Either.right(responseFormat);
1527 ArtifactDefinition artifactDefinition = artifactById.left().value();
1528 if (artifactDefinition == null) {
1529 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1530 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1531 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1532 return Either.right(responseFormat);
1535 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1536 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1537 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1538 return Either.left(insideEither);
1541 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1542 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1543 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1544 // in case of update artifact must be
1545 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1546 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1547 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1549 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1550 log.debug("Artifact {} already exist", artifactId);
1551 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1553 ArtifactDefinition currentArtifactInfo = null;
1554 if (artifactById.isLeft()) {
1555 // get previous value
1556 currentArtifactInfo = artifactById.left().value();
1558 return Either.left(currentArtifactInfo);
1561 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1562 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
1564 String artifactLabel = artifactInfo.getArtifactLabel();
1565 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1566 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1567 log.debug("missing artifact logical name for component {}", componentId);
1568 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1570 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1572 if (operationName != null) {
1573 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1574 log.debug("artifact label cannot be set {}", artifactLabel);
1575 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1577 artifactLabel = operationName;
1580 String displayName = artifactInfo.getArtifactDisplayName();
1581 if (displayName == null || displayName.isEmpty())
1582 displayName = artifactLabel;
1583 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1584 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1585 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1586 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1588 artifactInfo.setArtifactDisplayName(displayName);
1590 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1591 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1592 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1594 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1596 if (artifactLabel.isEmpty()) {
1597 log.debug("missing normalized artifact logical name for component {}", componentId);
1598 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1601 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1602 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1603 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1605 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1606 log.debug("Non unique Artifact label : {}", artifactLabel);
1607 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1610 artifactInfo.setArtifactLabel(artifactLabel);
1612 return Either.left(ActionStatus.OK);
1615 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1616 boolean isUnique = true;
1617 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1618 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1619 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1621 artifacts = artifactToscaOperation.getArtifacts(componentId);
1624 if (artifacts.isLeft()) {
1625 for (String label : artifacts.left().value().keySet()) {
1626 if (label.equals(artifactLabel)) {
1632 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1633 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
1634 if (allInterfacesOfResource.isLeft()) {
1635 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1636 for (Operation operation : interace.getOperationsMap().values()) {
1637 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1648 // ***************************************************************
1650 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1651 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1653 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1654 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1655 Either<ArtifactDefinition, Operation> insideEither = null;
1656 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1657 String instanceId = null;
1658 String instanceName = null;
1659 if (foundInstance != null) {
1660 instanceId = foundInstance.getUniqueId();
1661 instanceName = foundInstance.getName();
1663 if (artifactData == null) {
1664 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1665 log.debug("Failed to create artifact object for ES.");
1666 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1667 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1668 resultOp = Either.right(responseFormat);
1672 // set on graph object id of artifact in ES!
1673 artifactInfo.setEsId(artifactData.getId());
1675 boolean isLeft = false;
1676 String artifactUniqueId = null;
1677 StorageOperationStatus error = null;
1678 if (interfaceType != null && operationName != null) {
1679 // lifecycle artifact
1680 Operation operation = convertToOperation(artifactInfo, operationName);
1682 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1684 isLeft = result.isLeft();
1686 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1687 result.left().value().getImplementation();
1689 insideEither = Either.right(result.left().value());
1690 resultOp = Either.left(insideEither);
1692 error = result.right().value();
1695 // information/deployment/api aritfacts
1696 log.trace("Try to create entry on graph");
1697 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1698 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1700 isLeft = result.isLeft();
1702 artifactUniqueId = result.left().value().getUniqueId();
1703 result.left().value();
1705 insideEither = Either.left(result.left().value());
1706 resultOp = Either.left(insideEither);
1708 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1709 if (error != StorageOperationStatus.OK) {
1714 error = result.right().value();
1718 boolean res = saveArtifacts(artifactData, parentId, false);
1719 // String uniqueId = artifactDefinition.getUniqueId();
1722 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1724 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1725 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1728 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1729 log.debug("Failed to save the artifact.");
1730 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1731 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1733 resultOp = Either.right(responseFormat);
1737 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1738 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1739 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1740 resultOp = Either.right(responseFormat);
1746 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1747 ComponentInstance foundInstance = null;
1748 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1749 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1751 return foundInstance;
1754 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1756 Either<Boolean, ResponseFormat> result = Either.left(true);
1757 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1759 validateArtifactTypeExists(responseWrapper, artifactInfo);
1761 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1763 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1765 if (responseWrapper.isEmpty()) {
1766 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1769 if (responseWrapper.isEmpty()) {
1770 // Common code for all types
1771 // not allowed to change artifactType
1773 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1774 if (validateServiceApiType.isRight()) {
1775 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1779 if (responseWrapper.isEmpty()) {
1780 if (parentType.equals(NodeTypeEnum.Resource)) {
1781 // if (parentComponent instanceof Resource) {
1782 Resource resource = (Resource) parentComponent;
1783 ResourceTypeEnum resourceType = resource.getResourceType();
1784 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1785 if (config == null) {
1786 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1788 List<String> myList = config.getValidForResourceTypes();
1789 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1790 if (either.isRight()) {
1791 responseWrapper.setInnerElement(either.right().value());
1796 if (responseWrapper.isEmpty()) {
1797 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1800 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1801 String artifactName = artifactInfo.getArtifactName();
1802 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1803 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1807 if (responseWrapper.isEmpty()) {
1808 switch (artifactType) {
1812 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1816 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1817 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1820 case DCAE_INVENTORY_TOSCA:
1821 case DCAE_INVENTORY_JSON:
1822 case DCAE_INVENTORY_POLICY:
1823 // Validation is done in handle payload.
1824 case DCAE_INVENTORY_DOC:
1825 case DCAE_INVENTORY_BLUEPRINT:
1826 case DCAE_INVENTORY_EVENT:
1827 // No specific validation
1829 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1835 if (!responseWrapper.isEmpty()) {
1836 result = Either.right(responseWrapper.getInnerElement());
1841 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1842 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1843 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1844 responseWrapper.setInnerElement(responseFormat);
1845 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1849 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1850 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1851 if (parentType.equals(NodeTypeEnum.Resource)) {
1852 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1853 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1854 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1856 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1858 return resourceDeploymentArtifacts;
1861 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1862 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1863 if (artifactType == null) {
1864 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1865 responseWrapper.setInnerElement(responseFormat);
1866 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1870 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1871 ArtifactTypeConfig retConfig = null;
1872 String fileType = artifactType.getType();
1873 if (parentType.equals(NodeTypeEnum.Resource)) {
1874 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1875 } else if (parentType.equals(NodeTypeEnum.Service)) {
1876 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1877 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1878 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1883 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1884 // extract heat parameters
1885 if (artifactInfo.getPayloadData() != null) {
1886 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1887 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1888 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1889 log.info("failed to parse heat parameters ");
1890 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1891 return Either.right(responseFormat);
1892 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1893 artifactInfo.setListHeatParameters(heatParameters.left().value());
1896 return Either.left(true);
1901 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1902 String fileType = artifactType.getType();
1903 List<String> acceptedTypes = null;
1904 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1905 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1906 log.debug("parent type of artifact can be either resource or service");
1907 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1911 if (deploymentAcceptedTypes == null) {
1912 log.debug("parent type of artifact can be either resource or service");
1913 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1916 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1919 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1921 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1922 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1923 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1924 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1927 String artifactName = artifactInfo.getArtifactName();
1928 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1929 // Pavel - File extension validation is case-insensitive - Ella,
1931 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1932 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1933 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1938 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1940 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1941 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1942 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1944 if (errorWrapper.isEmpty()) {
1945 validateValidYaml(errorWrapper, artifactInfo);
1948 if (errorWrapper.isEmpty()) {
1949 // Validate Heat Exist
1950 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1953 // if (errorWrapper.isEmpty() && isCreate) {
1954 // // Validate Only Single HeatEnv Artifact
1955 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1958 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1959 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1962 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1963 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1967 Either<Boolean, ResponseFormat> eitherResponse;
1968 if (errorWrapper.isEmpty()) {
1969 eitherResponse = Either.left(true);
1971 eitherResponse = Either.right(errorWrapper.getInnerElement());
1973 return eitherResponse;
1976 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1977 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1978 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1979 if (fillArtifactPayload.isRight()) {
1980 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1981 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1984 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1988 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1989 Either<Boolean, ResponseFormat> result = Either.left(true);
1990 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1991 if (eitherArtifactData.isLeft()) {
1992 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1993 data = Base64.encodeBase64(data);
1994 payloadWrapper.setInnerElement(data);
1996 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1997 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1998 result = Either.right(responseFormat);
2004 @SuppressWarnings("unchecked")
2005 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2006 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2007 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2008 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2009 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2011 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2012 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2013 if (eitherHeatEnvProperties.isRight()) {
2014 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2015 errorWrapper.setInnerElement(responseFormat);
2016 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2017 } else if (eitherHeatProperties.isRight()) {
2018 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2019 errorWrapper.setInnerElement(responseFormat);
2020 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2022 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2023 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2024 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2025 if (heatEnvPropertiesKeys.size() > 0) {
2026 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2027 errorWrapper.setInnerElement(responseFormat);
2032 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2033 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2034 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2036 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2037 errorWrapper.setInnerElement(responseFormat);
2038 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2042 @SuppressWarnings("restriction")
2043 public boolean isValidXml(byte[] xmlToParse) {
2044 XMLReader parser = new SAXParser();
2046 parser.setFeature("http://apache.org/xml/features/validation/schema", false);
2047 } catch (SAXNotRecognizedException e) {
2048 e.printStackTrace();
2049 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2051 } catch (SAXNotSupportedException e) {
2052 e.printStackTrace();
2053 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2056 boolean isXmlValid = true;
2058 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2059 } catch (IOException | SAXException e) {
2060 log.debug("Xml is invalid : {}", e.getMessage(), e);
2066 public boolean isValidJson(byte[] jsonToParse) {
2067 String parsed = new String(jsonToParse);
2069 gson.fromJson(parsed, Object.class);
2070 } catch (Exception e) {
2071 log.debug("Json is invalid : {}", e.getMessage(), e);
2077 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2078 boolean typeArtifactFound = false;
2079 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2080 // (parentType == NodeTypeEnum.Resource) ?
2081 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2082 // parentComponent).iterator()
2083 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2085 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2087 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2088 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2089 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2091 if (typeArtifactFound) {
2092 String parentName = parentComponent.getName();
2093 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2095 errorWrapper.setInnerElement(responseFormat);
2096 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2101 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2102 boolean artifactNameFound = false;
2103 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2104 // (parentType == NodeTypeEnum.Resource) ?
2105 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2106 // parentComponent).iterator()
2107 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2109 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2111 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2112 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2114 if (artifactNameFound) {
2115 String parentName = parentComponent.getName();
2116 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2118 errorWrapper.setInnerElement(responseFormat);
2119 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2124 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2125 ComponentTypeEnum componentType) {
2126 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2127 if (res.isRight()) {
2128 ResponseFormat responseFormat;
2129 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2130 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2132 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2134 errorWrapper.setInnerElement(responseFormat);
2138 ArtifactDefinition heatArtifact = res.left().value();
2139 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2140 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2141 // while (!heatFound && parentArtifactsItr.hasNext()) {
2142 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2143 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2144 // heatFound = true;
2145 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2146 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2148 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2149 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2153 // if (!heatFound) {
2154 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2155 // errorWrapper.setInnerElement(responseFormat);
2156 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2161 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2162 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2163 // timeout > 0 for HEAT artifacts
2164 Integer timeout = artifactInfo.getTimeout();
2165 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2166 if (timeout == null) {
2167 artifactInfo.setTimeout(defaultTimeout);
2168 // HEAT artifact but timeout is invalid
2169 } else if (timeout < 1) {
2170 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2173 // US649856 - Allow several HEAT files on Resource
2175 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2176 * Either.right(errorWrapper.getInnerElement()); } }
2179 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2180 return Either.left(true);
2183 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2184 String listToString = (typeList != null) ? typeList.toString() : "";
2185 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2186 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2187 String resourceTypeName = resourceType.name();
2188 if (typeList != null && typeList.contains(resourceTypeName)) {
2189 either = Either.left(true);
2194 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2195 if (artifactInfo.getHeatParameters() != null) {
2196 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2197 String parameterType = heatParam.getType();
2198 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2199 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2200 if (heatParameterType == null) {
2201 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2202 return Either.right(responseFormat);
2205 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2206 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2207 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2208 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2209 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2210 return Either.right(responseFormat);
2214 return Either.left(artifactInfo);
2217 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2218 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2219 if (parentComponent.getDeploymentArtifacts() != null) {
2220 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2221 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2222 if (getRI.isRight()) {
2223 return deploymentArtifacts;
2225 ComponentInstance ri = getRI.left().value();
2226 if (ri.getDeploymentArtifacts() != null) {
2227 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2229 } else if (parentComponent.getDeploymentArtifacts() != null) {
2230 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2233 return deploymentArtifacts;
2236 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2237 // on create if null add informational to current
2238 if (artifactInfo.getArtifactGroupType() == null) {
2239 artifactInfo.setArtifactGroupType(type);
2241 if (artifactInfo.getUniqueId() != null) {
2242 log.error("artifact uniqid cannot be set ignoring");
2244 artifactInfo.setUniqueId(null);
2246 if (artifactInfo.getArtifactRef() != null) {
2247 log.error("artifact ref cannot be set ignoring");
2249 artifactInfo.setArtifactRef(null);
2251 if (artifactInfo.getArtifactRepository() != null) {
2252 log.error("artifact repository cannot be set ignoring");
2254 artifactInfo.setArtifactRepository(null);
2256 if (artifactInfo.getUserIdCreator() != null) {
2257 log.error("creator uuid cannot be set ignoring");
2259 artifactInfo.setArtifactCreator(user.getUserId());
2261 if (artifactInfo.getUserIdLastUpdater() != null) {
2262 log.error("userId of last updater cannot be set ignoring");
2264 artifactInfo.setUserIdLastUpdater(user.getUserId());
2266 if (artifactInfo.getCreatorFullName() != null) {
2267 log.error("creator Full name cannot be set ignoring");
2269 String fullName = user.getFirstName() + " " + user.getLastName();
2270 artifactInfo.setUpdaterFullName(fullName);
2272 if (artifactInfo.getUpdaterFullName() != null) {
2273 log.error("updater Full name cannot be set ignoring");
2275 artifactInfo.setUpdaterFullName(fullName);
2277 if (artifactInfo.getCreationDate() != null) {
2278 log.error("Creation Date cannot be set ignoring");
2280 long time = System.currentTimeMillis();
2281 artifactInfo.setCreationDate(time);
2283 if (artifactInfo.getLastUpdateDate() != null) {
2284 log.error("Last Update Date cannot be set ignoring");
2286 artifactInfo.setLastUpdateDate(time);
2288 if (artifactInfo.getEsId() != null) {
2289 log.error("es id cannot be set ignoring");
2291 artifactInfo.setEsId(null);
2296 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2297 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2298 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2299 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2300 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2301 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2304 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2305 String id = artifactId;
2306 if (artifactId == null || artifactId.isEmpty()) {
2307 String uniqueId = null;
2308 if (interfaceName != null && operationName != null) {
2309 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2311 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2313 artifactInfo.setUniqueId(uniqueId);
2314 artifactInfo.setEsId(uniqueId);
2317 artifactInfo.setUniqueId(artifactId);
2318 artifactInfo.setEsId(artifactId);
2323 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2324 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2325 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2326 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2327 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2330 boolean artifactTypeExist = false;
2331 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2332 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2334 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2335 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2338 allArtifactTypes = elementOperation.getAllArtifactTypes();
2340 if (allArtifactTypes.isRight()) {
2341 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2342 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2343 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2346 for (ArtifactType type : allArtifactTypes.left().value()) {
2347 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2348 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2349 artifactTypeExist = true;
2354 if (!artifactTypeExist) {
2355 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2356 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2357 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2360 return Either.left(ActionStatus.OK);
2363 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2365 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2366 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2368 if (parentType.equals(NodeTypeEnum.Service)) {
2369 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2370 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2371 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2373 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2375 if (deploymentArtifacts != null) {
2376 for (String artifactType : deploymentArtifacts.keySet()) {
2377 ArtifactType artifactT = new ArtifactType();
2378 artifactT.setName(artifactType);
2379 artifactTypes.add(artifactT);
2381 return Either.left(artifactTypes);
2383 return Either.right(ActionStatus.GENERAL_ERROR);
2388 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2389 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2390 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2392 return Either.left(true);
2396 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2397 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2398 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2401 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2402 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2403 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2405 artifactInfo.setArtifactName(normalizeFileName);
2407 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2408 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2411 return Either.left(true);
2414 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2415 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2416 log.info("artifact type is missing operation ignored");
2417 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2420 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2421 log.info("artifact type cannot be changed operation ignored");
2422 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2424 return Either.left(true);
2427 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2428 if (artifactInfo.getArtifactGroupType() == null) {
2429 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2432 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2433 log.info("artifact group type cannot be changed. operation failed");
2434 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2436 return Either.left(artifactInfo);
2439 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2441 // on update if null add informational to current
2442 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2443 currentArtifact.setArtifactGroupType(type);
2446 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2447 log.error("artifact uniqid cannot be set ignoring");
2449 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2451 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2452 log.error("artifact ref cannot be set ignoring");
2454 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2456 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2457 log.error("artifact repository cannot be set ignoring");
2459 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2461 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2462 log.error("creator uuid cannot be set ignoring");
2464 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2466 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2467 log.error("artifact creator cannot be set ignoring");
2469 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2471 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2472 log.error("userId of last updater cannot be set ignoring");
2474 artifactInfo.setUserIdLastUpdater(user.getUserId());
2476 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2477 log.error("creator Full name cannot be set ignoring");
2479 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2481 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2482 log.error("updater Full name cannot be set ignoring");
2484 String fullName = user.getFirstName() + " " + user.getLastName();
2485 artifactInfo.setUpdaterFullName(fullName);
2487 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2488 log.error("Creation Date cannot be set ignoring");
2490 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2492 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2493 log.error("Last Update Date cannot be set ignoring");
2495 long time = System.currentTimeMillis();
2496 artifactInfo.setLastUpdateDate(time);
2498 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2499 log.error("es id cannot be set ignoring");
2501 artifactInfo.setEsId(currentArtifact.getUniqueId());
2503 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2504 log.error(" Artifact Display Name cannot be set ignoring");
2506 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2508 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2509 log.debug("serviceApi cannot be set. ignoring.");
2511 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2513 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2514 log.debug("artifact group cannot be set. ignoring.");
2516 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2518 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2520 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2521 log.debug("artifact UUID cannot be set. ignoring.");
2523 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2525 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2526 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2530 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2532 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2533 for (HeatParameterDefinition parameter : heatParameters) {
2534 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2536 if (currentParam != null) {
2538 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2539 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2540 parameter.setName(currentParam.getName());
2542 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2543 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2544 parameter.setDefaultValue(currentParam.getDefaultValue());
2546 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2547 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2548 parameter.setType(currentParam.getType());
2550 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2551 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2552 parameter.setDescription(currentParam.getDescription());
2555 // check and set current value
2556 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2557 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2558 parameter.setCurrentValue(currentParam.getDefaultValue());
2564 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2566 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2567 for (HeatParameterDefinition param : currentParameters) {
2568 currentParamsMap.put(param.getUniqueId(), param);
2570 return currentParamsMap;
2573 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2574 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2575 log.debug("Artifact url cannot be empty.");
2576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2578 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2580 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2581 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2583 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2584 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2587 return Either.left(true);
2590 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2591 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2592 log.debug("Artifact description cannot be empty.");
2593 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2595 String description = artifactInfo.getDescription();
2596 description = ValidationUtils.removeNoneUtf8Chars(description);
2597 description = ValidationUtils.normaliseWhitespace(description);
2598 description = ValidationUtils.stripOctets(description);
2599 description = ValidationUtils.removeHtmlTagsOnly(description);
2600 if (!ValidationUtils.validateIsEnglish(description)) {
2601 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2603 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2604 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2606 artifactInfo.setDescription(description);
2607 return Either.left(true);
2610 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2611 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2612 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2613 String prevArtifactId = null;
2614 String currArtifactId = artifactId;
2616 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2617 Either<ArtifactDefinition, Operation> insideEither = null;
2619 if (artifactData == null) {
2620 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2621 log.debug("Failed to create artifact object for ES.");
2622 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2623 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2624 resultOp = Either.right(responseFormat);
2627 log.trace("Try to update entry on graph");
2628 String artifactUniqueId = null;
2629 ArtifactDefinition artifactDefinition = artifactInfo;
2630 StorageOperationStatus error = null;
2632 boolean isLeft = false;
2633 if (interfaceType != null && operationName != null) {
2634 // lifecycle artifact
2636 * Operation operation = convertToOperation(artifactInfo, operationName);
2638 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2640 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2642 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2645 log.debug("Enty on graph is updated. Update artifact in ES");
2647 // Changing previous and current artifactId for auditing
2648 prevArtifactId = currArtifactId;
2649 currArtifactId = artifactDefinition.getUniqueId();
2651 NodeTypeEnum convertParentType = convertParentType(componentType);
2653 if (decodedPayload == null) {
2654 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2655 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2656 // Either<ESArtifactData, ResourceUploadStatus>
2657 // artifactfromES = daoUploader.getArtifact(artifactId);
2658 if (artifactFromCassandra.isRight()) {
2659 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2660 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2661 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2662 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2663 resultOp = Either.right(responseFormat);
2666 // clone data to new artifact
2667 artifactData.setData(artifactFromCassandra.left().value().getData());
2668 artifactData.setId(artifactFromCassandra.left().value().getId());
2671 if (artifactDefinition.getEsId() == null) {
2672 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2673 artifactData.setId(artifactDefinition.getUniqueId());
2677 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2678 isLeft = result.isLeft();
2680 artifactUniqueId = result.left().value().getUniqueId();
2681 artifactDefinition = result.left().value();
2682 String artifactType = artifactInfo.getArtifactType();
2683 if (NodeTypeEnum.Resource == convertParentType
2684 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2686 if (!artifactUniqueId.equals(artifactId)) {
2687 // need to update the generated id in heat env
2688 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2689 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2690 if (findFirst.isPresent()) {
2691 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2692 artifactEnvInfo.setArtifactChecksum(null);
2693 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2698 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2700 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2701 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2706 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2708 insideEither = Either.left(result.left().value());
2709 resultOp = Either.left(insideEither);
2710 if (error != StorageOperationStatus.OK) {
2715 error = result.right().value();
2719 // create new entry in ES
2721 if (artifactData.getData() != null) {
2722 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2723 artifactData.setId(artifactDefinition.getEsId());
2724 res = saveArtifacts(artifactData, parentId, false);
2730 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2731 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2732 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2733 // resultOp = Either.left(result.left().value());
2736 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2737 log.debug("Failed to save the artifact.");
2738 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2739 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2740 resultOp = Either.right(responseFormat);
2748 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2749 log.trace("Starting payload handling");
2750 byte[] payload = artifactInfo.getPayloadData();
2751 byte[] decodedPayload = null;
2753 if (payload != null && payload.length != 0) {
2754 // the generated artifacts were already decoded by the handler
2755 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2756 if (decodedPayload.length == 0) {
2757 log.debug("Failed to decode the payload.");
2758 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2759 return Either.right(responseFormat);
2762 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
2763 artifactInfo.setArtifactChecksum(checkSum);
2764 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2766 // Specific payload validations of different types
2767 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2768 if (isDeploymentArtifact(artifactInfo)) {
2769 log.trace("Starting deployment artifacts payload validation");
2770 String artifactType = artifactInfo.getArtifactType();
2771 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2772 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2773 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2774 if (isValidPayload.isLeft()) {
2775 isValidPayload = extractHeatParameters(artifactInfo);
2777 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2778 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2779 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
2780 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2782 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2784 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2785 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2786 String artifactFileName = artifactInfo.getArtifactName();
2787 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2788 switch (fileExtension) {
2790 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2793 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2797 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2802 if (isValidPayload.isRight()) {
2803 ResponseFormat responseFormat = isValidPayload.right().value();
2804 return Either.right(responseFormat);
2807 } // null/empty payload is normal if called from metadata update ONLY.
2808 // The validation of whether this is metadata/payload update case is
2809 // currently done separately
2811 if (!isArtifactMetadataUpdate) {
2812 log.debug("Payload is missing.");
2813 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2814 return Either.right(responseFormat);
2817 log.trace("Ended payload handling");
2818 return Either.left(decodedPayload);
2821 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2822 // Basic YAML validation
2823 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2824 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2825 log.debug("Invalid YAML format");
2826 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2827 return Either.right(responseFormat);
2829 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2830 // HEAT specific YAML validation
2831 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2832 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2833 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2834 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2835 return Either.right(responseFormat);
2839 return Either.left(true);
2842 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2843 Either<Boolean, ResponseFormat> res = Either.left(true);
2844 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2845 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2846 log.debug("Invalid YAML format");
2847 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2848 res = Either.right(responseFormat);
2854 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
2855 boolean isXmlValid = isValidXml(payload);
2857 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2858 log.debug("Invalid XML content");
2859 return Either.right(responseFormat);
2861 return Either.left(true);
2864 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2865 boolean isJsonValid = isValidJson(payload);
2867 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2868 log.debug("Invalid JSON content");
2869 return Either.right(responseFormat);
2871 return Either.left(true);
2874 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2875 if (opState == null || opState.isRight()) {
2876 titanDao.rollback();
2882 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2883 boolean inTransaction) {
2884 User user = new User();
2885 user.setUserId(userUserId);
2886 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2887 if (parent.isRight()) {
2888 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2889 return Either.right(responseFormat);
2891 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2892 false, inTransaction);
2893 if (handleDelete.isRight()) {
2894 return Either.right(handleDelete.right().value());
2896 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2897 return Either.left(result.right().value());
2901 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2903 if (artifacts != null && !artifacts.isEmpty()) {
2904 for (ArtifactDefinition artifactDefinition : artifacts) {
2905 String esId = artifactDefinition.getEsId();
2906 if (esId != null && !esId.isEmpty()) {
2907 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2908 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2909 return deleteIfNotOnGraph;
2914 return StorageOperationStatus.OK;
2917 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2918 Operation op = new Operation();
2919 long time = System.currentTimeMillis();
2920 op.setCreationDate(time);
2922 String artifactName = artifactInfo.getArtifactName();
2923 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2925 op.setImplementation(artifactInfo);
2926 op.setLastUpdateDate(time);
2930 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2931 String newArtifactName = operationName + "_" + artifactName;
2932 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2933 return newArtifactName;
2936 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2937 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2938 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2939 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2940 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2942 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2943 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2944 // // last one. need to delete in ES
2945 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2946 // artifactCassandraDao.deleteArtifact(artifactEsId);
2947 // return StorageOperationStatus.OK;
2949 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2953 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2954 // return StorageOperationStatus.OK;
2958 return StorageOperationStatus.OK;
2962 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2964 // General validation
2965 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2966 log.debug("One of the function parameteres is null");
2967 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2970 // Normalizing artifact name
2971 artifactName = ValidationUtils.normalizeFileName(artifactName);
2973 // Resource validation
2974 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2975 if (validateResourceNameAndVersion.isRight()) {
2976 return Either.right(validateResourceNameAndVersion.right().value());
2979 Resource resource = validateResourceNameAndVersion.left().value();
2980 String resourceId = resource.getUniqueId();
2982 // Service validation
2983 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2984 if (validateServiceNameAndVersion.isRight()) {
2985 return Either.right(validateServiceNameAndVersion.right().value());
2988 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2989 if (artifacts == null || artifacts.isEmpty()) {
2990 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2991 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2994 ArtifactDefinition deploymentArtifact = null;
2996 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2997 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2998 log.debug("Found deployment artifact {}", artifactName);
2999 deploymentArtifact = artifactDefinition;
3004 if (deploymentArtifact == null) {
3005 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3006 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3009 // Downloading the artifact
3010 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
3011 if (downloadArtifactEither.isRight()) {
3012 log.debug("Download artifact {} failed", artifactName);
3013 return Either.right(downloadArtifactEither.right().value());
3015 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3016 return Either.left(downloadArtifactEither.left().value().getRight());
3020 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3022 // General validation
3023 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3024 log.debug("One of the function parameteres is null");
3025 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3028 // Normalizing artifact name
3029 artifactName = ValidationUtils.normalizeFileName(artifactName);
3031 // Resource validation
3033 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3034 * Either.right(validateResourceNameAndVersion.right().value()); }
3036 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3039 // Service validation
3040 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3041 if (validateServiceNameAndVersion.isRight()) {
3042 return Either.right(validateServiceNameAndVersion.right().value());
3045 Service service = validateServiceNameAndVersion.left().value();
3047 // ResourceInstance validation
3048 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3049 if (validateResourceInstance.isRight()) {
3050 return Either.right(validateResourceInstance.right().value());
3053 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3055 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3057 final String finalArtifactName = artifactName;
3058 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3060 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3061 ArtifactDefinition deployableArtifact;
3063 if (!hasDeploymentArtifacts) {
3064 log.debug("Deployment artifact with name {} not found", artifactName);
3065 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3068 log.debug("Found deployment artifact {}", artifactName);
3069 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3070 // Downloading the artifact
3071 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service );
3073 if (downloadArtifactEither.isRight()) {
3074 log.debug("Download artifact {} failed", artifactName);
3075 return Either.right(downloadArtifactEither.right().value());
3077 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3078 return Either.left(downloadArtifactEither.left().value().getRight());
3081 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3083 List<ComponentInstance> riList = service.getComponentInstances();
3084 for (ComponentInstance ri : riList) {
3085 if (ri.getNormalizedName().equals(resourceInstanceName))
3086 return Either.left(ri);
3089 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3092 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3094 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3095 if (serviceListBySystemName.isRight()) {
3096 log.debug("Couldn't fetch any service with name {}", serviceName);
3097 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3099 List<Service> serviceList = serviceListBySystemName.left().value();
3100 if (serviceList == null || serviceList.isEmpty()) {
3101 log.debug("Couldn't fetch any service with name {}", serviceName);
3102 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3105 Service foundService = null;
3106 for (Service service : serviceList) {
3107 if (service.getVersion().equals(serviceVersion)) {
3108 log.trace("Found service with version {}", serviceVersion);
3109 foundService = service;
3114 if (foundService == null) {
3115 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3116 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3118 return Either.left(foundService);
3121 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3123 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3124 if (resourceListBySystemName.isRight()) {
3125 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3126 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3128 return Either.left(resourceListBySystemName.left().value());
3131 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3133 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3134 if (serviceName == null || serviceVersion == null || artifactName == null) {
3135 log.debug("One of the function parameteres is null");
3136 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3139 // Normalizing artifact name
3140 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3142 // Service validation
3143 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3144 if (validateServiceNameAndVersion.isRight()) {
3145 return Either.right(validateServiceNameAndVersion.right().value());
3148 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3150 // Looking for deployment or tosca artifacts
3151 Service service = validateServiceNameAndVersion.left().value();
3153 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3154 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3155 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3158 Optional<ArtifactDefinition> foundArtifactOptl = null;
3160 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3161 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3162 // filters artifact by name
3163 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3165 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3166 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3167 // filters TOSCA artifact by name
3168 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3170 if (!foundArtifactOptl.isPresent()) {
3171 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3172 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3174 log.debug("Found deployment artifact {}", normalizedArtifactName);
3175 // Downloading the artifact
3176 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service);
3177 if (downloadArtifactEither.isRight()) {
3178 log.debug("Download artifact {} failed", normalizedArtifactName);
3179 return Either.right(downloadArtifactEither.right().value());
3181 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3182 return Either.left(downloadArtifactEither.left().value().getRight());
3185 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3186 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3187 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3188 if (artifactById.isRight()) {
3189 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3190 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3191 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3193 ArtifactDefinition artifactDefinition = artifactById.left().value();
3194 if (artifactDefinition == null) {
3195 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3196 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3199 return downloadArtifact(artifactDefinition, null);
3202 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3203 boolean found = false;
3204 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3205 if (artifactsS != null) {
3206 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3207 if (entry.getValue().getUniqueId().equals(artifactId)) {
3213 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3214 if (!found && deploymentArtifactsS != null) {
3215 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3216 if (entry.getValue().getUniqueId().equals(artifactId)) {
3222 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3223 if (!found && toscaArtifactsS != null) {
3224 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3225 if (entry.getValue().getUniqueId().equals(artifactId)) {
3231 switch (component.getComponentType()) {
3233 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3234 if (!found && interfaces != null) {
3235 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3236 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3237 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3238 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3247 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3248 if (!found && apiArtifacts != null) {
3249 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3250 if (entry.getValue().getUniqueId().equals(artifactId)) {
3264 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3266 boolean found = false;
3267 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3268 ComponentInstance resourceInstance = null;
3269 for (ComponentInstance ri : resourceInstances) {
3270 if (ri.getUniqueId().equals(resourceInstanceId)) {
3271 resourceInstance = ri;
3275 if (resourceInstance != null) {
3276 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3277 if (artifacts != null) {
3278 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3279 if (entry.getValue().getUniqueId().equals(artifactId)) {
3286 artifacts = resourceInstance.getArtifacts();
3287 if (artifacts != null) {
3288 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3289 if (entry.getValue().getUniqueId().equals(artifactId)) {
3300 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3301 String containerComponentType, boolean inTransaction) {
3303 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3304 componentForAudit.getNodeType();
3306 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3308 if (componentResult.isRight()) {
3309 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3310 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3311 log.debug("Service not found, serviceId {}", componentId);
3312 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3313 return Either.right(responseFormat);
3315 return Either.left(componentResult.left().value());
3318 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3319 ComponentTypeEnum componentType) {
3320 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3321 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3322 if (canWork.isRight()) {
3323 String uniqueId = component.getUniqueId();
3324 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3325 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3326 return Either.right(canWork.right().value());
3329 return Either.left(true);
3332 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3334 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3335 String role = user.getRole();
3336 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3337 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3338 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3339 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3340 return Either.right(responseFormat);
3343 return Either.left(true);
3346 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3347 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3349 if (validateUserExists.isRight()) {
3350 User user = new User();
3351 user.setUserId(userId);
3352 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3353 return Either.right(validateUserExists.right().value());
3355 return Either.left(validateUserExists.left().value());
3358 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3359 AuditingActionEnum auditingAction = null;
3360 switch (operation.getArtifactOperationEnum()) {
3362 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3365 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3368 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3371 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3376 return auditingAction;
3379 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) {
3380 String esArtifactId = artifactDefinition.getEsId();
3381 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3382 if (artifactfromES.isRight()) {
3383 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3384 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3385 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3386 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3387 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName());
3388 handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null);
3390 return Either.right(responseFormat);
3393 ESArtifactData esArtifactData = artifactfromES.left().value();
3394 byte[] data = esArtifactData.getDataAsArray();
3396 log.debug("Artifact data from ES is null");
3397 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3399 String artifactName = artifactDefinition.getArtifactName();
3400 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3401 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3404 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3405 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3406 return artifactData;
3409 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3411 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3413 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3414 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3416 log.info("Failed to save artifact {}.", artifactData.getId());
3422 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3423 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3426 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3427 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3430 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3431 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3432 if (user.isRight()) {
3433 ResponseFormat responseFormat;
3434 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3435 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3436 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3438 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3439 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3441 return Either.right(responseFormat);
3444 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3445 return Either.left(artifactDefinition);
3448 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3449 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3451 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3452 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3453 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3455 artifactInfo.setArtifactDisplayName(artifactName);
3456 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3457 artifactInfo.setArtifactType(artifactType);
3458 artifactInfo.setDescription(artifactDescription);
3459 artifactInfo.setArtifactGroupType(groupType);
3460 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3462 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3464 return artifactInfo;
3467 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3468 String uniqueId = null;
3470 if (resourceId != null) {
3471 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3472 artifactInfo.setUniqueId(uniqueId);
3474 artifactInfo.setUserIdCreator(user.getUserId());
3475 String fullName = user.getFullName();
3476 artifactInfo.setUpdaterFullName(fullName);
3478 long time = System.currentTimeMillis();
3480 artifactInfo.setCreatorFullName(fullName);
3481 artifactInfo.setCreationDate(time);
3483 artifactInfo.setLastUpdateDate(time);
3484 artifactInfo.setUserIdLastUpdater(user.getUserId());
3486 artifactInfo.setMandatory(true);
3489 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3490 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3493 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3494 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3497 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3499 byte[] payload = payloadStr.getBytes();
3501 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3502 return Either.left(artifactData);
3507 * @param artifactDefinition
3510 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3511 boolean shouldLock, String instanceId) {
3512 String payload = generateHeatEnvPayload(artifactDefinition);
3513 String prevUUID = artifactDefinition.getArtifactUUID();
3514 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3515 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3516 if (generateResult.isLeft()) {
3517 ArtifactDefinition updatedArtDef = generateResult.left().value();
3518 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3519 List<ComponentInstance> componentInstances = component.getComponentInstances();
3520 if (componentInstances != null) {
3521 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3522 if (findFirst.isPresent()) {
3523 ComponentInstance relevantInst = findFirst.get();
3524 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3526 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3527 updatedGroupInstances.forEach(gi -> {
3528 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3529 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3531 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3532 if (status.isRight()) {
3533 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3534 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3535 return Either.right(responseFormat);
3543 return generateResult;
3546 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3547 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3548 StringBuilder sb = new StringBuilder();
3549 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3550 sb.append("parameters:\n");
3551 if (heatParameters != null) {
3552 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3554 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3556 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3558 String heatValue = heatParameterDefinition.getCurrentValue();
3559 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3560 heatValue = heatParameterDefinition.getDefaultValue();
3561 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3562 empltyHeatValues.add(heatParameterDefinition);
3566 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3570 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3573 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3575 case COMMA_DELIMITED_LIST:
3577 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3580 String value = heatValue;
3581 boolean starts = value.startsWith("\"");
3582 boolean ends = value.endsWith("\"");
3583 if (!(starts && ends)) {
3584 starts = value.startsWith("'");
3585 ends = value.endsWith("'");
3586 if (!(starts && ends)) {
3587 value = "\"" + value + "\"";
3590 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3597 if (!empltyHeatValues.isEmpty()) {
3598 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3599 empltyHeatValues.forEach(hv -> {
3600 sb.append(" ").append(hv.getName()).append(":");
3601 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3602 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3603 sb.append(" \"\"").append("\n");
3605 sb.append(" ").append("\n");
3610 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3613 String result = sb.toString().replaceAll("\\\\n", "\n");
3620 * @param artifactDefinition
3624 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3625 User modifier, boolean shouldLock, String instanceId) {
3626 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3627 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3631 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3632 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3634 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3635 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3637 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3638 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3639 ESArtifactData artifactData = null;
3641 if (artifactDataRes.isLeft()) {
3642 artifactData = artifactDataRes.left().value();
3644 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3645 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3646 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3648 return Either.right(artifactDataRes.right().value());
3650 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
3652 String esArtifactId = artifactDefinition.getEsId();
3653 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3654 ESArtifactData esArtifactData;
3655 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3656 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
3657 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3658 if (artifactfromES.isRight()) {
3659 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3660 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3661 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3662 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus.name(), esArtifactId);
3663 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3665 esArtifactData = artifactfromES.left().value();
3666 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
3668 oldCheckSum = artifactDefinition.getArtifactChecksum();
3671 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3674 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3675 if (lockComponent.isRight()) {
3676 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3677 return Either.right(lockComponent.right().value());
3681 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3683 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3684 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3685 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3686 if (updateArifactDefinitionStatus.isRight()) {
3687 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3688 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3689 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3690 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3692 return Either.right(responseFormat);
3696 oldCheckSum = artifactDefinition.getArtifactChecksum();
3697 artifactDefinition.setArtifactChecksum(newCheckSum);
3698 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3699 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3700 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3701 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3703 log.trace("Update Payload ", artifactDefinition.getEsId());
3705 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3707 artifactDefinition = updateArifactDefinitionStatus.left().value();
3708 artifactData.setId(artifactDefinition.getUniqueId());
3709 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3711 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3713 log.debug("Artifact Saved In ES {}", artifactData.getId());
3714 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3715 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3716 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3719 titanDao.rollback();
3720 log.info("Failed to save artifact {}.", artifactData.getId());
3721 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3722 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3723 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3725 return Either.right(responseFormat);
3728 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3729 log.debug("Failed To update artifact {}", artifactData.getId());
3730 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3731 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3733 return Either.right(responseFormat);
3738 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3743 return Either.left(artifactDefinition);
3746 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3747 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3748 convertParentType(componentType);
3749 String parentId = parent.getUniqueId();
3750 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3751 ArtifactDefinition currArtifact = artifactInfo;
3753 if (origMd5 != null) {
3754 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3755 if (validateMd5.isRight()) {
3756 ResponseFormat responseFormat = validateMd5.right().value();
3757 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3758 return Either.right(responseFormat);
3761 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3762 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3763 if (deploymentValidationResult.isRight()) {
3764 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3765 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3766 return Either.right(responseFormat);
3769 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3770 if (payloadEither.isRight()) {
3771 ResponseFormat responseFormat = payloadEither.right().value();
3772 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3773 return Either.right(responseFormat);
3775 } else { // duplicate
3776 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3777 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3778 return Either.right(responseFormat);
3784 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3785 if (lockComponent.isRight()) {
3786 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3787 return Either.right(lockComponent.right().value());
3790 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3792 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3797 if (resultOp == null || resultOp.isRight()) {
3798 log.debug("all changes rollback");
3799 if (false == inTransaction)
3800 titanDao.rollback();
3802 log.debug("all changes committed");
3803 if (false == inTransaction)
3807 componentType = parent.getComponentType();
3808 NodeTypeEnum nodeType = componentType.getNodeType();
3809 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3810 // graphLockOperation.unlockComponent(parentId, parentType);
3814 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3815 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3817 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3818 Either<ArtifactDefinition, Operation> insideEither = null;
3820 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3822 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3823 if (getRI.isRight()) {
3824 return Either.right(getRI.right().value());
3826 ComponentInstance ri = getRI.left().value();
3827 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3828 if (getArtifactRes.isRight()) {
3829 return Either.right(getArtifactRes.right().value());
3831 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3833 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3834 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3835 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3836 return Either.right(responseFormat);
3838 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3839 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3840 new ArrayList<HeatParameterDefinition>();
3843 if (origMd5 != null) {
3844 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3845 updatedHeatEnvParams, currArtifact.getArtifactName());
3846 if (uploadParamsValidationResult.isRight()) {
3847 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3848 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3849 return Either.right(responseFormat);
3851 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3854 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3855 if (validateAndConvertHeatParamers.isRight()) {
3856 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3857 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3858 return Either.right(responseFormat);
3861 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3863 // fill reduced heat env parameters List for updating
3864 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3865 paramName = heatEnvParam.getName();
3866 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3867 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3868 String updatedParamValue = heatEnvParam.getCurrentValue();
3869 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3870 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3871 } else if (updatedParamValue != null) {
3872 currHeatParam.setCurrentValue(updatedParamValue);
3877 //currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3878 currArtifact.setListHeatParameters(currentHeatEnvParams);
3880 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3881 if (updateArifactRes.isRight()) {
3882 log.debug("Failed to update artifact on graph - {}", artifactId);
3883 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3884 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3885 return Either.right(responseFormat);
3887 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3888 if (error != StorageOperationStatus.OK) {
3889 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3890 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3891 return Either.right(responseFormat);
3894 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3895 if (error != StorageOperationStatus.OK) {
3896 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3897 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3898 return Either.right(responseFormat);
3904 insideEither = Either.left(currArtifact);
3905 resultOp = Either.left(insideEither);
3906 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3907 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3911 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3912 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3914 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3915 Either<ArtifactDefinition, Operation> insideEither = null;
3917 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3919 String currentHeatId = currHeatArtifact.getUniqueId();
3921 String esArtifactId = currHeatArtifact.getEsId();
3922 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3923 if (artifactfromES.isRight()) {
3924 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3925 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3926 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3927 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3928 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3931 ESArtifactData esArtifactData = artifactfromES.left().value();
3932 byte[] data = esArtifactData.getDataAsArray();
3935 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3937 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3938 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3939 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3941 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3944 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3946 paramName = heatEnvParam.getName();
3947 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3948 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3950 String updatedParamValue = heatEnvParam.getCurrentValue();
3951 if (updatedParamValue == null)
3952 updatedParamValue = heatEnvParam.getDefaultValue();
3953 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3954 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3955 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3956 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3957 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3958 return Either.right(responseFormat);
3961 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3962 newHeatEnvParams.add(currHeatParam);
3967 if (!newHeatEnvParams.isEmpty()) {
3968 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3969 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3971 if (operationStatus.isRight()) {
3972 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3974 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3975 return Either.right(responseFormat);
3978 updatedHeatArt = operationStatus.left().value();
3980 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3981 esArtifactData.setId(updatedHeatArt.getEsId());
3982 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3985 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3986 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3987 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3988 // resultOp = Either.left(result.left().value());
3991 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3992 log.debug("Failed to save the artifact.");
3993 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3994 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3995 resultOp = Either.right(responseFormat);
3999 insideEither = Either.left(updatedHeatArt);
4002 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4003 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4004 artifactEnvInfo.setArtifactChecksum(null);
4005 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
4007 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
4010 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4011 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
4012 if (result != ActionStatus.OK) {
4013 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4014 return Either.right(responseFormat);
4018 if (updatedHeatEnvParams.isEmpty()) {
4019 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
4021 resultOp = Either.left(insideEither);
4022 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4023 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4028 private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4029 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4030 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4031 return Either.right(responseFormat);
4035 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4036 StorageOperationStatus error = StorageOperationStatus.OK;
4037 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4038 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4039 // List<GroupInstance> associatedGroups = null;
4040 List<String> groupInstancesId = null;
4041 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4042 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4044 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4045 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4046 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4052 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4053 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4055 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4056 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4057 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4058 return Either.right(responseFormat);
4061 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4062 String paramName = uploadedHeatParam.getName();
4063 boolean isExistsInHeat = false;
4064 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4065 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4067 isExistsInHeat = true;
4068 uploadedHeatParam.setType(currHeatParam.getType());
4069 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4070 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4071 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4075 if (!isExistsInHeat) {
4076 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4077 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4078 return Either.right(responseFormat);
4081 return Either.left(updatedHeatEnvParams);
4084 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4085 ResponseFormat responseFormat = null;
4086 List<ComponentInstance> ris = component.getComponentInstances();
4087 for (ComponentInstance ri : ris) {
4088 if (riID.equals(ri.getUniqueId())) {
4089 return Either.left(ri);
4092 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4093 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4094 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4095 return Either.right(responseFormat);
4098 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4099 ResponseFormat responseFormat = null;
4100 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4101 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4102 if (artifactId.equals(artifact.getUniqueId())) {
4103 return Either.left(artifact);
4106 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4107 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4108 return Either.right(responseFormat);
4111 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4112 ArtifactDefinition ret;
4113 if (eitherArtifact.isLeft()) {
4114 ret = eitherArtifact.left().value();
4116 ret = eitherArtifact.right().value().getImplementationArtifact();
4122 * downloads artifact of component by UUIDs
4124 * @param componentType
4125 * @param componentUuid
4126 * @param artifactUUID
4127 * @param auditAdditionalParam
4130 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4131 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4132 Either<byte[], ResponseFormat> result;
4133 byte[] downloadedArtifact = null;
4134 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4135 if (errorWrapper.isEmpty()) {
4136 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4137 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4139 if (errorWrapper.isEmpty()) {
4140 result = Either.left(downloadedArtifact);
4142 result = Either.right(errorWrapper.getInnerElement());
4148 * downloads an artifact of resource instance of component by UUIDs
4150 * @param componentType
4151 * @param componentUuid
4152 * @param resourceName
4153 * @param artifactUUID
4154 * @param auditAdditionalParam
4157 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4158 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4159 Either<byte[], ResponseFormat> result;
4160 byte[] downloadedArtifact = null;
4161 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4162 if (errorWrapper.isEmpty()) {
4163 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4165 if (errorWrapper.isEmpty()) {
4166 result = Either.left(downloadedArtifact);
4168 result = Either.right(errorWrapper.getInnerElement());
4174 * uploads an artifact to a component by UUID
4178 * @param componentType
4179 * @param componentUuid
4180 * @param additionalParams
4184 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4185 ArtifactOperationInfo operation) {
4186 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4187 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4188 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4189 ArtifactDefinition uploadArtifact = null;
4190 Component component = null;
4191 String componentId = null;
4192 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4193 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4194 String userId = request.getHeader(Constants.USER_ID_HEADER);
4196 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4197 if (getComponentRes.isRight()) {
4198 StorageOperationStatus status = getComponentRes.right().value();
4199 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4200 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4202 if (errorWrapper.isEmpty()) {
4203 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4204 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4206 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4207 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4208 if (component != null) {
4209 componentId = component.getUniqueId();
4210 componentName = component.getName();
4213 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4215 if (errorWrapper.isEmpty()) {
4216 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4217 if (actionResult.isRight()) {
4218 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4219 errorWrapper.setInnerElement(actionResult.right().value());
4222 if (errorWrapper.isEmpty()) {
4223 uploadArtifact = actionResult.left().value().left().value();
4224 uploadArtifactResult = Either.left(uploadArtifact);
4226 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4228 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4229 return uploadArtifactResult;
4233 * upload an artifact to a resource instance by UUID
4237 * @param componentType
4238 * @param componentUuid
4239 * @param resourceInstanceName
4240 * @param additionalParams
4244 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4245 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4246 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4247 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4248 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4249 ArtifactDefinition uploadArtifact = null;
4250 Component component = null;
4251 String componentInstanceId;
4253 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4254 String userId = request.getHeader(Constants.USER_ID_HEADER);
4256 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4257 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4258 if (getComponentRes.isRight()) {
4259 StorageOperationStatus status = getComponentRes.right().value();
4260 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4261 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4263 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4264 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4266 if (errorWrapper.isEmpty()) {
4267 if (component == null) {
4268 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4270 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4273 if (errorWrapper.isEmpty()) {
4274 componentInstanceId = componentRiPair.getRight().getUniqueId();
4275 componentId = componentRiPair.getLeft().getUniqueId();
4276 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4278 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4279 if (actionResult.isRight()) {
4280 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4281 errorWrapper.setInnerElement(actionResult.right().value());
4284 if (errorWrapper.isEmpty()) {
4285 uploadArtifact = actionResult.left().value().left().value();
4286 uploadArtifactResult = Either.left(uploadArtifact);
4288 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4290 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4291 return uploadArtifactResult;
4295 * updates an artifact on a component by UUID
4299 * @param componentType
4300 * @param componentUuid
4301 * @param artifactUUID
4302 * @param additionalParams
4307 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4308 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4309 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4310 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4311 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4312 ArtifactDefinition updateArtifact = null;
4313 Component component = null;
4314 String componentId = null;
4315 String artifactId = null;
4316 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4317 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4318 String userId = request.getHeader(Constants.USER_ID_HEADER);
4320 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4321 if (getComponentRes.isRight()) {
4322 StorageOperationStatus status = getComponentRes.right().value();
4323 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4324 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4326 if (errorWrapper.isEmpty()) {
4327 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4328 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4330 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4331 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4332 if (component != null) {
4333 componentId = component.getUniqueId();
4334 componentName = component.getName();
4337 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4339 if (errorWrapper.isEmpty()) {
4340 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4342 if (errorWrapper.isEmpty()) {
4343 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4344 if (actionResult.isRight()) {
4345 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4346 errorWrapper.setInnerElement(actionResult.right().value());
4349 if (errorWrapper.isEmpty()) {
4350 updateArtifact = actionResult.left().value().left().value();
4351 updateArtifactResult = Either.left(updateArtifact);
4354 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4356 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4357 return updateArtifactResult;
4361 * updates an artifact on a resource instance by UUID
4365 * @param componentType
4366 * @param componentUuid
4367 * @param resourceInstanceName
4368 * @param artifactUUID
4369 * @param additionalParams
4374 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4375 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4377 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4378 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4379 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4380 ArtifactDefinition updateArtifact = null;
4381 Component component = null;
4382 String componentInstanceId = null;
4383 String componentId = null;
4384 String artifactId = null;
4385 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4386 String userId = request.getHeader(Constants.USER_ID_HEADER);
4388 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4389 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4390 if (getComponentRes.isRight()) {
4391 StorageOperationStatus status = getComponentRes.right().value();
4392 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4393 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4395 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4396 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4398 if (errorWrapper.isEmpty()) {
4399 if (component == null) {
4400 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4402 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4405 if (errorWrapper.isEmpty()) {
4406 componentInstanceId = componentRiPair.getRight().getUniqueId();
4407 componentId = componentRiPair.getLeft().getUniqueId();
4408 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4410 if (errorWrapper.isEmpty()) {
4411 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4413 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4414 if (actionResult.isRight()) {
4415 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4416 errorWrapper.setInnerElement(actionResult.right().value());
4419 if (errorWrapper.isEmpty()) {
4420 updateArtifact = actionResult.left().value().left().value();
4421 updateArtifactResult = Either.left(updateArtifact);
4423 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4425 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4426 return updateArtifactResult;
4430 * deletes an artifact on a component by UUID
4433 * @param componentType
4434 * @param componentUuid
4435 * @param artifactUUID
4436 * @param additionalParams
4441 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4442 ArtifactOperationInfo operation) {
4444 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4445 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4446 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4447 ArtifactDefinition deleteArtifact = null;
4448 Component component = null;
4449 String componentId = null;
4450 String artifactId = null;
4451 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4452 String userId = request.getHeader(Constants.USER_ID_HEADER);
4454 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4455 if (getComponentRes.isRight()) {
4456 StorageOperationStatus status = getComponentRes.right().value();
4457 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4458 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4460 if (errorWrapper.isEmpty()) {
4461 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4462 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4463 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4464 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4465 if (component != null) {
4466 componentId = component.getUniqueId();
4467 componentName = component.getName();
4470 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4472 if (errorWrapper.isEmpty()) {
4473 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4475 if (errorWrapper.isEmpty()) {
4476 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4477 if (actionResult.isRight()) {
4478 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4479 errorWrapper.setInnerElement(actionResult.right().value());
4482 if (errorWrapper.isEmpty()) {
4483 deleteArtifact = actionResult.left().value().left().value();
4484 deleteArtifactResult = Either.left(deleteArtifact);
4486 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4488 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4489 return deleteArtifactResult;
4493 * deletes an artifact from a resource instance by UUID
4496 * @param componentType
4497 * @param componentUuid
4498 * @param resourceInstanceName
4499 * @param artifactUUID
4500 * @param additionalParams
4505 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4506 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4508 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4509 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4510 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4511 ArtifactDefinition deleteArtifact = null;
4512 Component component = null;
4513 String componentInstanceId = null;
4514 String componentId = null;
4515 String artifactId = null;
4516 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4517 String userId = request.getHeader(Constants.USER_ID_HEADER);
4518 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4519 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4520 if (getComponentRes.isRight()) {
4521 StorageOperationStatus status = getComponentRes.right().value();
4522 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4523 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4525 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4526 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4528 if (errorWrapper.isEmpty()) {
4529 if (component == null) {
4530 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4532 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4535 if (errorWrapper.isEmpty()) {
4536 componentInstanceId = componentRiPair.getRight().getUniqueId();
4537 componentId = componentRiPair.getLeft().getUniqueId();
4538 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4540 if (errorWrapper.isEmpty()) {
4542 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4544 if (actionResult.isRight()) {
4545 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4546 errorWrapper.setInnerElement(actionResult.right().value());
4549 if (errorWrapper.isEmpty()) {
4550 deleteArtifact = actionResult.left().value().left().value();
4551 deleteArtifactResult = Either.left(deleteArtifact);
4553 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4555 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4556 return deleteArtifactResult;
4559 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4560 String artifactId = null;
4561 ArtifactDefinition foundArtifact = null;
4562 if (instance.getDeploymentArtifacts() != null) {
4563 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4565 if (foundArtifact == null && instance.getArtifacts() != null) {
4566 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4568 if (foundArtifact == null) {
4569 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4570 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4572 artifactId = foundArtifact.getUniqueId();
4577 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4578 Map<String, String> existingEnvVersions) {
4579 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4583 @SuppressWarnings("unchecked")
4584 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4585 Map<String, String> existingEnvVersions, boolean overrideId) {
4586 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4587 if (deploymentResourceArtifacts == null) {
4588 log.debug("no deployment artifacts are configured for generated artifacts");
4589 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4591 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4592 if (placeHolderData == null) {
4593 log.debug("no env type {} are configured for generated artifacts", envType);
4594 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4597 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4598 String parentIdParam = parentId;
4600 parentIdParam = null;
4602 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4603 if (createArtifactPlaceHolder.isRight()) {
4604 return Either.right(createArtifactPlaceHolder.right().value());
4606 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4608 // fix for migration only!!!! create heat env placeholder according to heat id.
4609 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4612 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4613 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4614 artifactHeatEnv.setTimeout(0);
4615 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4616 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4617 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4618 // clone heat parameters in case of heat env only not VF heat env
4619 if (envType.equals(HEAT_ENV_NAME)) {
4620 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4622 ArtifactDefinition artifactDefinition;
4623 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4624 if (parentType != NodeTypeEnum.ResourceInstance) {
4625 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4626 if (addHeatEnvArtifact.isRight()) {
4627 log.debug("failed to create heat env artifact on resource instance");
4628 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4630 artifactDefinition = createArtifactPlaceHolder.left().value();
4632 artifactDefinition = artifactHeatEnv;
4633 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4636 if (artifact.getHeatParameters() != null) {
4637 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4638 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4639 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4640 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4641 heatEnvParameters.add(heatEnvParameter);
4643 artifactDefinition.setListHeatParameters(heatEnvParameters);
4647 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4648 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4649 ComponentTypeEnum componentType = component.getComponentType();
4650 if (parentType == NodeTypeEnum.ResourceInstance) {
4651 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4653 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4654 return Either.left(artifactDefinition);
4657 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4658 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4659 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4660 String name = heatArtifact.getArtifactName();
4663 name = heatArtifact.getArtifactLabel();
4664 fileName = name + "." + envExtension;
4666 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4668 heatEnvArtifact.setArtifactName(fileName);
4671 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4672 if (null != existingEnvVersions) {
4673 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4674 if (null != prevVersion) {
4675 heatEnvArtifact.setArtifactVersion(prevVersion);
4681 * Handles Artifacts Request For Inner Component
4683 * @param artifactsToHandle
4686 * @param vfcsNewCreatedArtifacts
4689 * @param inTransaction
4692 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4693 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4695 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4696 ComponentTypeEnum componentType = component.getComponentType();
4697 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4698 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4699 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4703 for (ArtifactDefinition artifact : artifactsToHandle) {
4704 originData = buildJsonStringForCsarVfcArtifact(artifact);
4705 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
4706 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4707 if (actionResult.isRight()) {
4708 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4709 errorWrapper.setInnerElement(actionResult.right().value());
4710 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4711 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4715 uploadedArtifacts.add(actionResult.left().value().left().value());
4717 if (errorWrapper.isEmpty()) {
4718 handleArtifactsResult = Either.left(uploadedArtifacts);
4720 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4722 } catch (Exception e) {
4723 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4724 handleArtifactsResult = Either.right(responseFormat);
4725 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4727 return handleArtifactsResult;
4730 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4731 ComponentInstance componentInstance = null;
4732 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4733 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4734 if (errorWrapper.isEmpty()) {
4735 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4736 if (componentInstance == null) {
4737 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4738 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4741 return componentInstance;
4744 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4746 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4747 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4748 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4749 if (componentInstance == null) {
4750 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4751 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4753 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4755 return relatedComponentComponentInstancePair;
4758 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4759 ComponentInstance componentInstance;
4760 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4761 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4762 if (errorWrapper.isEmpty()) {
4763 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4764 if (componentInstance == null) {
4765 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4766 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4768 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4771 return relatedComponentComponentInstancePair;
4774 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4776 byte[] downloadedArtifact = null;
4777 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4778 List<ArtifactDefinition> artifactsList = null;
4779 ArtifactDefinition deploymentArtifact = null;
4780 if (artifacts != null && !artifacts.isEmpty()) {
4781 artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4783 if (artifactsList == null || artifactsList.isEmpty()) {
4784 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4785 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4787 if (errorWrapper.isEmpty()) {
4788 deploymentArtifact = artifactsList.get(0);
4789 downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
4790 if (downloadArtifactEither.isRight()) {
4791 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4792 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4795 if (errorWrapper.isEmpty()) {
4796 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4797 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4799 return downloadedArtifact;
4802 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4803 Component component = null;
4804 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4805 if (getComponentRes.isRight()) {
4806 StorageOperationStatus status = getComponentRes.right().value();
4807 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4808 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4810 component = getComponentRes.left().value();
4815 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4816 Component component = null;
4817 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4818 if (getComponentRes.isRight()) {
4819 StorageOperationStatus status = getComponentRes.right().value();
4820 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4821 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4823 List<Component> value = getComponentRes.left().value();
4824 if (value.isEmpty()){
4825 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4826 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4827 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4829 component = value.get(0);
4835 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4836 String artifactId = null;
4837 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4838 StorageOperationStatus storageStatus;
4839 ArtifactDefinition latestArtifact = null;
4840 List<ArtifactDefinition> artifacts = null;
4841 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4842 if (getArtifactsRes.isRight()) {
4843 storageStatus = getArtifactsRes.right().value();
4844 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4845 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4846 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4848 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4850 if (errorWrapper.isEmpty()) {
4851 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4852 if (artifacts == null || artifacts.isEmpty()) {
4853 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4854 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4857 if (errorWrapper.isEmpty()) {
4858 latestArtifact = artifacts.stream().max((a1, a2) -> {
4859 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4860 if (compareRes == 0) {
4861 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4865 if (latestArtifact == null) {
4866 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4867 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4870 if (errorWrapper.isEmpty()) {
4871 artifactId = latestArtifact.getUniqueId();
4876 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4878 Component component = null;
4879 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4880 if (getUserRes.isRight()) {
4881 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4882 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4884 if (errorWrapper.isEmpty()) {
4885 User modifier = getUserRes.left().value();
4886 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4887 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4888 if (checkoutRes.isRight()) {
4889 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4890 errorWrapper.setInnerElement(checkoutRes.right().value());
4892 component = checkoutRes.left().value();
4898 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4899 if (artifact == null) {
4900 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4901 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4902 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4903 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4906 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4907 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4908 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4912 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4913 Map<String, Object> json = new HashMap<>();
4914 String artifactName = artifact.getArtifactName();
4915 json.put(Constants.ARTIFACT_NAME, artifactName);
4916 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4917 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4918 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4919 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4920 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4921 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4922 return gson.toJson(json);