2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import fj.data.Either;
27 import org.apache.commons.codec.binary.Base64;
28 import org.apache.commons.collections.CollectionUtils;
29 import org.apache.commons.collections.MapUtils;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.elasticsearch.common.Strings;
33 import org.openecomp.sdc.be.components.ArtifactsResolver;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
36 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
37 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager;
40 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
41 import org.openecomp.sdc.be.config.ConfigurationManager;
42 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
43 import org.openecomp.sdc.be.dao.api.ActionStatus;
44 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
45 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
46 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
47 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
50 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
51 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
52 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
53 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
54 import org.openecomp.sdc.be.model.ArtifactDefinition;
55 import org.openecomp.sdc.be.model.ArtifactType;
56 import org.openecomp.sdc.be.model.Component;
57 import org.openecomp.sdc.be.model.ComponentInstance;
58 import org.openecomp.sdc.be.model.ComponentParametersView;
59 import org.openecomp.sdc.be.model.GroupDefinition;
60 import org.openecomp.sdc.be.model.GroupInstance;
61 import org.openecomp.sdc.be.model.HeatParameterDefinition;
62 import org.openecomp.sdc.be.model.InterfaceDefinition;
63 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
64 import org.openecomp.sdc.be.model.LifecycleStateEnum;
65 import org.openecomp.sdc.be.model.Operation;
66 import org.openecomp.sdc.be.model.Resource;
67 import org.openecomp.sdc.be.model.Service;
68 import org.openecomp.sdc.be.model.User;
69 import org.openecomp.sdc.be.model.heat.HeatParameterType;
70 import org.openecomp.sdc.be.model.jsontitan.operations.InterfaceOperation;
71 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
72 import org.openecomp.sdc.be.model.jsontitan.utils.InterfaceUtils;
73 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
74 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
75 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
76 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
77 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
78 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
79 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
80 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
81 import org.openecomp.sdc.be.resources.data.ESArtifactData;
82 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
83 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
84 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceAuditData;
85 import org.openecomp.sdc.be.servlets.RepresentationUtils;
86 import org.openecomp.sdc.be.tosca.CsarUtils;
87 import org.openecomp.sdc.be.tosca.ToscaError;
88 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
89 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
90 import org.openecomp.sdc.be.user.IUserBusinessLogic;
91 import org.openecomp.sdc.be.user.Role;
92 import org.openecomp.sdc.be.user.UserBusinessLogic;
93 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
94 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
95 import org.openecomp.sdc.common.api.Constants;
96 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
97 import org.openecomp.sdc.common.datastructure.Wrapper;
98 import org.openecomp.sdc.common.util.GeneralUtility;
99 import org.openecomp.sdc.common.util.ValidationUtils;
100 import org.openecomp.sdc.common.util.YamlToObjectConverter;
101 import org.openecomp.sdc.exception.ResponseFormat;
102 import org.slf4j.Logger;
103 import org.slf4j.LoggerFactory;
104 import org.springframework.beans.factory.annotation.Autowired;
105 import org.xml.sax.InputSource;
106 import org.xml.sax.SAXException;
107 import org.xml.sax.SAXNotRecognizedException;
108 import org.xml.sax.SAXNotSupportedException;
109 import org.xml.sax.XMLReader;
110 import org.yaml.snakeyaml.Yaml;
112 import javax.servlet.http.HttpServletRequest;
113 import javax.xml.XMLConstants;
114 import javax.xml.parsers.ParserConfigurationException;
115 import javax.xml.parsers.SAXParserFactory;
116 import java.io.ByteArrayInputStream;
117 import java.io.IOException;
118 import java.math.BigDecimal;
119 import java.util.ArrayList;
120 import java.util.Comparator;
121 import java.util.EnumMap;
122 import java.util.HashMap;
123 import java.util.Iterator;
124 import java.util.List;
125 import java.util.Map;
126 import java.util.Map.Entry;
127 import java.util.Optional;
128 import java.util.Set;
129 import java.util.function.Predicate;
130 import java.util.function.Supplier;
131 import java.util.stream.Collectors;
133 @org.springframework.stereotype.Component("artifactBusinessLogic")
134 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
135 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
136 private static final String ARTIFACT_DESCRIPTION = "artifact description";
137 private static final String ARTIFACT_LABEL = "artifact label";
138 private static final String ARTIFACT_URL = "artifact url";
139 private static final String ARTIFACT_NAME = "artifact name";
140 private static final String ARTIFACT_PAYLOAD = "artifact payload";
142 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
143 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
144 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
146 public static final String HEAT_ENV_NAME = "heatEnv";
147 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
148 public static final String HEAT_ENV_SUFFIX = "env";
149 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
151 private static final Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class);
152 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
154 @javax.annotation.Resource
155 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
156 @javax.annotation.Resource
157 private IUserAdminOperation userOperaton;
159 @javax.annotation.Resource
160 private IElementOperation elementOperation;
162 @javax.annotation.Resource
163 private ResourceBusinessLogic resourceBusinessLogic;
165 @javax.annotation.Resource
166 private ServiceBusinessLogic serviceBusinessLogic;
168 @javax.annotation.Resource
169 private UserBusinessLogic userAdminManager;
171 @javax.annotation.Resource
172 private IHeatParametersOperation heatParametersOperation;
175 private ArtifactCassandraDao artifactCassandraDao;
178 private ToscaExportHandler toscaExportUtils;
181 private CsarUtils csarUtils;
184 private LifecycleBusinessLogic lifecycleBusinessLogic;
187 private IUserBusinessLogic userBusinessLogic;
190 private NodeTemplateOperation nodeTemplateOperation;
193 private ArtifactsResolver artifactsResolver;
196 private InterfaceOperation interfaceOperation;
198 public enum ArtifactOperationEnum {
199 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
201 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
202 return operation == CREATE || operation == LINK;
206 public class ArtifactOperationInfo {
208 private ArtifactOperationEnum artifactOperationEnum;
209 private boolean isExternalApi;
210 private boolean ignoreLifecycleState;
212 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
213 this.artifactOperationEnum = artifactOperationEnum;
214 this.isExternalApi = isExternalApi;
215 this.ignoreLifecycleState = ignoreLifecycleState;
218 public boolean isExternalApi() {
219 return isExternalApi;
222 public boolean ignoreLifecycleState() {
223 return ignoreLifecycleState;
226 public ArtifactOperationEnum getArtifactOperationEnum() {
227 return artifactOperationEnum;
233 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
234 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
235 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
238 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
239 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
241 // step 1 - detect auditing type
242 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
243 // step 2 - check header
244 if (userId == null) {
245 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
246 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
247 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
248 return Either.right(responseFormat);
250 // step 3 - check user existence
251 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
252 if (userResult.isRight()) {
253 return Either.right(userResult.right().value());
256 // step 4 - check user's role
257 User user = userResult.left().value();
258 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
259 if (validateUserRole.isRight()) {
260 return Either.right(validateUserRole.right().value());
264 // 5. check service/resource existence
265 // 6. check service/resource check out
266 // 7. user is owner of checkout state
267 org.openecomp.sdc.be.model.Component component = null;
268 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
269 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
270 if (validateComponent.isRight()) {
271 return Either.right(validateComponent.right().value());
273 component = validateComponent.left().value();
274 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
275 if (validateWorkOnResource.isRight()) {
276 return Either.right(validateWorkOnResource.right().value());
280 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
281 shouldLock, inTransaction, true);
285 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
286 * For regular usage use <br>
287 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
291 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
292 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
293 Component parent = component;
294 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
296 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
297 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
299 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
300 if (errorWrapper.isEmpty()) {
302 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
305 result = Either.right(errorWrapper.getInnerElement());
310 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
311 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
312 ArtifactDefinition validatedArtifactInfo = artifactInfo;
313 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
314 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
315 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
316 if (validateArtifact.isRight()) {
317 ResponseFormat responseFormat = validateArtifact.right().value();
318 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
319 errorWrapper.setInnerElement(validateArtifact.right().value());
321 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
322 validatedArtifactInfo = validateArtifact.left().value();
323 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
326 return validatedArtifactInfo;
329 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
330 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
331 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
333 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
334 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
335 ComponentInstance componentInstance = component.getComponentInstances()
337 .filter(p -> p.getUniqueId().equals(componentId))
340 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
342 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
344 .filter(p -> p.getUniqueId()
345 .equals(validatedArtifact.getUniqueId()))
348 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
349 .getName(), user, componentId, shouldLock, inTransaction);
350 if (eitherGenerated.isRight()) {
351 errorWrapper.setInnerElement(eitherGenerated.right().value());
356 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
357 boolean needGenerate;
358 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
359 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
360 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
361 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
362 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
366 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
367 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
369 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
372 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
373 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
375 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
376 if (generated.isRight()) {
379 byte[] decodedPayload = artifactDefinition.getPayloadData();
380 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
381 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
382 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
383 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
384 shouldLock, inTransaction);
388 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
389 log.debug("tosca artifact generation");
390 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
391 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
393 if (generated.isRight()) {
394 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
397 return Either.right(generated.right().value());
399 byte[] value = generated.left().value();
400 artifactInfo.setPayload(value);
404 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
405 if (exportComponent.isRight()) {
406 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
408 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
409 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
410 return Either.right(responseFormat);
412 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
413 String payload = exportComponent.left().value().getMainYaml();
414 artifactInfo.setPayloadData(payload);
416 return Either.left(Either.left(artifactInfo));
419 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
420 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
421 /*if (interfaceName != null && operationName != null) {
422 interfaceName = interfaceName.toLowerCase();
423 operationName = operationName.toLowerCase();
425 switch (operation.getArtifactOperationEnum()) {
427 if (artifactGenerationRequired(parent, artifactInfo)) {
428 return generateNotSavedArtifact(parent, artifactInfo);
430 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
432 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
434 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
435 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
436 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
437 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
438 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
439 if (needUpdateGroup && result.isLeft()) {
440 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
441 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
442 .value(), parent, componentType, componentId);
443 if (error != ActionStatus.OK) {
444 result = Either.right(componentsUtils.getResponseFormat(error));
449 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
450 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
453 if (result == null) {
454 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
455 if (needUpdateGroup && result.isLeft()) {
456 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
458 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
459 .value(), parent, componentType);
460 if (error != ActionStatus.OK) {
461 result = Either.right(componentsUtils.getResponseFormat(error));
467 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
469 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
474 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
475 List<GroupDefinition> groups = parent.getGroups();
476 if (groups != null && !groups.isEmpty()) {
477 List<GroupDataDefinition> groupToUpdate = groups.stream()
478 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
479 .contains(artifactInfo
481 .collect(Collectors.toList());
482 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
483 groupToUpdate.forEach(g -> {
484 g.getArtifacts().remove(artifactInfo.getUniqueId());
485 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
486 g.getArtifacts().add(artAfterUpdate.getUniqueId());
487 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
489 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
490 if (status.isRight()) {
491 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
492 return componentsUtils.convertFromStorageResponse(status.right().value());
496 return ActionStatus.OK;
499 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
500 List<GroupDefinition> groups = parent.getGroups();
501 if (groups != null && !groups.isEmpty()) {
502 List<GroupDataDefinition> groupToUpdate = groups.stream()
503 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
504 .contains(artifactInfoHeat
506 .collect(Collectors.toList());
507 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
508 groupToUpdate.forEach(g -> {
509 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
510 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
511 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
512 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
513 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
514 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
516 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
517 if (status.isRight()) {
518 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
519 return componentsUtils.convertFromStorageResponse(status.right().value());
523 return ActionStatus.OK;
526 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
527 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
528 List<GroupInstance> groupInstances = null;
529 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
531 .filter(ci -> ci.getUniqueId().equals(parentId))
533 if (componentInstOp.isPresent()) {
534 groupInstances = componentInstOp.get().getGroupInstances();
536 if (CollectionUtils.isNotEmpty(groupInstances)) {
537 boolean isUpdated = false;
538 for (GroupInstance groupInstance : groupInstances) {
540 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
541 .contains(artifactInfo
543 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
544 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
547 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
548 .contains(artifactInfo
549 .getArtifactUUID())) {
550 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
551 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
555 updatedGroupInstances.add(groupInstance);
559 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
560 if (status.isRight()) {
561 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
562 return componentsUtils.convertFromStorageResponse(status.right().value());
564 return ActionStatus.OK;
567 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
568 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
569 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
570 result = generateToscaArtifact(parent, artifactInfo, false, false);
573 String heatArtifactId = artifactInfo.getGeneratedFromId();
574 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
575 if (heatRes.isRight()) {
576 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
578 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
581 return Either.right(responseFormat);
583 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
584 artifactInfo.setPayloadData(generatedPayload);
585 result = Either.left(Either.left(artifactInfo));
590 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
591 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
592 convertParentType(componentType);
593 String parentId = parent.getUniqueId();
594 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
595 .getGeneratedFromId());
596 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
598 if (origMd5 != null) {
599 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
600 if (validateMd5.isRight()) {
601 ResponseFormat responseFormat = validateMd5.right().value();
602 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
603 return Either.right(responseFormat);
606 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
608 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
609 if (payloadEither.isRight()) {
610 ResponseFormat responseFormat = payloadEither.right().value();
611 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
612 return Either.right(responseFormat);
616 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
617 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
618 return Either.right(responseFormat);
624 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
625 if (lockComponent.isRight()) {
626 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
627 .value(), componentType, null);
628 return Either.right(lockComponent.right().value());
631 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
633 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
639 if (resultOp == null || resultOp.isRight()) {
640 log.debug("all changes rollback");
641 if (!inTransaction) {
646 log.debug("all changes committed");
647 if (!inTransaction) {
652 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
657 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
658 if (artifactGenerationRequired(component, csarArtifact)) {
659 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
661 if (generated.isRight()) {
662 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
665 return Either.right(generated.right().value());
667 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
670 return downloadArtifact(csarArtifact);
673 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
674 // perform all validation in common flow
675 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
676 null, parentId, containerComponentType);
677 if (result.isRight()) {
678 return Either.right(result.right().value());
680 ArtifactDefinition artifactDefinition;
681 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
682 if (insideValue.isLeft()) {
683 artifactDefinition = insideValue.left().value();
686 artifactDefinition = insideValue.right().value().getImplementationArtifact();
688 // for tosca artifacts and heat env on VF level generated on download without saving
689 if (artifactDefinition.getPayloadData() != null) {
690 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
693 return downloadArtifact(artifactDefinition);
696 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
698 // detect auditing type
699 Map<String, ArtifactDefinition> resMap = null;
700 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
705 if (userId == null) {
706 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
707 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
709 resultOp = Either.right(responseFormat);
713 // check user existence
717 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
718 if (userResult.isRight()) {
720 resultOp = Either.right(userResult.right().value());
724 userResult.left().value();
727 // 5. check service/resource existence
728 // 6. check service/resource check out
729 // 7. user is owner of checkout state
730 org.openecomp.sdc.be.model.Component component = null;
731 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
732 ComponentParametersView componentFilter = new ComponentParametersView();
733 componentFilter.disableAll();
734 componentFilter.setIgnoreArtifacts(false);
735 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
736 componentFilter.setIgnoreComponentInstances(false);
739 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
740 .findByParamName(containerComponentType), componentFilter);
742 if (validateComponent.isRight()) {
743 resultOp = Either.right(validateComponent.right().value());
746 component = validateComponent.left().value();
747 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
748 if (lockComponent.isRight()) {
750 resultOp = Either.right(lockComponent.right().value());
755 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
757 if (groupType == null) {
758 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
759 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
761 resultOp = Either.right(responseFormat);
765 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
766 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
767 if (list != null && !list.isEmpty()) {
768 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
771 resMap = new HashMap<>();
773 resultOp = Either.left(resMap);
778 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
779 .getNodeType(), groupType, componentId);
780 if (artifactsMapStatus.isRight()) {
781 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
782 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
783 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
784 resultOp = Either.right(responseFormat);
787 resMap = new HashMap<>();
788 resultOp = Either.left(resMap);
792 resMap = artifactsMapStatus.left().value();
793 resultOp = Either.left(resMap);
800 if (resultOp == null || resultOp.isRight()) {
801 log.debug("all changes rollback");
805 log.debug("all changes committed");
809 componentType = component.getComponentType();
810 NodeTypeEnum nodeType = componentType.getNodeType();
811 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
816 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
818 // check artifact existence
819 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
821 if (artifactResult.isRight()) {
822 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
823 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
824 log.debug("addArtifact - artifact {} not found", artifactId);
825 return Either.right(responseFormat);
829 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
832 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
834 return Either.right(responseFormat);
838 // check artifact belong to component
839 boolean found = false;
840 switch (componentType) {
843 found = checkArtifactInComponent(component, artifactId);
845 case RESOURCE_INSTANCE:
846 found = checkArtifactInResourceInstance(component, componentId, artifactId);
852 String componentName = componentType.name().toLowerCase();
853 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
854 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
855 return Either.right(responseFormat);
857 return Either.left(artifactResult.left().value());
860 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
861 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
863 String artifactId = null;
866 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
867 if (payloadEither.isRight()) {
868 return Either.right(payloadEither.right().value());
870 byte[] decodedPayload = payloadEither.left().value();
871 convertParentType(componentType);
874 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
875 if (lockComponent.isRight()) {
876 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
877 .value(), componentType, null);
878 return Either.right(lockComponent.right().value());
881 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
884 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
889 unlockComponent(resultOp, parent, inTransaction);
896 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
897 Component parent, boolean shouldLock, boolean inTransaction) {
900 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
901 if (lockComponent.isRight()) {
902 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
903 .value(), componentType, null);
904 return Either.right(lockComponent.right().value());
907 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
910 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
915 unlockComponent(resultOp, parent, inTransaction);
922 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
923 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
925 convertParentType(componentType);
929 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
931 if (lockComponent.isRight()) {
932 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
933 .value(), componentType, null);
934 return Either.right(lockComponent.right().value());
938 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
940 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
946 unlockComponent(resultOp, parent, inTransaction);
951 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
952 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
954 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
956 if (payloadEither.isRight()) {
957 return Either.right(payloadEither.right().value());
959 byte[] decodedPayload = payloadEither.left().value();
961 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
964 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
965 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
967 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
968 if (validateMd5.isRight()) {
969 ResponseFormat responseFormat = validateMd5.right().value();
970 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
971 return Either.right(responseFormat);
975 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
976 if (validateResult.isRight()) {
977 ResponseFormat responseFormat = validateResult.right().value();
978 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
979 return Either.right(validateResult.right().value());
982 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
983 if (payloadEither.isRight()) {
984 ResponseFormat responseFormat = payloadEither.right().value();
985 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
986 log.debug("Error during handle payload");
987 return Either.right(responseFormat);
990 // validate heat parameters. this part must be after the parameters are
991 // extracted in "handlePayload"
992 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
994 if (validateAndConvertHeatParamers.isRight()) {
995 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
996 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
997 log.debug("Error during handle payload");
998 return Either.right(responseFormat);
1000 return payloadEither;
1003 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1004 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1006 if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType()
1007 .equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
1010 String artifactData = buildAuditingArtifactData(artifactDefinition);
1014 user.setUserId("UNKNOWN");
1016 switch (componentTypeEnum) {
1018 Resource resource = (Resource) component;
1019 if (resource == null) {
1020 // In that case, component ID should be instead of name
1021 resource = new Resource();
1022 resource.setName(componentId);
1024 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1025 ResourceAuditData.newBuilder()
1026 .artifactUuid(prevArtifactUuid)
1027 .build(), currentArtifactUuid, artifactData);
1031 Service service = (Service) component;
1032 if (service == null) {
1033 // In that case, component ID should be instead of name
1034 service = new Service();
1035 service.setName(componentId);
1037 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, ComponentTypeEnum.SERVICE,
1038 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1039 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1040 null, null, artifactData, null);
1043 case RESOURCE_INSTANCE:
1044 if (resourceInstanceName == null) {
1045 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1047 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE,
1048 ResourceAuditData.newBuilder().artifactUuid(prevArtifactUuid).build(),
1049 ResourceAuditData.newBuilder().artifactUuid(currentArtifactUuid).build(),
1050 resourceInstanceName, null, artifactData, null);
1057 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1058 ComponentInstance resourceInstance = component.getComponentInstances()
1060 .filter(p -> p.getUniqueId().equals(componentId))
1063 String resourceInstanceName = null;
1064 if (resourceInstance != null) {
1065 resourceInstanceName = resourceInstance.getName();
1067 return resourceInstanceName;
1070 public Map<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
1071 Map<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1072 // Putting together artifact info
1073 String artifactData = buildAuditingArtifactData(artifactDefinition);
1074 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
1075 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
1076 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
1077 return auditingFields;
1082 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1083 StringBuilder sb = new StringBuilder();
1084 if (artifactDefinition != null) {
1085 sb.append(artifactDefinition.getArtifactGroupType().getType())
1088 .append(artifactDefinition.getArtifactLabel())
1091 .append(artifactDefinition.getArtifactType())
1093 .append(artifactDefinition.getArtifactName())
1095 .append(artifactDefinition.getTimeout())
1097 .append(artifactDefinition.getEsId());
1100 if (artifactDefinition.getArtifactVersion() != null) {
1102 sb.append(artifactDefinition.getArtifactVersion());
1108 if (artifactDefinition.getArtifactUUID() != null) {
1109 sb.append(artifactDefinition.getArtifactUUID());
1115 return sb.toString();
1118 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1120 if (origMd5 != null) {
1121 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1122 if (!encodeBase64Str.equals(origMd5)) {
1123 log.debug("The calculated md5 is different then the received one");
1124 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1128 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1129 log.debug("Missing md5 header during artifact create");
1130 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1133 if (payload != null && payload.length != 0) {
1134 log.debug("Cannot have payload while md5 header is missing");
1135 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1138 return Either.left(true);
1141 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1142 ComponentTypeEnum componentType, Component parentComponent) {
1144 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1145 if (artifactById.isRight()) {
1146 return Either.right(artifactById.right().value());
1148 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1150 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1151 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1152 if (validateInformationalArtifactRes.isRight()) {
1153 return Either.right(validateInformationalArtifactRes.right().value());
1155 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1156 if (validateAndSetArtifactname.isRight()) {
1157 return Either.right(validateAndSetArtifactname.right().value());
1159 if (operationName != null && interfaceName != null) {
1160 operationName = operationName.toLowerCase();
1161 interfaceName = interfaceName.toLowerCase();
1163 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1164 if (logicalNameStatus.isRight()) {
1165 return Either.right(logicalNameStatus.right().value());
1167 // This is a patch to block possibility of updating service api fields
1168 // through other artifacts flow
1170 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1171 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1172 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1175 checkCreateFields(user, artifactInfo, artifactGroupType);
1178 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1179 if (currentArtifactInfo != null) {
1180 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1183 // artifactGroupType is not allowed to be updated
1184 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1185 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1186 if (validateGroupType.isRight()) {
1187 return Either.right(validateGroupType.right().value());
1191 NodeTypeEnum parentType = convertParentType(componentType);
1194 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1196 if (isDeploymentArtifact(artifactInfo)) {
1197 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1198 if (deploymentValidationResult.isRight()) {
1199 return Either.right(deploymentValidationResult.right().value());
1203 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1206 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1207 if (descriptionResult.isRight()) {
1208 return Either.right(descriptionResult.right().value());
1211 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1212 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1213 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1214 if (validateServiceApiType.isRight()) {
1215 return Either.right(validateServiceApiType.right().value());
1217 // Change of type is not allowed and should be ignored
1219 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1221 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1222 if (validateUrl.isRight()) {
1223 return Either.right(validateUrl.right().value());
1226 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1227 if (validateUpdate.isRight()) {
1228 log.debug("serviceApi first update cnnot be without payload.");
1229 return Either.right(validateUpdate.right().value());
1233 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1234 if (validateArtifactType.isRight()) {
1235 return Either.right(validateArtifactType.right().value());
1237 if (artifactInfo.getApiUrl() != null) {
1238 artifactInfo.setApiUrl(null);
1239 log.error("Artifact URL cannot be set through this API - ignoring");
1242 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1243 artifactInfo.setServiceApi(false);
1244 log.error("Artifact service API flag cannot be changed - ignoring");
1248 return Either.left(artifactInfo);
1251 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1252 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1253 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1254 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1255 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1259 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1261 Either<ArtifactDefinition, ResponseFormat> result = null;
1262 ArtifactDefinition foundArtifact = null;
1263 if (StringUtils.isNotEmpty(artifactId)) {
1264 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1266 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1267 log.debug("Artifact {} already exist", artifactId);
1268 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1270 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1271 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1272 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1274 if (result == null) {
1275 result = Either.left(foundArtifact);
1280 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1281 ArtifactDefinition foundArtifact;
1282 if (parentComponent.getUniqueId().equals(parentId)) {
1283 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1286 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1287 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1289 return foundArtifact;
1292 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1293 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1294 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1295 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1296 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1297 if (artifactType == null) {
1298 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1299 .getArtifactType()));
1301 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1302 String artifactTypeName = artifactType.getType();
1303 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1304 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1306 .getResourceInformationalArtifacts();
1307 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1308 if (!validArtifactTypes.contains(artifactTypeName)) {
1309 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1312 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1313 .getValidForResourceTypes();
1314 if (!validResourceType.contains(parentResourceType.name())) {
1315 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1319 return validationResult;
1322 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1323 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1324 return NodeTypeEnum.Resource;
1326 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1327 return NodeTypeEnum.ResourceInstance;
1330 return NodeTypeEnum.Service;
1334 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1335 boolean shouldLock, boolean inTransaction) {
1337 NodeTypeEnum parentType = convertParentType(componentType);
1338 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1339 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1340 ArtifactDefinition foundArtifact = null;
1341 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1342 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1343 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1344 boolean isDuplicated = false;
1346 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1349 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1350 if (lockComponent.isRight()) {
1351 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1352 .value(), componentType, null);
1353 resultOp = Either.right(lockComponent.right().value());
1356 if (resultOp == null) {
1357 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1358 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1359 if (getContainerRes.isRight()) {
1360 log.debug("Failed to fetch the container component {}. ", parentId);
1361 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1363 .value()), artifactId);
1364 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1365 resultOp = Either.right(responseFormat);
1368 if (resultOp == null) {
1369 fetchedContainerComponent = getContainerRes.left().value();
1370 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1371 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1372 if (getArtifactRes.isRight()) {
1373 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1375 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1376 .value(), artifactId);
1377 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1378 resultOp = Either.right(responseFormat);
1381 foundArtifact = getArtifactRes.left().value().getLeft();
1382 esId = foundArtifact.getEsId();
1385 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1386 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1387 .getComponentType()));
1388 if (needCloneRes.isRight()) {
1389 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1390 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1392 .value()), foundArtifact.getArtifactDisplayName());
1393 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1394 resultOp = Either.right(responseFormat);
1397 boolean isNeedToDeleteArtifactFromDB = true;
1398 if (resultOp == null) {
1400 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1401 String instanceId = parentId;
1402 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1404 if (isOnlyResourceInstanceArtifact.isRight()) {
1405 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1406 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1407 .value(), foundArtifact
1408 .getArtifactDisplayName());
1409 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1410 return Either.right(responseFormat);
1412 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1415 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1418 if (updatedArtifactRes.isRight()) {
1419 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1420 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1422 .value()), foundArtifact.getArtifactDisplayName());
1423 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1424 resultOp = Either.right(responseFormat);
1427 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1431 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1432 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1433 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1434 if (cassandraStatus != CassandraOperationStatus.OK) {
1435 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1436 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1437 .getArtifactDisplayName());
1438 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1439 resultOp = Either.right(responseFormat);
1442 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1444 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1448 .getGroupInstances());
1449 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1450 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1451 if (status.isRight()) {
1452 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1453 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1455 .value()), foundArtifact.getArtifactDisplayName());
1456 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1457 resultOp = Either.right(responseFormat);
1461 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1462 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1463 if (status != StorageOperationStatus.OK) {
1464 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1465 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1466 .getArtifactDisplayName());
1467 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1468 resultOp = Either.right(responseFormat);
1471 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1472 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1474 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1475 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1476 if (status.isRight()) {
1477 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1478 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1480 .value()), foundArtifact.getArtifactDisplayName());
1481 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1482 resultOp = Either.right(responseFormat);
1486 if (resultOp == null) {
1487 resultOp = Either.left(Either.left(foundArtifact));
1488 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1494 unlockComponent(resultOp, parent, inTransaction);
1499 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1500 Either<Boolean, ActionStatus> result = Either.left(true);
1501 ComponentInstance foundInstance = null;
1502 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1504 .filter(i -> i.getUniqueId().equals(instanceId))
1506 if (!componentInstanceOpt.isPresent()) {
1507 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1510 foundInstance = componentInstanceOpt.get();
1511 String componentUid = foundInstance.getComponentUid();
1512 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1513 if (getContainerRes.isRight()) {
1514 log.debug("Failed to fetch the container component {}. ", componentUid);
1515 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1517 Component origComponent = getContainerRes.left().value();
1518 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1519 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1520 Optional<String> op = deploymentArtifacts.keySet()
1522 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1524 if (op.isPresent()) {
1525 return Either.left(false);
1528 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1529 if (artifacts != null && !artifacts.isEmpty()) {
1530 Optional<String> op = artifacts.keySet()
1532 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1534 if (op.isPresent()) {
1535 return Either.left(false);
1543 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1544 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1545 boolean isUpdated = false;
1546 if (groups != null) {
1547 for (GroupDefinition group : groups) {
1549 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1550 group.getArtifacts().remove(artifactId);
1553 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1554 .contains(foundArtifact.getArtifactUUID())) {
1555 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1559 updatedGroups.add(group);
1563 return updatedGroups;
1566 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1567 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1568 if (CollectionUtils.isNotEmpty(groupInstances)) {
1569 boolean isUpdated = false;
1570 for (GroupInstance groupInstance : groupInstances) {
1572 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1573 .contains(artifactId)) {
1574 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1577 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1578 .contains(foundArtifact
1579 .getArtifactUUID())) {
1580 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1584 updatedGroupInstances.add(groupInstance);
1588 return updatedGroupInstances;
1591 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1593 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1594 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1595 String componentId = component.getUniqueId();
1596 String instanceId = componentId.equals(parentId) ? null : parentId;
1598 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1599 resetMandatoryArtifactFields(foundArtifact);
1600 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1602 else if (cloneIsNeeded) {
1603 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1604 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1607 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1608 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1613 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1615 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1616 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1617 ComponentInstance foundInstance = null;
1618 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1619 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1621 .filter(i -> i.getUniqueId()
1624 if (!componentInstanceOpt.isPresent()) {
1625 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1628 foundInstance = componentInstanceOpt.get();
1629 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1633 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1635 if (result == null) {
1636 if (artifacts.containsKey(artifactId)) {
1637 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1640 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1646 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1647 Map<String, ArtifactDefinition> currArtifacts;
1648 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1649 currArtifacts = component.getDeploymentArtifacts()
1652 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1653 if (MapUtils.isNotEmpty(currArtifacts)) {
1654 artifacts.putAll(currArtifacts);
1657 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1658 currArtifacts = component.getArtifacts()
1661 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1662 if (MapUtils.isNotEmpty(currArtifacts)) {
1663 artifacts.putAll(currArtifacts);
1666 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1667 currArtifacts = component.getToscaArtifacts()
1670 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1671 if (MapUtils.isNotEmpty(currArtifacts)) {
1672 artifacts.putAll(currArtifacts);
1677 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1678 Map<String, ArtifactDefinition> currArtifacts;
1679 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1680 currArtifacts = instance.getDeploymentArtifacts()
1683 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1684 if (MapUtils.isNotEmpty(currArtifacts)) {
1685 artifacts.putAll(currArtifacts);
1688 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1689 currArtifacts = instance.getArtifacts()
1692 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1693 if (MapUtils.isNotEmpty(currArtifacts)) {
1694 artifacts.putAll(currArtifacts);
1699 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1700 if (fetchedArtifact != null) {
1701 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1702 fetchedArtifact.setEsId(null);
1703 fetchedArtifact.setArtifactName(null);
1704 fetchedArtifact.setDescription(null);
1705 fetchedArtifact.setApiUrl(null);
1706 fetchedArtifact.setArtifactChecksum(null);
1707 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1708 fetchedArtifact.setArtifactUUID(null);
1709 long time = System.currentTimeMillis();
1710 fetchedArtifact.setPayloadUpdateDate(time);
1711 fetchedArtifact.setHeatParameters(null);
1712 fetchedArtifact.setHeatParamsUpdateDate(null);
1716 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1717 StorageOperationStatus error = StorageOperationStatus.OK;
1718 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1719 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1720 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1725 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1727 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1729 if (artifactById.isRight()) {
1730 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1731 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1732 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1733 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1734 return Either.right(responseFormat);
1736 ArtifactDefinition artifactDefinition = artifactById.left().value();
1737 if (artifactDefinition == null) {
1738 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1739 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1740 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1741 return Either.right(responseFormat);
1744 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1745 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1746 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1747 return Either.left(insideEither);
1750 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1751 ComponentTypeEnum componentType) {
1753 String artifactLabel = artifactInfo.getArtifactLabel();
1754 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1756 BeEcompErrorManager.getInstance()
1757 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1758 log.debug("missing artifact logical name for component {}", componentId);
1759 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1761 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1763 if (operationName != null) {
1764 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1765 log.debug("artifact label cannot be set {}", artifactLabel);
1766 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1769 artifactLabel = operationName;
1772 String displayName = artifactInfo.getArtifactDisplayName();
1773 if (displayName == null || displayName.isEmpty()) {
1774 displayName = artifactLabel;
1776 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1777 artifactInfo.setArtifactDisplayName(displayName);
1779 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1780 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1781 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1783 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1785 if (artifactLabel.isEmpty()) {
1786 log.debug("missing normalized artifact logical name for component {}", componentId);
1787 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1790 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1791 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1792 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1793 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1795 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1796 log.debug("Non unique Artifact label : {}", artifactLabel);
1797 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1800 artifactInfo.setArtifactLabel(artifactLabel);
1802 return Either.left(ActionStatus.OK);
1805 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1806 boolean isUnique = true;
1807 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1808 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1809 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1812 artifacts = artifactToscaOperation.getArtifacts(componentId);
1815 if (artifacts.isLeft()) {
1816 for (String label : artifacts.left().value().keySet()) {
1817 if (label.equals(artifactLabel)) {
1823 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1824 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1825 .getAllInterfacesOfResource(componentId, true, true);
1826 if (allInterfacesOfResource.isLeft()) {
1827 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1828 for (Operation operation : interace.getOperationsMap().values()) {
1829 if (operation.getImplementation() != null && operation.getImplementation()
1831 .equals(artifactLabel)) {
1842 // ***************************************************************
1844 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1845 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1846 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1847 Either<ArtifactDefinition, Operation> insideEither = null;
1848 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1849 String instanceId = null;
1850 String instanceName = null;
1851 if (foundInstance != null) {
1852 instanceId = foundInstance.getUniqueId();
1853 instanceName = foundInstance.getName();
1855 boolean isLeft = false;
1856 String artifactUniqueId = null;
1857 StorageOperationStatus error = null;
1858 // information/deployment/api aritfacts
1859 log.trace("Try to create entry on graph");
1860 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1861 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1862 .getUniqueId(), nodeType, true, instanceId);
1864 isLeft = result.isLeft();
1866 artifactUniqueId = result.left().value().getUniqueId();
1867 result.left().value();
1869 insideEither = Either.left(result.left().value());
1870 resultOp = Either.left(insideEither);
1872 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1873 if (error != StorageOperationStatus.OK) {
1879 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1880 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1884 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1885 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1886 .getArtifactDisplayName());
1887 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1888 resultOp = Either.right(responseFormat);
1894 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1895 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1897 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1898 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1899 Either<ArtifactDefinition, Operation> insideEither = null;
1900 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1901 String instanceId = null;
1902 String instanceName = null;
1903 if (foundInstance != null) {
1904 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1905 log.debug("Failed to create artifact, already exists");
1906 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1907 .getArtifactLabel());
1908 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1910 resultOp = Either.right(responseFormat);
1914 instanceId = foundInstance.getUniqueId();
1915 instanceName = foundInstance.getName();
1917 if (artifactData == null) {
1918 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1919 log.debug("Failed to create artifact object for ES.");
1920 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1921 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1922 resultOp = Either.right(responseFormat);
1926 // set on graph object id of artifact in ES!
1927 artifactInfo.setEsId(artifactData.getId());
1929 boolean isLeft = false;
1930 String artifactUniqueId = null;
1931 StorageOperationStatus error = null;
1932 if (interfaceType != null && operationName != null) {
1933 // lifecycle artifact
1934 Operation operation = convertToOperation(artifactInfo, operationName);
1936 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1938 isLeft = result.isLeft();
1940 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1941 result.left().value().getImplementation();
1943 insideEither = Either.right(result.left().value());
1944 resultOp = Either.left(insideEither);
1947 error = result.right().value();
1951 // information/deployment/api aritfacts
1952 log.trace("Try to create entry on graph");
1953 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1954 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1955 .getUniqueId(), nodeType, true, instanceId);
1957 isLeft = result.isLeft();
1959 artifactUniqueId = result.left().value().getUniqueId();
1960 artifactData.setId(result.left().value().getEsId());
1961 insideEither = Either.left(result.left().value());
1962 resultOp = Either.left(insideEither);
1964 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1965 if (error != StorageOperationStatus.OK) {
1971 error = result.right().value();
1975 boolean res = saveArtifacts(artifactData, parentId);
1978 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1980 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1981 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1985 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1986 log.debug("Failed to save the artifact.");
1987 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1988 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1990 resultOp = Either.right(responseFormat);
1995 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1996 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1997 .getArtifactDisplayName());
1998 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1999 resultOp = Either.right(responseFormat);
2005 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2006 ComponentInstance foundInstance = null;
2007 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2008 foundInstance = containerComponent.getComponentInstances()
2010 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2014 return foundInstance;
2017 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2019 Either<Boolean, ResponseFormat> result = Either.left(true);
2020 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
2022 validateArtifactTypeExists(responseWrapper, artifactInfo);
2024 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2026 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2028 if (responseWrapper.isEmpty()) {
2029 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2032 // Common code for all types
2033 // not allowed to change artifactType
2034 if (responseWrapper.isEmpty() && !isCreate) {
2035 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2036 if (validateServiceApiType.isRight()) {
2037 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2040 if (responseWrapper.isEmpty()) {
2041 if (parentType.equals(NodeTypeEnum.Resource)) {
2042 Resource resource = (Resource) parentComponent;
2043 ResourceTypeEnum resourceType = resource.getResourceType();
2044 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2045 if (config == null) {
2046 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2047 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2048 .getArtifactType()));
2051 List<String> myList = config.getValidForResourceTypes();
2052 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2053 if (either.isRight()) {
2054 responseWrapper.setInnerElement(either.right().value());
2059 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2062 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2063 String artifactName = artifactInfo.getArtifactName();
2064 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2065 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2069 if (responseWrapper.isEmpty()) {
2070 switch (artifactType) {
2074 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2077 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2078 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2080 case DCAE_INVENTORY_TOSCA:
2081 case DCAE_INVENTORY_JSON:
2082 case DCAE_INVENTORY_POLICY:
2083 // Validation is done in handle payload.
2084 case DCAE_INVENTORY_DOC:
2085 case DCAE_INVENTORY_BLUEPRINT:
2086 case DCAE_INVENTORY_EVENT:
2087 // No specific validation
2089 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2095 if (!responseWrapper.isEmpty()) {
2096 result = Either.right(responseWrapper.getInnerElement());
2101 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2102 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2103 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2104 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2105 .getArtifactType());
2106 responseWrapper.setInnerElement(responseFormat);
2107 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2111 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2112 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2113 if (parentType.equals(NodeTypeEnum.Resource)) {
2114 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2116 .getResourceDeploymentArtifacts();
2118 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2119 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2121 .getResourceInstanceDeploymentArtifacts();
2124 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2126 .getServiceDeploymentArtifacts();
2128 return resourceDeploymentArtifacts;
2131 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2132 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2133 if (artifactType == null) {
2134 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2135 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2136 .getArtifactType());
2137 responseWrapper.setInnerElement(responseFormat);
2138 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2142 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2143 ArtifactTypeConfig retConfig = null;
2144 String fileType = artifactType.getType();
2145 if (parentType.equals(NodeTypeEnum.Resource)) {
2146 retConfig = ConfigurationManager.getConfigurationManager()
2148 .getResourceDeploymentArtifacts()
2151 else if (parentType.equals(NodeTypeEnum.Service)) {
2152 retConfig = ConfigurationManager.getConfigurationManager()
2154 .getServiceDeploymentArtifacts()
2157 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2158 retConfig = ConfigurationManager.getConfigurationManager()
2160 .getResourceInstanceDeploymentArtifacts()
2166 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2167 // extract heat parameters
2168 if (artifactInfo.getPayloadData() != null) {
2169 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2170 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2171 .getArtifactType());
2172 if (heatParameters.isRight() && (!heatParameters.right()
2174 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2175 log.info("failed to parse heat parameters ");
2176 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2177 .getArtifactType());
2178 return Either.right(responseFormat);
2180 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2181 artifactInfo.setListHeatParameters(heatParameters.left().value());
2184 return Either.left(true);
2189 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2190 String fileType = artifactType.getType();
2191 List<String> acceptedTypes = null;
2192 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2193 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2194 log.debug("parent type of artifact can be either resource or service");
2195 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2199 if (deploymentAcceptedTypes == null) {
2200 log.debug("parent type of artifact can be either resource or service");
2201 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2202 .getArtifactType()));
2206 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2209 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2212 String artifactName = artifactInfo.getArtifactName();
2213 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2214 // Pavel - File extension validation is case-insensitive - Ella,
2216 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2217 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2218 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2223 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2225 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
2226 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
2227 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2229 if (errorWrapper.isEmpty()) {
2230 validateValidYaml(errorWrapper, artifactInfo);
2233 if (errorWrapper.isEmpty()) {
2234 // Validate Heat Exist
2235 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2236 .getComponentType());
2239 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2240 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2243 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2244 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2248 Either<Boolean, ResponseFormat> eitherResponse;
2249 if (errorWrapper.isEmpty()) {
2250 eitherResponse = Either.left(true);
2253 eitherResponse = Either.right(errorWrapper.getInnerElement());
2255 return eitherResponse;
2258 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2259 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2260 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2261 if (fillArtifactPayload.isRight()) {
2262 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2263 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2267 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2271 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2272 Either<Boolean, ResponseFormat> result = Either.left(true);
2273 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2275 if (eitherArtifactData.isLeft()) {
2276 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2277 data = Base64.encodeBase64(data);
2278 payloadWrapper.setInnerElement(data);
2281 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2284 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2285 result = Either.right(responseFormat);
2291 @SuppressWarnings("unchecked")
2292 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2293 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2294 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2295 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2296 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2298 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2299 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2300 if (eitherHeatEnvProperties.isRight()) {
2301 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2302 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2303 errorWrapper.setInnerElement(responseFormat);
2304 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2306 else if (eitherHeatProperties.isRight()) {
2307 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2308 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2309 .getArtifactName(), heatArtifact.getArtifactName());
2310 errorWrapper.setInnerElement(responseFormat);
2311 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2312 .getArtifactName());
2315 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2316 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2317 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2318 if (!heatEnvPropertiesKeys.isEmpty()) {
2319 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2320 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2321 .getArtifactName(), heatArtifact.getArtifactName());
2322 errorWrapper.setInnerElement(responseFormat);
2327 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2328 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2329 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2331 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2332 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2333 .getArtifactType());
2334 errorWrapper.setInnerElement(responseFormat);
2335 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2339 private boolean isValidXml(byte[] xmlToParse) {
2340 boolean isXmlValid = true;
2342 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2343 setFeatures(reader);
2344 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2346 catch (ParserConfigurationException | IOException | SAXException e) {
2347 log.debug("Xml is invalid : {}", e.getMessage(), e);
2353 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2355 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2356 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2358 catch (SAXNotRecognizedException e) {
2359 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2363 private boolean isValidJson(byte[] jsonToParse) {
2364 String parsed = new String(jsonToParse);
2366 gson.fromJson(parsed, Object.class);
2368 catch (Exception e) {
2369 log.debug("Json is invalid : {}", e.getMessage(), e);
2375 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2376 boolean artifactNameFound = false;
2377 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2380 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2381 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2383 if (artifactNameFound) {
2384 String parentName = parentComponent.getName();
2385 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2386 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2387 .name(), parentName, artifactName);
2389 errorWrapper.setInnerElement(responseFormat);
2390 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2395 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2396 ComponentTypeEnum componentType) {
2397 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2398 if (res.isRight()) {
2399 ResponseFormat responseFormat;
2400 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2401 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2404 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2406 errorWrapper.setInnerElement(responseFormat);
2409 ArtifactDefinition heatArtifact = res.left().value();
2410 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2413 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2414 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2415 // timeout > 0 for HEAT artifacts
2416 Integer timeout = artifactInfo.getTimeout();
2417 if (timeout == null) {
2418 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2419 artifactInfo.setTimeout(defaultTimeout);
2420 // HEAT artifact but timeout is invalid
2422 else if (timeout < 1) {
2423 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2426 // US649856 - Allow several HEAT files on Resource
2427 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2428 return Either.left(true);
2431 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2432 String listToString = (typeList != null) ? typeList.toString() : "";
2433 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2434 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2435 .getArtifactName(), listToString, resourceType.getValue());
2436 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2437 String resourceTypeName = resourceType.name();
2438 if (typeList != null && typeList.contains(resourceTypeName)) {
2439 either = Either.left(true);
2444 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2445 if (artifactInfo.getHeatParameters() != null) {
2446 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2447 String parameterType = heatParam.getType();
2448 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2449 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2450 if (heatParameterType == null) {
2451 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2453 return Either.right(responseFormat);
2456 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2457 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2458 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2459 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2460 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2461 .getType(), heatParam.getName());
2462 return Either.right(responseFormat);
2466 return Either.left(artifactInfo);
2469 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2470 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2471 if (parentComponent.getDeploymentArtifacts() != null) {
2472 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2473 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2474 if (getRI.isRight()) {
2475 return deploymentArtifacts;
2477 ComponentInstance ri = getRI.left().value();
2478 if (ri.getDeploymentArtifacts() != null) {
2479 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2482 else if (parentComponent.getDeploymentArtifacts() != null) {
2483 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2486 return deploymentArtifacts;
2489 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2490 // on create if null add informational to current
2491 if (artifactInfo.getArtifactGroupType() == null) {
2492 artifactInfo.setArtifactGroupType(type);
2494 if (artifactInfo.getUniqueId() != null) {
2495 log.error("artifact uniqid cannot be set ignoring");
2497 artifactInfo.setUniqueId(null);
2499 if (artifactInfo.getArtifactRef() != null) {
2500 log.error("artifact ref cannot be set ignoring");
2502 artifactInfo.setArtifactRef(null);
2504 if (artifactInfo.getArtifactRepository() != null) {
2505 log.error("artifact repository cannot be set ignoring");
2507 artifactInfo.setArtifactRepository(null);
2509 if (artifactInfo.getUserIdCreator() != null) {
2510 log.error("creator uuid cannot be set ignoring");
2512 artifactInfo.setArtifactCreator(user.getUserId());
2514 if (artifactInfo.getUserIdLastUpdater() != null) {
2515 log.error("userId of last updater cannot be set ignoring");
2517 artifactInfo.setUserIdLastUpdater(user.getUserId());
2519 if (artifactInfo.getCreatorFullName() != null) {
2520 log.error("creator Full name cannot be set ignoring");
2522 String fullName = user.getFirstName() + " " + user.getLastName();
2523 artifactInfo.setUpdaterFullName(fullName);
2525 if (artifactInfo.getUpdaterFullName() != null) {
2526 log.error("updater Full name cannot be set ignoring");
2528 artifactInfo.setUpdaterFullName(fullName);
2530 if (artifactInfo.getCreationDate() != null) {
2531 log.error("Creation Date cannot be set ignoring");
2533 long time = System.currentTimeMillis();
2534 artifactInfo.setCreationDate(time);
2536 if (artifactInfo.getLastUpdateDate() != null) {
2537 log.error("Last Update Date cannot be set ignoring");
2539 artifactInfo.setLastUpdateDate(time);
2541 if (artifactInfo.getEsId() != null) {
2542 log.error("es id cannot be set ignoring");
2544 artifactInfo.setEsId(null);
2549 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2550 String id = artifactId;
2551 if (artifactId == null || artifactId.isEmpty()) {
2552 String uniqueId = null;
2553 if (interfaceName != null && operationName != null) {
2554 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2555 .getArtifactLabel());
2558 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2560 artifactInfo.setUniqueId(uniqueId);
2561 artifactInfo.setEsId(uniqueId);
2565 artifactInfo.setUniqueId(artifactId);
2566 artifactInfo.setEsId(artifactId);
2571 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2572 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2573 BeEcompErrorManager.getInstance()
2574 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2575 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2576 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2579 boolean artifactTypeExist = false;
2580 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2581 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2583 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2584 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2588 allArtifactTypes = elementOperation.getAllArtifactTypes();
2590 if (allArtifactTypes.isRight()) {
2591 BeEcompErrorManager.getInstance()
2592 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2596 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2598 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2601 for (ArtifactType type : allArtifactTypes.left().value()) {
2602 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2603 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2604 artifactTypeExist = true;
2609 if (!artifactTypeExist) {
2610 BeEcompErrorManager.getInstance()
2611 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2612 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2613 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2614 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2615 .getArtifactType()));
2618 return Either.left(ActionStatus.OK);
2621 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2623 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2624 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2626 if (parentType.equals(NodeTypeEnum.Service)) {
2627 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2629 .getServiceDeploymentArtifacts();
2631 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2632 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2634 .getResourceInstanceDeploymentArtifacts();
2637 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2639 .getResourceDeploymentArtifacts();
2641 if (deploymentArtifacts != null) {
2642 for (String artifactType : deploymentArtifacts.keySet()) {
2643 ArtifactType artifactT = new ArtifactType();
2644 artifactT.setName(artifactType);
2645 artifactTypes.add(artifactT);
2647 return Either.left(artifactTypes);
2650 return Either.right(ActionStatus.GENERAL_ERROR);
2655 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2656 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2657 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2659 return Either.left(true);
2663 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2664 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2665 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2668 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2669 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2670 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2672 artifactInfo.setArtifactName(normalizeFileName);
2674 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2675 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2678 return Either.left(true);
2681 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2682 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2683 log.info("artifact type is missing operation ignored");
2684 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2687 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2688 log.info("artifact type cannot be changed operation ignored");
2689 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2691 return Either.left(true);
2694 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2695 if (artifactInfo.getArtifactGroupType() == null) {
2696 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2699 else if (!currentArtifact.getArtifactGroupType()
2701 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2702 log.info("artifact group type cannot be changed. operation failed");
2703 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2705 return Either.left(artifactInfo);
2708 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2710 // on update if null add informational to current
2711 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2712 currentArtifact.setArtifactGroupType(type);
2715 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2716 log.error("artifact uniqid cannot be set ignoring");
2718 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2720 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2721 .equals(artifactInfo.getArtifactRef())) {
2722 log.error("artifact ref cannot be set ignoring");
2724 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2726 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2727 .equals(artifactInfo.getArtifactRepository())) {
2728 log.error("artifact repository cannot be set ignoring");
2730 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2732 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2733 .equals(artifactInfo.getUserIdCreator())) {
2734 log.error("creator uuid cannot be set ignoring");
2736 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2738 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2739 .equals(artifactInfo.getArtifactCreator())) {
2740 log.error("artifact creator cannot be set ignoring");
2742 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2744 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2745 .equals(artifactInfo.getUserIdLastUpdater())) {
2746 log.error("userId of last updater cannot be set ignoring");
2748 artifactInfo.setUserIdLastUpdater(user.getUserId());
2750 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2751 .equals(artifactInfo.getCreatorFullName())) {
2752 log.error("creator Full name cannot be set ignoring");
2754 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2756 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2757 .equals(artifactInfo.getUpdaterFullName())) {
2758 log.error("updater Full name cannot be set ignoring");
2760 String fullName = user.getFirstName() + " " + user.getLastName();
2761 artifactInfo.setUpdaterFullName(fullName);
2763 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2764 .equals(artifactInfo.getCreationDate())) {
2765 log.error("Creation Date cannot be set ignoring");
2767 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2769 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2770 .equals(artifactInfo.getLastUpdateDate())) {
2771 log.error("Last Update Date cannot be set ignoring");
2773 long time = System.currentTimeMillis();
2774 artifactInfo.setLastUpdateDate(time);
2776 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2777 log.error("es id cannot be set ignoring");
2779 artifactInfo.setEsId(currentArtifact.getUniqueId());
2781 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2782 .equals(artifactInfo.getArtifactDisplayName())) {
2783 log.error(" Artifact Display Name cannot be set ignoring");
2785 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2787 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2788 .equals(artifactInfo.getServiceApi())) {
2789 log.debug("serviceApi cannot be set. ignoring.");
2791 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2793 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2794 .equals(artifactInfo.getArtifactGroupType())) {
2795 log.debug("artifact group cannot be set. ignoring.");
2797 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2799 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2801 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2802 .isEmpty() && !currentArtifact.getArtifactUUID()
2803 .equals(artifactInfo.getArtifactUUID())) {
2804 log.debug("artifact UUID cannot be set. ignoring.");
2806 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2808 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2809 .getHeatParameters()
2810 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2811 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2815 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2817 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2818 for (HeatParameterDefinition parameter : heatParameters) {
2819 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2821 if (currentParam != null) {
2823 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2824 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2825 parameter.setName(currentParam.getName());
2827 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2828 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2829 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2830 parameter.setDefaultValue(currentParam.getDefaultValue());
2832 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2833 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2834 parameter.setType(currentParam.getType());
2836 if (parameter.getDescription() != null && !parameter.getDescription()
2837 .equalsIgnoreCase(currentParam.getDescription())) {
2838 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2839 parameter.setDescription(currentParam.getDescription());
2842 // check and set current value
2843 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2844 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2845 parameter.setCurrentValue(currentParam.getDefaultValue());
2851 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2853 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2854 for (HeatParameterDefinition param : currentParameters) {
2855 currentParamsMap.put(param.getUniqueId(), param);
2857 return currentParamsMap;
2860 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2861 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2862 log.debug("Artifact url cannot be empty.");
2863 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2865 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2867 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2868 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2870 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2871 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2874 return Either.left(true);
2877 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2878 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2879 log.debug("Artifact description cannot be empty.");
2880 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2882 String description = artifactInfo.getDescription();
2883 description = ValidationUtils.removeNoneUtf8Chars(description);
2884 description = ValidationUtils.normaliseWhitespace(description);
2885 description = ValidationUtils.stripOctets(description);
2886 description = ValidationUtils.removeHtmlTagsOnly(description);
2887 if (!ValidationUtils.validateIsEnglish(description)) {
2888 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2890 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2891 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2892 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2894 artifactInfo.setDescription(description);
2895 return Either.left(true);
2898 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2899 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2900 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2901 String prevArtifactId = null;
2902 String currArtifactId = artifactId;
2904 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2905 Either<ArtifactDefinition, Operation> insideEither = null;
2907 log.trace("Try to update entry on graph");
2908 String artifactUniqueId = null;
2909 ArtifactDefinition artifactDefinition = artifactInfo;
2910 StorageOperationStatus error;
2913 if (interfaceType == null || operationUuid == null) {
2914 log.debug("Entity on graph is updated. Update artifact in ES");
2916 // Changing previous and current artifactId for auditing
2917 prevArtifactId = currArtifactId;
2918 currArtifactId = artifactDefinition.getUniqueId();
2921 if (decodedPayload == null) {
2922 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2923 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2925 if (artifactFromCassandra.isRight()) {
2926 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2927 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2929 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2930 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2931 resultOp = Either.right(responseFormat);
2934 // clone data to new artifact
2935 artifactData.setData(artifactFromCassandra.left().value().getData());
2936 artifactData.setId(artifactFromCassandra.left().value().getId());
2939 if (artifactDefinition.getEsId() == null) {
2940 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2941 artifactData.setId(artifactDefinition.getUniqueId());
2945 NodeTypeEnum convertParentType = convertParentType(componentType);
2946 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
2947 .getUniqueId(), artifactId, convertParentType, parentId);
2948 isLeft = result.isLeft();
2950 artifactUniqueId = result.left().value().getUniqueId();
2951 artifactDefinition = result.left().value();
2952 String artifactType = artifactInfo.getArtifactType();
2953 if (NodeTypeEnum.Resource == convertParentType
2954 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
2955 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
2956 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
2957 && !artifactUniqueId.equals(artifactId)) {
2958 // need to update the generated id in heat env
2959 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2960 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
2962 .filter(a -> a.getValue()
2963 .getGeneratedFromId() != null && a
2965 .getGeneratedFromId()
2966 .equals(artifactId))
2968 if (findFirst.isPresent()) {
2969 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2970 artifactEnvInfo.setArtifactChecksum(null);
2971 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2974 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2976 insideEither = Either.left(result.left().value());
2977 resultOp = Either.left(insideEither);
2978 if (error != StorageOperationStatus.OK) {
2983 error = result.right().value();
2987 // create new entry in ES
2989 if (artifactData.getData() != null) {
2990 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
2991 artifactData.setId(artifactDefinition.getEsId());
2993 res = saveArtifacts(artifactData, parentId);
2999 log.debug("Artifact saved into ES - {}", artifactUniqueId);
3000 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3001 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3003 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3004 log.debug("Failed to save the artifact.");
3005 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3006 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3007 resultOp = Either.right(responseFormat);
3010 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3011 decodedPayload, componentType, auditingAction, operationUuid, artifactData, prevArtifactId,
3012 currArtifactId, artifactDefinition);
3018 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3019 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3020 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction,
3021 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3022 ArtifactDefinition artifactDefinition) {
3023 StorageOperationStatus error;
3024 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3025 if (decodedPayload == null) {
3026 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3027 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3029 if (artifactFromCassandra.isRight()) {
3030 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3031 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3033 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3034 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3035 resultOp = Either.right(responseFormat);
3038 // clone data to new artifact
3039 artifactData.setData(artifactFromCassandra.left().value().getData());
3040 artifactData.setId(artifactFromCassandra.left().value().getId());
3042 // todo if not exist(first time)
3046 if (artifactDefinition.getEsId() == null) {
3047 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3048 artifactData.setId(artifactDefinition.getUniqueId());
3051 NodeTypeEnum convertParentType = convertParentType(componentType);
3052 // fetch the resource from storage
3053 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
3054 toscaOperationFacade.getToscaElement(parentId);
3055 if (resourceStorageOperationStatusEither.isRight()) {
3056 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
3057 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
3058 return Either.right(componentsUtils
3059 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
3061 Resource storedResource = resourceStorageOperationStatusEither.left().value();
3063 String interfaceToscaName = InterfaceUtils.createInterfaceToscaResourceName(
3064 storedResource.getName());
3065 //fetch the interface from storage
3066 Optional<InterfaceDefinition> interfaceDefinition = storedResource.getInterfaces().values()
3068 .filter(interfaceDef -> interfaceDef.getToscaResourceName()
3069 .equals(interfaceToscaName))
3071 if (!interfaceDefinition.isPresent()) {
3072 log.debug("Failed to get resource interface for resource Id {}", parentId);
3073 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3074 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3075 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3076 currArtifactId, responseFormat, componentType, null);
3077 return Either.right(responseFormat);
3080 //fetch the operation from storage
3081 InterfaceDefinition gotInterface = interfaceDefinition.get();
3082 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
3083 Optional<Operation> optionalOperation = operationsMap.values()
3085 .filter(o -> o.getUniqueId().equals(operationUuid))
3087 if (!optionalOperation.isPresent()) {
3088 log.debug("Failed to get resource interface operation for resource Id {} " +
3089 " and operationId {}", parentId, operationUuid);
3090 ResponseFormat responseFormat = componentsUtils.getResponseFormat(
3091 ActionStatus.INTERFACE_OPERATION_NOT_FOUND, parentId);
3092 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId,
3093 currArtifactId, responseFormat, componentType, null);
3094 return Either.right(responseFormat);
3097 Operation operation = optionalOperation.get();
3098 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
3099 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
3100 implementationArtifact.setDescription(artifactInfo.getDescription());
3101 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
3102 operation.setImplementation(implementationArtifact);
3103 gotInterface.setOperationsMap(operationsMap);
3104 Either<InterfaceDefinition, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
3105 interfaceOperation.updateInterface(storedResource.getUniqueId(), gotInterface);
3106 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
3107 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
3108 ActionStatus actionStatus =
3109 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
3110 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3113 String uniqueId = implementationArtifact.getUniqueId();
3114 artifactData.setId(uniqueId);
3115 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3116 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3117 log.debug("Failed to persist operation {} artifact, error is {}",operation.getName(),cassandraOperationStatus);
3118 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3119 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3120 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3122 return Either.left(Either.left(implementationArtifact));
3125 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3126 log.trace("Starting payload handling");
3127 byte[] payload = artifactInfo.getPayloadData();
3128 byte[] decodedPayload = null;
3130 if (payload != null && payload.length != 0) {
3131 // the generated artifacts were already decoded by the handler
3132 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3133 if (decodedPayload.length == 0) {
3134 log.debug("Failed to decode the payload.");
3135 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3136 return Either.right(responseFormat);
3139 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3140 artifactInfo.setArtifactChecksum(checkSum);
3141 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3143 // Specific payload validations of different types
3144 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
3145 if (isDeploymentArtifact(artifactInfo)) {
3146 log.trace("Starting deployment artifacts payload validation");
3147 String artifactType = artifactInfo.getArtifactType();
3148 if (ArtifactTypeEnum.HEAT.getType()
3149 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType()
3150 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET
3152 .equalsIgnoreCase(artifactType)
3153 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3154 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
3155 if (isValidPayload.isLeft()) {
3156 isValidPayload = extractHeatParameters(artifactInfo);
3159 else if (ArtifactTypeEnum.YANG_XML.getType()
3160 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType()
3161 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE
3163 .equalsIgnoreCase(artifactType)
3164 || ArtifactTypeEnum.VENDOR_LICENSE.getType()
3165 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE
3167 .equalsIgnoreCase(artifactType)
3168 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType()
3169 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION
3171 .equalsIgnoreCase(artifactType)) {
3172 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3174 else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType()
3175 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA
3177 .equalsIgnoreCase(artifactType)
3178 || ArtifactTypeEnum.VES_EVENTS.getType()
3179 .equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS
3181 .equalsIgnoreCase(artifactType)) {
3182 String artifactFileName = artifactInfo.getArtifactName();
3183 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
3184 switch (fileExtension) {
3186 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
3189 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
3193 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
3200 if (isValidPayload.isRight()) {
3201 ResponseFormat responseFormat = isValidPayload.right().value();
3202 return Either.right(responseFormat);
3205 } // null/empty payload is normal if called from metadata update ONLY.
3206 // The validation of whether this is metadata/payload update case is
3207 // currently done separately
3209 if (!isArtifactMetadataUpdate) {
3210 log.debug("Payload is missing.");
3211 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3212 return Either.right(responseFormat);
3215 log.trace("Ended payload handling");
3216 return Either.left(decodedPayload);
3219 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
3220 // Basic YAML validation
3221 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3222 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3223 log.debug("Invalid YAML format");
3224 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3225 return Either.right(responseFormat);
3227 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
3228 // HEAT specific YAML validation
3229 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
3230 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
3231 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
3232 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
3233 return Either.right(responseFormat);
3237 return Either.left(true);
3240 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
3241 Either<Boolean, ResponseFormat> res = Either.left(true);
3242 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3243 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
3244 log.debug("Invalid YAML format");
3245 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
3246 res = Either.right(responseFormat);
3252 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
3253 boolean isXmlValid = isValidXml(payload);
3255 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3256 .getResponseFormat(ActionStatus.INVALID_XML, artifactType);
3257 log.debug("Invalid XML content");
3258 return Either.right(responseFormat);
3260 return Either.left(true);
3263 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3264 boolean isJsonValid = isValidJson(payload);
3266 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
3267 .getResponseFormat(ActionStatus.INVALID_JSON, type);
3268 log.debug("Invalid JSON content");
3269 return Either.right(responseFormat);
3271 return Either.left(true);
3274 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3275 boolean inTransaction) {
3276 User user = new User();
3277 user.setUserId(userUserId);
3278 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3279 if (parent.isRight()) {
3280 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3283 return Either.right(responseFormat);
3285 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3288 false, inTransaction);
3289 if (handleDelete.isRight()) {
3290 return Either.right(handleDelete.right().value());
3292 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3293 return Either.left(result.right().value());
3297 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3298 Operation op = new Operation();
3299 long time = System.currentTimeMillis();
3300 op.setCreationDate(time);
3302 String artifactName = artifactInfo.getArtifactName();
3303 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3305 op.setImplementation(artifactInfo);
3306 op.setLastUpdateDate(time);
3310 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3311 String newArtifactName = operationName + "_" + artifactName;
3312 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3313 return newArtifactName;
3317 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3319 // General validation
3320 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3321 log.debug("One of the function parameteres is null");
3322 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3325 // Normalizing artifact name
3326 artifactName = ValidationUtils.normalizeFileName(artifactName);
3328 // Resource validation
3329 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3330 if (validateResourceNameAndVersion.isRight()) {
3331 return Either.right(validateResourceNameAndVersion.right().value());
3334 Resource resource = validateResourceNameAndVersion.left().value();
3335 String resourceId = resource.getUniqueId();
3337 // Service validation
3338 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3339 if (validateServiceNameAndVersion.isRight()) {
3340 return Either.right(validateServiceNameAndVersion.right().value());
3343 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3344 if (artifacts == null || artifacts.isEmpty()) {
3345 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3346 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3349 ArtifactDefinition deploymentArtifact = null;
3351 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3352 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3353 .equals(artifactName)) {
3354 log.debug("Found deployment artifact {}", artifactName);
3355 deploymentArtifact = artifactDefinition;
3360 if (deploymentArtifact == null) {
3361 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3362 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3365 // Downloading the artifact
3366 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3367 if (downloadArtifactEither.isRight()) {
3368 log.debug("Download artifact {} failed", artifactName);
3369 return Either.right(downloadArtifactEither.right().value());
3371 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3372 return Either.left(downloadArtifactEither.left().value().getRight());
3376 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3378 // General validation
3379 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3380 log.debug("One of the function parameteres is null");
3381 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3384 // Normalizing artifact name
3385 artifactName = ValidationUtils.normalizeFileName(artifactName);
3387 // Service validation
3388 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3389 if (validateServiceNameAndVersion.isRight()) {
3390 return Either.right(validateServiceNameAndVersion.right().value());
3393 Service service = validateServiceNameAndVersion.left().value();
3395 // ResourceInstance validation
3396 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3397 if (validateResourceInstance.isRight()) {
3398 return Either.right(validateResourceInstance.right().value());
3401 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3403 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3405 final String finalArtifactName = artifactName;
3406 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3408 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3410 .anyMatch(filterArtifactByName);
3411 ArtifactDefinition deployableArtifact;
3413 if (!hasDeploymentArtifacts) {
3414 log.debug("Deployment artifact with name {} not found", artifactName);
3415 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3418 log.debug("Found deployment artifact {}", artifactName);
3419 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3420 // Downloading the artifact
3421 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3423 if (downloadArtifactEither.isRight()) {
3424 log.debug("Download artifact {} failed", artifactName);
3425 return Either.right(downloadArtifactEither.right().value());
3427 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3428 return Either.left(downloadArtifactEither.left().value().getRight());
3431 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3433 List<ComponentInstance> riList = service.getComponentInstances();
3434 for (ComponentInstance ri : riList) {
3435 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3436 return Either.left(ri);
3440 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3443 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3445 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3446 if (serviceListBySystemName.isRight()) {
3447 log.debug("Couldn't fetch any service with name {}", serviceName);
3448 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3450 .value(), ComponentTypeEnum.SERVICE), serviceName));
3452 List<Service> serviceList = serviceListBySystemName.left().value();
3453 if (serviceList == null || serviceList.isEmpty()) {
3454 log.debug("Couldn't fetch any service with name {}", serviceName);
3455 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3458 Service foundService = null;
3459 for (Service service : serviceList) {
3460 if (service.getVersion().equals(serviceVersion)) {
3461 log.trace("Found service with version {}", serviceVersion);
3462 foundService = service;
3467 if (foundService == null) {
3468 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3469 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3470 .getValue(), serviceVersion));
3472 return Either.left(foundService);
3475 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3477 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3478 if (resourceListBySystemName.isRight()) {
3479 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3480 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3482 .value()), resourceName));
3484 return Either.left(resourceListBySystemName.left().value());
3487 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3489 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3490 if (serviceName == null || serviceVersion == null || artifactName == null) {
3491 log.debug("One of the function parameteres is null");
3492 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3495 // Normalizing artifact name
3496 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3498 // Service validation
3499 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3500 if (validateServiceNameAndVersion.isRight()) {
3501 return Either.right(validateServiceNameAndVersion.right().value());
3504 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3506 // Looking for deployment or tosca artifacts
3507 Service service = validateServiceNameAndVersion.left().value();
3509 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3510 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3511 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3514 Optional<ArtifactDefinition> foundArtifactOptl = null;
3516 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3517 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3518 // filters artifact by name
3519 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3521 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3522 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3523 // filters TOSCA artifact by name
3524 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3526 if (!foundArtifactOptl.isPresent()) {
3527 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3528 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3530 log.debug("Found deployment artifact {}", normalizedArtifactName);
3531 // Downloading the artifact
3532 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3534 if (downloadArtifactEither.isRight()) {
3535 log.debug("Download artifact {} failed", normalizedArtifactName);
3536 return Either.right(downloadArtifactEither.right().value());
3538 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3539 return Either.left(downloadArtifactEither.left().value().getRight());
3542 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3543 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3544 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3545 if (artifactById.isRight()) {
3546 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3547 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3548 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3550 ArtifactDefinition artifactDefinition = artifactById.left().value();
3551 if (artifactDefinition == null) {
3552 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3553 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3556 return downloadArtifact(artifactDefinition);
3559 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3560 boolean found = false;
3561 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3562 if (artifactsS != null) {
3563 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3564 if (entry.getValue().getUniqueId().equals(artifactId)) {
3570 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3571 if (!found && deploymentArtifactsS != null) {
3572 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3573 if (entry.getValue().getUniqueId().equals(artifactId)) {
3579 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3580 if (!found && toscaArtifactsS != null) {
3581 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3582 if (entry.getValue().getUniqueId().equals(artifactId)) {
3588 switch (component.getComponentType()) {
3590 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3591 if (!found && interfaces != null) {
3592 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3593 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3594 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3595 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3596 .getImplementation()
3598 .equals(artifactId)) {
3607 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3608 if (!found && apiArtifacts != null) {
3609 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3610 if (entry.getValue().getUniqueId().equals(artifactId)) {
3624 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3626 boolean found = false;
3627 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3628 ComponentInstance resourceInstance = null;
3629 for (ComponentInstance ri : resourceInstances) {
3630 if (ri.getUniqueId().equals(resourceInstanceId)) {
3631 resourceInstance = ri;
3635 if (resourceInstance != null) {
3636 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3637 if (artifacts != null) {
3638 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3639 if (entry.getValue().getUniqueId().equals(artifactId)) {
3646 artifacts = resourceInstance.getArtifacts();
3647 if (artifacts != null) {
3648 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3649 if (entry.getValue().getUniqueId().equals(artifactId)) {
3660 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3661 String containerComponentType) {
3663 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3664 componentForAudit.getNodeType();
3666 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3667 .getToscaFullElement(componentId);
3669 if (componentResult.isRight()) {
3670 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3671 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3672 log.debug("Service not found, serviceId {}", componentId);
3673 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3674 return Either.right(responseFormat);
3676 return Either.left(componentResult.left().value());
3679 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3680 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3681 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3682 if (canWork.isRight()) {
3683 String uniqueId = component.getUniqueId();
3684 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3685 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3687 .getComponentType(), null);
3688 return Either.right(canWork.right().value());
3691 return Either.left(true);
3694 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3696 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3697 String role = user.getRole();
3698 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3699 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3700 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3701 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3702 return Either.right(responseFormat);
3705 return Either.left(true);
3708 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3709 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3711 if (validateUserExists.isRight()) {
3712 User user = new User();
3713 user.setUserId(userId);
3714 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right()
3715 .value(), componentType, null);
3716 return Either.right(validateUserExists.right().value());
3718 return Either.left(validateUserExists.left().value());
3721 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3722 AuditingActionEnum auditingAction = null;
3723 switch (operation.getArtifactOperationEnum()) {
3725 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3728 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3731 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3734 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3739 return auditingAction;
3742 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3743 String esArtifactId = artifactDefinition.getEsId();
3744 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3745 if (artifactfromES.isRight()) {
3746 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3747 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3748 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3749 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3750 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3751 .getArtifactDisplayName());
3753 return Either.right(responseFormat);
3756 ESArtifactData esArtifactData = artifactfromES.left().value();
3757 byte[] data = esArtifactData.getDataAsArray();
3759 log.debug("Artifact data from ES is null");
3760 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3762 String artifactName = artifactDefinition.getArtifactName();
3763 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3764 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3767 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3768 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3771 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3772 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3774 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3775 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3778 log.info("Failed to save artifact {}.", artifactData.getId());
3784 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3785 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3788 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3789 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3792 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3793 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3794 if (user.isRight()) {
3795 ResponseFormat responseFormat;
3796 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3797 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3798 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3801 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3802 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3804 return Either.right(responseFormat);
3807 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3809 .value(), groupType);
3810 return Either.left(artifactDefinition);
3813 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3814 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3816 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3817 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3818 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3820 artifactInfo.setArtifactDisplayName(artifactName);
3821 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3822 artifactInfo.setArtifactType(artifactType);
3823 artifactInfo.setDescription(artifactDescription);
3824 artifactInfo.setArtifactGroupType(groupType);
3825 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3827 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3829 return artifactInfo;
3832 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3833 String uniqueId = null;
3835 if (resourceId != null) {
3836 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3838 artifactInfo.setUniqueId(uniqueId);
3840 artifactInfo.setUserIdCreator(user.getUserId());
3841 String fullName = user.getFullName();
3842 artifactInfo.setUpdaterFullName(fullName);
3844 long time = System.currentTimeMillis();
3846 artifactInfo.setCreatorFullName(fullName);
3847 artifactInfo.setCreationDate(time);
3849 artifactInfo.setLastUpdateDate(time);
3850 artifactInfo.setUserIdLastUpdater(user.getUserId());
3852 artifactInfo.setMandatory(true);
3855 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3856 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3859 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3860 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3863 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3865 byte[] payload = payloadStr.getBytes();
3867 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3868 return Either.left(artifactData);
3872 * @param artifactDefinition
3875 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3876 String instanceId, boolean shouldLock, boolean inTransaction) {
3877 String payload = generateHeatEnvPayload(artifactDefinition);
3878 String prevUUID = artifactDefinition.getArtifactUUID();
3879 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3880 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3882 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3885 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3886 boolean shouldLock, boolean inTransaction, String instanceId) {
3887 String payload = generateHeatEnvPayload(artifactDefinition);
3888 String prevUUID = artifactDefinition.getArtifactUUID();
3889 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3890 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3892 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3895 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3896 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3897 List<ComponentInstance> componentInstances = component.getComponentInstances();
3898 if (componentInstances != null) {
3899 Optional<ComponentInstance> findFirst = componentInstances.stream()
3900 .filter(ci -> ci.getUniqueId()
3901 .equals(instanceId))
3903 if (findFirst.isPresent()) {
3904 ComponentInstance relevantInst = findFirst.get();
3905 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3906 .getGroupInstances());
3908 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3909 updatedGroupInstances.forEach(gi -> {
3910 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3911 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3913 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3914 if (status.isRight()) {
3915 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3916 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3917 .convertFromStorageResponse(status.right()
3918 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3919 return Either.right(responseFormat);
3925 return Either.left(updatedArtDef);
3928 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3929 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3930 StringBuilder sb = new StringBuilder();
3931 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3932 sb.append("parameters:\n");
3933 if (heatParameters != null) {
3934 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3936 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3938 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3940 String heatValue = heatParameterDefinition.getCurrentValue();
3941 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3942 heatValue = heatParameterDefinition.getDefaultValue();
3943 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3944 empltyHeatValues.add(heatParameterDefinition);
3948 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3953 .append(heatParameterDefinition.getName())
3956 .append(Boolean.parseBoolean(heatValue))
3961 .append(heatParameterDefinition.getName())
3964 .append(new BigDecimal(heatValue).toPlainString())
3967 case COMMA_DELIMITED_LIST:
3970 .append(heatParameterDefinition.getName())
3977 String value = heatValue;
3978 boolean starts = value.startsWith("\"");
3979 boolean ends = value.endsWith("\"");
3980 if (!(starts && ends)) {
3981 starts = value.startsWith("'");
3982 ends = value.endsWith("'");
3983 if (!(starts && ends)) {
3984 value = "\"" + value + "\"";
3988 .append(heatParameterDefinition.getName())
3998 if (!empltyHeatValues.isEmpty()) {
3999 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
4000 empltyHeatValues.forEach(hv -> {
4001 sb.append(" ").append(hv.getName()).append(":");
4002 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
4003 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
4004 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
4005 sb.append(" \"\"").append("\n");
4008 sb.append(" ").append("\n");
4013 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
4016 return sb.toString().replaceAll("\\\\n", "\n");
4020 * @param artifactDefinition
4024 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4025 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4026 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
4027 .getHeatParamsUpdateDate(),
4028 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4032 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
4033 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
4034 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
4035 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
4039 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
4040 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
4042 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
4044 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
4045 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
4047 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
4048 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
4049 ESArtifactData artifactData = null;
4051 if (artifactDataRes.isLeft()) {
4052 artifactData = artifactDataRes.left().value();
4055 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4056 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4057 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4058 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4060 return Either.right(artifactDataRes.right().value());
4062 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4064 String esArtifactId = artifactDefinition.getEsId();
4065 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4066 ESArtifactData esArtifactData;
4067 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4068 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4069 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4070 if (artifactfromES.isRight()) {
4071 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4072 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4073 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4074 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4075 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4077 esArtifactData = artifactfromES.left().value();
4078 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4081 oldCheckSum = artifactDefinition.getArtifactChecksum();
4084 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4087 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4088 if (lockComponent.isRight()) {
4089 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4090 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4091 return Either.right(lockComponent.right().value());
4095 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4097 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4098 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4099 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4100 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4101 .getArtifactType(), artifactDefinition.getEsId());
4102 if (updateArifactDefinitionStatus.isRight()) {
4103 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4105 .value()), artifactDefinition.getArtifactDisplayName());
4106 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4107 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4108 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4109 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4111 return Either.right(responseFormat);
4116 oldCheckSum = artifactDefinition.getArtifactChecksum();
4117 artifactDefinition.setArtifactChecksum(newCheckSum);
4118 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4119 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4120 .getArtifactType(), artifactDefinition.getEsId());
4121 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4122 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4124 log.trace("Update Payload ", artifactDefinition.getEsId());
4126 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4128 artifactDefinition = updateArifactDefinitionStatus.left().value();
4129 artifactData.setId(artifactDefinition.getUniqueId());
4130 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4132 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4133 if (!inTransaction) {
4136 log.debug("Artifact Saved In ES {}", artifactData.getId());
4137 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4138 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4139 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4140 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4144 if (!inTransaction) {
4145 titanDao.rollback();
4147 log.info("Failed to save artifact {}.", artifactData.getId());
4148 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4149 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4150 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4151 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4153 return Either.right(responseFormat);
4157 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4159 .value()), artifactDefinition.getArtifactDisplayName());
4160 log.debug("Failed To update artifact {}", artifactData.getId());
4161 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4162 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4163 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4165 return Either.right(responseFormat);
4171 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4177 return Either.left(artifactDefinition);
4181 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4182 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4183 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4184 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4188 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4189 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4191 Map<String, Object> json = new HashMap<String, Object>();
4192 if (artifactId != null && !artifactId.isEmpty()) {
4193 json.put(Constants.ARTIFACT_ID, artifactId);
4196 json.put(Constants.ARTIFACT_NAME, artifactName);
4197 json.put(Constants.ARTIFACT_TYPE, artifactType);
4198 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4200 if (artifactContent != null) {
4201 log.debug("payload is encoded. perform decode");
4202 String encodedPayload = Base64.encodeBase64String(artifactContent);
4203 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4205 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4206 json.put(Constants.ARTIFACT_LABEL, label);
4207 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4208 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4209 : updatedRequiredArtifacts.stream()
4210 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4212 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4213 .map(e -> e.getFileName())
4214 .collect(Collectors.toList()));
4215 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4220 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4222 String jsonStr = gson.toJson(json);
4223 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4224 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4225 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4226 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4227 if (uploadArtifactToService.isRight()) {
4228 return Either.right(uploadArtifactToService.right().value());
4231 return Either.left(uploadArtifactToService.left().value());
4234 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4235 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4236 convertParentType(componentType);
4237 String parentId = parent.getUniqueId();
4238 ArtifactDefinition currArtifact = artifactInfo;
4240 if (origMd5 != null) {
4241 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4242 if (validateMd5.isRight()) {
4243 ResponseFormat responseFormat = validateMd5.right().value();
4244 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4245 return Either.right(responseFormat);
4248 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4249 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4250 if (deploymentValidationResult.isRight()) {
4251 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4252 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4253 return Either.right(responseFormat);
4256 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4257 if (payloadEither.isRight()) {
4258 ResponseFormat responseFormat = payloadEither.right().value();
4259 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4260 return Either.right(responseFormat);
4264 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4265 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4266 return Either.right(responseFormat);
4272 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
4273 if (lockComponent.isRight()) {
4274 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4275 .value(), componentType, null);
4276 return Either.right(lockComponent.right().value());
4279 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4281 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4287 if (resultOp == null || resultOp.isRight()) {
4288 log.debug("all changes rollback");
4289 if (!inTransaction) {
4290 titanDao.rollback();
4294 log.debug("all changes committed");
4295 if (!inTransaction) {
4300 componentType = parent.getComponentType();
4302 NodeTypeEnum nodeType = componentType.getNodeType();
4303 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4307 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4308 ComponentTypeEnum componentType, String origMd5) {
4310 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4311 Either<ArtifactDefinition, Operation> insideEither = null;
4312 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4313 if (getRI.isRight()) {
4314 return Either.right(getRI.right().value());
4316 ComponentInstance ri = getRI.left().value();
4317 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4318 if (getArtifactRes.isRight()) {
4319 return Either.right(getArtifactRes.right().value());
4321 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4323 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4324 .equals(ArtifactTypeEnum.HEAT_VOL
4325 .getType()) || currArtifact
4327 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4328 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4329 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4331 return Either.right(responseFormat);
4333 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4334 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4335 new ArrayList<HeatParameterDefinition>();
4338 if (origMd5 != null) {
4339 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4340 .getName(), currentHeatEnvParams,
4341 updatedHeatEnvParams, currArtifact.getArtifactName());
4342 if (uploadParamsValidationResult.isRight()) {
4343 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4344 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4346 return Either.right(responseFormat);
4348 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4351 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4353 if (validateAndConvertHeatParamers.isRight()) {
4354 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4355 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4357 return Either.right(responseFormat);
4360 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4361 // fill reduced heat env parameters List for updating
4362 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4363 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4364 currArtifact.setListHeatParameters(currentHeatEnvParams);
4366 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4367 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4368 if (updateArifactRes.isRight()) {
4369 log.debug("Failed to update artifact on graph - {}", artifactId);
4370 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4373 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4375 return Either.right(responseFormat);
4377 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4378 if (error != StorageOperationStatus.OK) {
4379 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4380 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4382 return Either.right(responseFormat);
4385 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4387 .getUniqueId(), parent.getUniqueId());
4388 if (error != StorageOperationStatus.OK) {
4389 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4390 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4392 return Either.right(responseFormat);
4396 insideEither = Either.left(currArtifact);
4397 resultOp = Either.left(insideEither);
4398 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4399 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4404 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4405 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4406 String paramName = heatEnvParam.getName();
4407 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4408 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4409 String updatedParamValue = heatEnvParam.getCurrentValue();
4410 currHeatParam.setCurrentValue(updatedParamValue);
4416 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4417 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4419 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4420 Either<ArtifactDefinition, Operation> insideEither = null;
4421 String currentHeatId = currHeatArtifact.getUniqueId();
4423 String esArtifactId = currHeatArtifact.getEsId();
4424 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4425 if (artifactFromES.isRight()) {
4426 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4427 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4428 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4429 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4430 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4433 ESArtifactData esArtifactData = artifactFromES.left().value();
4435 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4437 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4438 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4439 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4441 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4445 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4447 paramName = heatEnvParam.getName();
4448 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4449 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4451 String updatedParamValue = heatEnvParam.getCurrentValue();
4452 if (updatedParamValue == null) {
4453 updatedParamValue = heatEnvParam.getDefaultValue();
4455 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4456 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4457 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4458 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4459 .getType(), paramType.getType(), paramName);
4460 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4461 return Either.right(responseFormat);
4464 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4465 newHeatEnvParams.add(currHeatParam);
4470 if (!newHeatEnvParams.isEmpty()) {
4471 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4472 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4473 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4475 if (operationStatus.isRight()) {
4476 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4478 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4481 return Either.right(responseFormat);
4484 updatedHeatArt = operationStatus.left().value();
4486 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4487 esArtifactData.setId(updatedHeatArt.getEsId());
4489 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4492 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
4493 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4494 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4495 .getUniqueId(), responseFormat, componentType, null);
4498 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
4499 log.debug("Failed to save the artifact.");
4500 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4501 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4502 .getUniqueId(), responseFormat, componentType, null);
4503 resultOp = Either.right(responseFormat);
4506 insideEither = Either.left(updatedHeatArt);
4509 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4510 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4511 artifactEnvInfo.setArtifactChecksum(null);
4512 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4513 .getUniqueId(), componentType.getNodeType(), componentId);
4516 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4520 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4521 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4523 .value(), parent, componentType);
4524 if (result != ActionStatus.OK) {
4525 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4526 return Either.right(responseFormat);
4530 if (updatedHeatEnvParams.isEmpty()) {
4531 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4533 resultOp = Either.left(insideEither);
4534 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4535 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4540 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4541 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4542 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4543 return Either.right(responseFormat);
4547 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4548 StorageOperationStatus error = StorageOperationStatus.OK;
4549 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4550 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4551 List<String> groupInstancesId = null;
4552 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4553 groupInstancesId = groupsInstances.stream()
4554 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4555 .contains(artifactId))
4556 .map(GroupInstanceDataDefinition::getUniqueId)
4557 .collect(Collectors.toList());
4559 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4560 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4566 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4567 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4569 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4570 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4571 .getArtifactName(), currArtifactName);
4572 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4573 return Either.right(responseFormat);
4576 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4577 String paramName = uploadedHeatParam.getName();
4578 boolean isExistsInHeat = false;
4579 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4580 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4582 isExistsInHeat = true;
4583 uploadedHeatParam.setType(currHeatParam.getType());
4584 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4585 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4586 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4590 if (!isExistsInHeat) {
4591 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4592 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4593 return Either.right(responseFormat);
4596 return Either.left(updatedHeatEnvParams);
4599 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4600 ResponseFormat responseFormat = null;
4601 List<ComponentInstance> ris = component.getComponentInstances();
4602 for (ComponentInstance ri : ris) {
4603 if (riID.equals(ri.getUniqueId())) {
4604 return Either.left(ri);
4607 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4608 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4609 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4610 return Either.right(responseFormat);
4613 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4614 ResponseFormat responseFormat = null;
4615 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4616 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4617 if (artifactId.equals(artifact.getUniqueId())) {
4618 return Either.left(artifact);
4621 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4622 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4624 return Either.right(responseFormat);
4627 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4628 ArtifactDefinition ret;
4629 if (eitherArtifact.isLeft()) {
4630 ret = eitherArtifact.left().value();
4633 ret = eitherArtifact.right().value().getImplementationArtifact();
4639 * downloads artifact of component by UUIDs
4641 * @param componentType
4642 * @param componentUuid
4643 * @param artifactUUID
4644 * @param auditAdditionalParam
4647 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4648 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4649 Either<byte[], ResponseFormat> result;
4650 byte[] downloadedArtifact = null;
4651 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4652 if (errorWrapper.isEmpty()) {
4653 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4654 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4656 if (errorWrapper.isEmpty()) {
4657 result = Either.left(downloadedArtifact);
4660 result = Either.right(errorWrapper.getInnerElement());
4666 * downloads an artifact of resource instance of component by UUIDs
4668 * @param componentType
4669 * @param componentUuid
4670 * @param resourceInstanceName
4671 * @param artifactUUID
4672 * @param auditAdditionalParam
4675 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4676 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4677 Either<byte[], ResponseFormat> result;
4678 byte[] downloadedArtifact = null;
4679 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4680 if (errorWrapper.isEmpty()) {
4681 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4684 if (errorWrapper.isEmpty()) {
4685 result = Either.left(downloadedArtifact);
4688 result = Either.right(errorWrapper.getInnerElement());
4694 * uploads an artifact to a component by UUID
4698 * @param componentType
4699 * @param componentUuid
4700 * @param additionalParams
4704 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4705 ArtifactOperationInfo operation) {
4706 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4707 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4708 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4709 ArtifactDefinition uploadArtifact = null;
4710 Component component = null;
4711 String componentId = null;
4712 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4713 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4714 String userId = request.getHeader(Constants.USER_ID_HEADER);
4716 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4717 if (getComponentRes.isRight()) {
4718 StorageOperationStatus status = getComponentRes.right().value();
4719 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4720 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4722 if (errorWrapper.isEmpty()) {
4723 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4724 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4726 if (!getComponentRes.left()
4728 .getMetadataDataDefinition()
4730 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4731 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4732 if (component != null) {
4733 componentId = component.getUniqueId();
4734 componentName = component.getName();
4737 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4739 if (errorWrapper.isEmpty()) {
4740 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4741 if (actionResult.isRight()) {
4742 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4745 errorWrapper.setInnerElement(actionResult.right().value());
4748 if (errorWrapper.isEmpty()) {
4749 uploadArtifact = actionResult.left().value().left().value();
4750 uploadArtifactResult = Either.left(uploadArtifact);
4753 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4755 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4756 return uploadArtifactResult;
4760 * upload an artifact to a resource instance by UUID
4764 * @param componentType
4765 * @param componentUuid
4766 * @param resourceInstanceName
4767 * @param additionalParams
4771 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4772 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4773 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4774 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4775 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4776 ArtifactDefinition uploadArtifact = null;
4777 Component component = null;
4778 String componentInstanceId;
4780 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4781 String userId = request.getHeader(Constants.USER_ID_HEADER);
4783 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4784 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4785 if (getComponentRes.isRight()) {
4786 StorageOperationStatus status = getComponentRes.right().value();
4787 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4788 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4790 if (errorWrapper.isEmpty() && !getComponentRes.left()
4792 .getMetadataDataDefinition()
4794 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4795 component = checkoutParentComponent(componentType, getComponentRes.left()
4797 .getMetadataDataDefinition()
4798 .getUniqueId(), userId, errorWrapper);
4800 if (errorWrapper.isEmpty()) {
4801 if (component == null) {
4802 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4805 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4808 if (errorWrapper.isEmpty()) {
4809 componentInstanceId = componentRiPair.getRight().getUniqueId();
4810 componentId = componentRiPair.getLeft().getUniqueId();
4811 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4813 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4814 .findParamByType(componentType));
4815 if (actionResult.isRight()) {
4816 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4819 errorWrapper.setInnerElement(actionResult.right().value());
4822 if (errorWrapper.isEmpty()) {
4823 uploadArtifact = actionResult.left().value().left().value();
4824 uploadArtifactResult = Either.left(uploadArtifact);
4827 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4829 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4830 return uploadArtifactResult;
4834 * updates an artifact on a component by UUID
4838 * @param componentType
4839 * @param componentUuid
4840 * @param artifactUUID
4841 * @param additionalParams
4842 * @param operation TODO
4845 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4846 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4847 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4848 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4849 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4850 ArtifactDefinition updateArtifact = null;
4851 Component component = null;
4852 String componentId = null;
4853 String artifactId = null;
4854 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4855 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4856 String userId = request.getHeader(Constants.USER_ID_HEADER);
4858 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4859 if (getComponentRes.isRight()) {
4860 StorageOperationStatus status = getComponentRes.right().value();
4861 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4862 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4864 if (errorWrapper.isEmpty()) {
4865 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4866 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4868 if (!getComponentRes.left()
4870 .getMetadataDataDefinition()
4872 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4873 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4874 if (component != null) {
4875 componentId = component.getUniqueId();
4876 componentName = component.getName();
4879 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4881 if (errorWrapper.isEmpty()) {
4882 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4884 if (errorWrapper.isEmpty()) {
4885 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4886 if (actionResult.isRight()) {
4887 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
4890 errorWrapper.setInnerElement(actionResult.right().value());
4893 if (errorWrapper.isEmpty()) {
4894 updateArtifact = actionResult.left().value().left().value();
4895 updateArtifactResult = Either.left(updateArtifact);
4899 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4901 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4902 return updateArtifactResult;
4906 * updates an artifact on a resource instance by UUID
4910 * @param componentType
4911 * @param componentUuid
4912 * @param resourceInstanceName
4913 * @param artifactUUID
4914 * @param additionalParams
4915 * @param operation TODO
4918 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4919 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4921 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4922 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4923 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4924 ArtifactDefinition updateArtifact = null;
4925 Component component = null;
4926 String componentInstanceId = null;
4927 String componentId = null;
4928 String artifactId = null;
4929 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4930 String userId = request.getHeader(Constants.USER_ID_HEADER);
4932 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4933 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4934 if (getComponentRes.isRight()) {
4935 StorageOperationStatus status = getComponentRes.right().value();
4936 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4937 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4939 if (errorWrapper.isEmpty() && !getComponentRes.left()
4941 .getMetadataDataDefinition()
4943 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4944 component = checkoutParentComponent(componentType, getComponentRes.left()
4946 .getMetadataDataDefinition()
4947 .getUniqueId(), userId, errorWrapper);
4949 if (errorWrapper.isEmpty()) {
4950 if (component == null) {
4951 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4954 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4957 if (errorWrapper.isEmpty()) {
4958 componentInstanceId = componentRiPair.getRight().getUniqueId();
4959 componentId = componentRiPair.getLeft().getUniqueId();
4960 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4962 if (errorWrapper.isEmpty()) {
4963 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4965 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4966 .findParamByType(componentType));
4967 if (actionResult.isRight()) {
4968 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
4971 errorWrapper.setInnerElement(actionResult.right().value());
4974 if (errorWrapper.isEmpty()) {
4975 updateArtifact = actionResult.left().value().left().value();
4976 updateArtifactResult = Either.left(updateArtifact);
4979 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4981 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4982 return updateArtifactResult;
4986 * updates an artifact on a component by UUID
4990 * @param componentType
4991 * @param componentUuid
4992 * @param artifactUUID
4993 * @param additionalParams
4994 * @param operation TODO
4997 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4998 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4999 String componentUuid, String artifactUUID, String operationUUID,
5000 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
5001 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5002 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
5003 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5004 ArtifactDefinition updateArtifact = null;
5005 String componentId = null;
5006 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
5007 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5008 String userId = request.getHeader(Constants.USER_ID_HEADER);
5010 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5011 if (getComponentRes.isRight()) {
5012 StorageOperationStatus status = getComponentRes.right().value();
5013 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5014 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5016 if (errorWrapper.isEmpty()) {
5017 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5018 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5019 if (!getComponentRes.left()
5021 .getMetadataDataDefinition()
5023 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5024 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5025 if (component != null) {
5026 componentId = component.getUniqueId();
5027 componentName = component.getName();
5029 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
5032 if (errorWrapper.isEmpty()) {
5033 Either<String, ResponseFormat> interfaceName = fetchInterfaceName(componentId);
5034 if (interfaceName.isRight()) {
5035 errorWrapper.setInnerElement(interfaceName.right().value());
5037 if (errorWrapper.isEmpty()) {
5038 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5039 artifactUUID, artifactInfo, origMd5, data, interfaceName.left().value(),
5040 operationUUID, null, null);
5041 if (actionResult.isRight()) {
5042 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
5045 errorWrapper.setInnerElement(actionResult.right().value());
5049 if (errorWrapper.isEmpty()) {
5050 updateArtifact = actionResult.left().value().left().value();
5051 updateArtifactResult = Either.left(updateArtifact);
5055 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5057 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
5058 return updateArtifactResult;
5061 private Either<String, ResponseFormat> fetchInterfaceName(String componentId) {
5062 Either<Resource, StorageOperationStatus> resourceStorageOperationStatusEither =
5063 toscaOperationFacade.getToscaElement(componentId);
5064 if (resourceStorageOperationStatusEither.isRight()) {
5065 StorageOperationStatus errorStatus = resourceStorageOperationStatusEither.right().value();
5066 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
5067 return Either.right(componentsUtils
5068 .getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5070 Resource storedResource = resourceStorageOperationStatusEither.left().value();
5072 return Either.left(InterfaceUtils.createInterfaceToscaResourceName(
5073 storedResource.getName()));
5078 * deletes an artifact on a component by UUID
5081 * @param componentType
5082 * @param componentUuid
5083 * @param artifactUUID
5084 * @param additionalParams
5085 * @param operation TODO
5088 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
5089 ArtifactOperationInfo operation) {
5091 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5092 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5093 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5094 ArtifactDefinition deleteArtifact = null;
5095 Component component = null;
5096 String componentId = null;
5097 String artifactId = null;
5098 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5099 String userId = request.getHeader(Constants.USER_ID_HEADER);
5101 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5102 if (getComponentRes.isRight()) {
5103 StorageOperationStatus status = getComponentRes.right().value();
5104 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5105 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5107 if (errorWrapper.isEmpty()) {
5108 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5109 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5110 if (!getComponentRes.left()
5112 .getMetadataDataDefinition()
5114 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5115 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5116 if (component != null) {
5117 componentId = component.getUniqueId();
5118 componentName = component.getName();
5121 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
5123 if (errorWrapper.isEmpty()) {
5124 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5126 if (errorWrapper.isEmpty()) {
5127 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5128 if (actionResult.isRight()) {
5129 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult
5132 errorWrapper.setInnerElement(actionResult.right().value());
5135 if (errorWrapper.isEmpty()) {
5136 deleteArtifact = actionResult.left().value().left().value();
5137 deleteArtifactResult = Either.left(deleteArtifact);
5140 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5142 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5143 return deleteArtifactResult;
5147 * deletes an artifact from a resource instance by UUID
5150 * @param componentType
5151 * @param componentUuid
5152 * @param resourceInstanceName
5153 * @param artifactUUID
5154 * @param additionalParams
5155 * @param operation TODO
5158 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5159 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
5161 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5162 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5163 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5164 ArtifactDefinition deleteArtifact = null;
5165 Component component = null;
5166 String componentInstanceId = null;
5167 String componentId = null;
5168 String artifactId = null;
5169 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5170 String userId = request.getHeader(Constants.USER_ID_HEADER);
5171 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5172 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5173 if (getComponentRes.isRight()) {
5174 StorageOperationStatus status = getComponentRes.right().value();
5175 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5176 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5178 if (errorWrapper.isEmpty() && !getComponentRes.left()
5180 .getMetadataDataDefinition()
5182 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5183 component = checkoutParentComponent(componentType, getComponentRes.left()
5185 .getMetadataDataDefinition()
5186 .getUniqueId(), userId, errorWrapper);
5188 if (errorWrapper.isEmpty()) {
5189 if (component == null) {
5190 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5193 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5196 if (errorWrapper.isEmpty()) {
5197 componentInstanceId = componentRiPair.getRight().getUniqueId();
5198 componentId = componentRiPair.getLeft().getUniqueId();
5199 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5201 if (errorWrapper.isEmpty()) {
5203 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5204 .findParamByType(componentType));
5206 if (actionResult.isRight()) {
5207 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult
5210 errorWrapper.setInnerElement(actionResult.right().value());
5213 if (errorWrapper.isEmpty()) {
5214 deleteArtifact = actionResult.left().value().left().value();
5215 deleteArtifactResult = Either.left(deleteArtifact);
5218 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5220 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
5221 return deleteArtifactResult;
5224 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5225 String artifactId = null;
5226 ArtifactDefinition foundArtifact = null;
5227 if (instance.getDeploymentArtifacts() != null) {
5228 foundArtifact = instance.getDeploymentArtifacts()
5231 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5232 .equals(artifactUUID))
5236 if (foundArtifact == null && instance.getArtifacts() != null) {
5237 foundArtifact = instance.getArtifacts()
5240 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5241 .equals(artifactUUID))
5245 if (foundArtifact == null) {
5246 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5247 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5250 artifactId = foundArtifact.getUniqueId();
5255 @SuppressWarnings("unchecked")
5256 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5257 Map<String, String> existingEnvVersions) {
5258 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5260 .getDeploymentResourceInstanceArtifacts();
5261 if (deploymentResourceArtifacts == null) {
5262 log.debug("no deployment artifacts are configured for generated artifacts");
5263 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5265 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5266 if (placeHolderData == null) {
5267 log.debug("no env type {} are configured for generated artifacts", envType);
5268 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5271 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5272 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5273 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5274 if (createArtifactPlaceHolder.isRight()) {
5275 return Either.right(createArtifactPlaceHolder.right().value());
5277 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5278 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5279 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5280 artifactHeatEnv.setTimeout(0);
5281 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5282 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5283 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5284 ArtifactDefinition heatEnvPlaceholder;
5285 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5286 if (parentType != NodeTypeEnum.ResourceInstance) {
5287 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5288 .getUniqueId(), parentType, parentId);
5289 if (addHeatEnvArtifact.isRight()) {
5290 log.debug("failed to create heat env artifact on resource instance");
5291 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5293 .value(), false), "", null));
5295 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5298 heatEnvPlaceholder = artifactHeatEnv;
5299 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5300 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5302 String artifactData = buildAuditingArtifactData(heatEnvPlaceholder);
5303 ComponentTypeEnum componentType = component.getComponentType();
5304 if (parentType == NodeTypeEnum.ResourceInstance) {
5305 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5307 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD, componentType,
5308 ResourceAuditData.newBuilder().build(),
5309 ResourceAuditData.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5310 parentName, null, artifactData, null);
5311 return Either.left(heatEnvPlaceholder);
5314 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5315 if (artifact.getListHeatParameters() == null) {
5318 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5319 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5320 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5321 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5322 heatEnvParameter.setCurrentValue(null);
5323 heatEnvParameters.add(heatEnvParameter);
5325 artifactDefinition.setListHeatParameters(heatEnvParameters);
5328 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5329 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5330 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5331 String name = heatArtifact.getArtifactName();
5334 name = heatArtifact.getArtifactLabel();
5335 fileName = name + "." + envExtension;
5338 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5340 heatEnvArtifact.setArtifactName(fileName);
5343 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5344 if (null != existingEnvVersions) {
5345 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5346 if (null != prevVersion) {
5347 heatEnvArtifact.setArtifactVersion(prevVersion);
5353 * Handles Artifacts Request For Inner Component
5355 * @param artifactsToHandle
5358 * @param vfcsNewCreatedArtifacts
5361 * @param inTransaction
5364 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5365 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5367 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5368 ComponentTypeEnum componentType = component.getComponentType();
5369 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5370 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5371 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5375 for (ArtifactDefinition artifact : artifactsToHandle) {
5376 originData = buildJsonStringForCsarVfcArtifact(artifact);
5377 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5378 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5379 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5380 if (actionResult.isRight()) {
5381 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5382 .getName(), actionResult.right().value());
5383 errorWrapper.setInnerElement(actionResult.right().value());
5384 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5385 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5389 uploadedArtifacts.add(actionResult.left().value().left().value());
5391 if (errorWrapper.isEmpty()) {
5392 handleArtifactsResult = Either.left(uploadedArtifacts);
5395 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5398 catch (Exception e) {
5399 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5400 handleArtifactsResult = Either.right(responseFormat);
5401 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5403 return handleArtifactsResult;
5406 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5407 ComponentInstance componentInstance = null;
5408 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5409 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5410 if (errorWrapper.isEmpty()) {
5411 componentInstance = component.getComponentInstances()
5413 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5414 .equals(normalizedName))
5417 if (componentInstance == null) {
5418 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5420 .getValue(), component.getName()));
5421 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5424 return componentInstance;
5427 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5429 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5430 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5431 ComponentInstance componentInstance = component.getComponentInstances()
5433 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5434 .equals(normalizedName))
5437 if (componentInstance == null) {
5438 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5440 .getValue(), component.getName()));
5441 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5444 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5446 return relatedComponentComponentInstancePair;
5449 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5450 ComponentInstance componentInstance;
5451 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5452 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5453 if (errorWrapper.isEmpty()) {
5454 componentInstance = component.getComponentInstances()
5456 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5459 if (componentInstance == null) {
5460 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component
5462 .getValue(), component.getName()));
5463 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
5466 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5469 return relatedComponentComponentInstancePair;
5472 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5474 byte[] downloadedArtifact = null;
5475 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5476 List<ArtifactDefinition> artifactsList = null;
5477 ArtifactDefinition deploymentArtifact = null;
5478 if (artifacts != null && !artifacts.isEmpty()) {
5479 artifactsList = artifacts.values()
5481 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5482 .equals(artifactUUID))
5483 .collect(Collectors.toList());
5485 if (artifactsList == null || artifactsList.isEmpty()) {
5486 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5487 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5489 if (errorWrapper.isEmpty()) {
5490 deploymentArtifact = artifactsList.get(0);
5491 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5492 if (downloadArtifactEither.isRight()) {
5493 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5494 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5497 if (errorWrapper.isEmpty()) {
5498 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5499 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5501 return downloadedArtifact;
5504 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5505 Component component = null;
5506 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5507 if (getComponentRes.isRight()) {
5508 StorageOperationStatus status = getComponentRes.right().value();
5509 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5510 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5513 component = getComponentRes.left().value();
5518 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5519 Component component = null;
5520 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5521 if (getComponentRes.isRight()) {
5522 StorageOperationStatus status = getComponentRes.right().value();
5523 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5524 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5527 List<Component> value = getComponentRes.left().value();
5528 if (value.isEmpty()) {
5529 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5530 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5531 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5534 component = value.get(0);
5540 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5541 String artifactId = null;
5542 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5543 StorageOperationStatus storageStatus;
5544 ArtifactDefinition latestArtifact = null;
5545 List<ArtifactDefinition> artifacts = null;
5546 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5547 if (getArtifactsRes.isRight()) {
5548 storageStatus = getArtifactsRes.right().value();
5549 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5550 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5551 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5553 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5555 if (errorWrapper.isEmpty()) {
5556 artifacts = getArtifactsRes.left()
5560 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5561 .equals(artifactUUID))
5562 .collect(Collectors.toList());
5563 if (artifacts == null || artifacts.isEmpty()) {
5564 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5565 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5568 if (errorWrapper.isEmpty()) {
5569 latestArtifact = artifacts.stream().max((a1, a2) -> {
5570 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5571 if (compareRes == 0) {
5572 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5573 .getLastUpdateDate());
5577 if (latestArtifact == null) {
5578 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5579 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5582 if (errorWrapper.isEmpty()) {
5583 artifactId = latestArtifact.getUniqueId();
5588 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5590 Component component = null;
5591 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5592 if (getUserRes.isRight()) {
5593 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5596 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5598 if (errorWrapper.isEmpty()) {
5599 User modifier = getUserRes.left().value();
5600 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5601 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5602 if (checkoutRes.isRight()) {
5603 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5604 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5605 errorWrapper.setInnerElement(checkoutRes.right().value());
5608 component = checkoutRes.left().value();
5614 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
5615 if (artifact == null) {
5616 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
5617 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
5618 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
5619 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
5623 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
5624 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
5625 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
5629 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5630 Map<String, Object> json = new HashMap<>();
5631 String artifactName = artifact.getArtifactName();
5632 json.put(Constants.ARTIFACT_NAME, artifactName);
5633 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5634 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5635 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5636 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5637 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5638 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5639 return gson.toJson(json);
5643 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5644 this.nodeTemplateOperation = nodeTemplateOperation;