2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Collection;
28 import java.util.Comparator;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
35 import java.util.function.Predicate;
36 import java.util.function.Supplier;
37 import java.util.stream.Collectors;
39 import javax.servlet.http.HttpServletRequest;
41 import org.apache.commons.codec.binary.Base64;
42 import org.apache.commons.lang3.tuple.ImmutablePair;
43 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
44 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
45 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
46 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
47 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
48 import org.openecomp.sdc.be.config.BeEcompErrorManager;
49 import org.openecomp.sdc.be.config.Configuration.DeploymentArtifactTypeConfig;
50 import org.openecomp.sdc.be.config.ConfigurationManager;
51 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
52 import org.openecomp.sdc.be.dao.api.ActionStatus;
53 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
54 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
55 import org.openecomp.sdc.be.dao.titan.TitanOperationStatus;
56 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
57 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
59 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.ArtifactType;
62 import org.openecomp.sdc.be.model.Component;
63 import org.openecomp.sdc.be.model.ComponentInstance;
64 import org.openecomp.sdc.be.model.HeatParameterDefinition;
65 import org.openecomp.sdc.be.model.InterfaceDefinition;
66 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
67 import org.openecomp.sdc.be.model.LifecycleStateEnum;
68 import org.openecomp.sdc.be.model.Operation;
69 import org.openecomp.sdc.be.model.Resource;
70 import org.openecomp.sdc.be.model.Service;
71 import org.openecomp.sdc.be.model.User;
72 import org.openecomp.sdc.be.model.heat.HeatParameterType;
73 import org.openecomp.sdc.be.model.operations.api.IArtifactOperation;
74 import org.openecomp.sdc.be.model.operations.api.IComponentInstanceOperation;
75 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
76 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
77 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
78 import org.openecomp.sdc.be.model.operations.api.IResourceOperation;
79 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
80 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
81 import org.openecomp.sdc.be.model.operations.impl.ComponentOperation;
82 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
83 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
84 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
85 import org.openecomp.sdc.be.resources.data.ArtifactData;
86 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
87 import org.openecomp.sdc.be.resources.data.ESArtifactData;
88 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
89 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
90 import org.openecomp.sdc.be.servlets.RepresentationUtils;
91 import org.openecomp.sdc.be.tosca.CsarUtils;
92 import org.openecomp.sdc.be.tosca.ToscaError;
93 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
94 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
95 import org.openecomp.sdc.be.user.IUserBusinessLogic;
96 import org.openecomp.sdc.be.user.Role;
97 import org.openecomp.sdc.be.user.UserBusinessLogic;
98 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
99 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
100 import org.openecomp.sdc.common.api.Constants;
101 import org.openecomp.sdc.common.config.EcompErrorName;
102 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
103 import org.openecomp.sdc.common.datastructure.Wrapper;
104 import org.openecomp.sdc.common.util.GeneralUtility;
105 import org.openecomp.sdc.common.util.ValidationUtils;
106 import org.openecomp.sdc.common.util.YamlToObjectConverter;
107 import org.openecomp.sdc.exception.ResponseFormat;
108 import org.slf4j.Logger;
109 import org.slf4j.LoggerFactory;
110 import org.springframework.beans.factory.annotation.Autowired;
111 import org.xml.sax.InputSource;
112 import org.xml.sax.SAXException;
113 import org.xml.sax.XMLReader;
114 import org.yaml.snakeyaml.Yaml;
116 import com.google.gson.Gson;
117 import com.google.gson.GsonBuilder;
118 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
120 import fj.data.Either;
122 @org.springframework.stereotype.Component("artifactBusinessLogic")
123 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
124 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
125 private static final String ARTIFACT_DESCRIPTION = "artifact description";
126 private static final String ARTIFACT_LABEL = "artifact label";
127 private static final String ARTIFACT_URL = "artifact url";
128 private static final String ARTIFACT_NAME = "artifact name";
129 private static final String ARTIFACT_PAYLOAD = "artifact payload";
131 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
132 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
133 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
135 private static Integer defaultHeatTimeout;
136 private static final Integer NON_HEAT_TIMEOUT = 0;
137 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
138 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
140 @javax.annotation.Resource
141 private IArtifactOperation artifactOperation;
143 // @javax.annotation.Resource
144 // private IResourceUploader daoUploader;
146 @javax.annotation.Resource
147 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
148 @javax.annotation.Resource
149 private IUserAdminOperation userOperaton;
151 // @javax.annotation.Resource
152 // private ESCatalogDAO esCatalogDao;
154 @javax.annotation.Resource
155 private IElementOperation elementOperation;
157 @javax.annotation.Resource
158 private ResourceBusinessLogic resourceBusinessLogic;
160 @javax.annotation.Resource
161 private ServiceBusinessLogic serviceBusinessLogic;
163 @javax.annotation.Resource
164 private UserBusinessLogic userAdminManager;
166 @javax.annotation.Resource
167 private IHeatParametersOperation heatParametersOperation;
169 @javax.annotation.Resource
170 private IComponentInstanceOperation resourceInstanceOperation;
173 private ArtifactCassandraDao artifactCassandraDao;
176 private ToscaExportHandler toscaExportUtils;
179 private CsarUtils csarUtils;
182 private LifecycleBusinessLogic lifecycleBusinessLogic;
185 private IUserBusinessLogic userBusinessLogic;
187 public ArtifactsBusinessLogic() {
188 defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
189 if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
190 defaultHeatTimeout = 60;
194 public static enum ArtifactOperation {
196 Create(false), Update(false), Delete(false), Download(false);
198 private boolean isExternalApi;
200 ArtifactOperation(boolean isExternalApi) {
201 this.isExternalApi = isExternalApi;
204 public boolean isExternalApi() {
205 return isExternalApi;
208 public void setExternalApi(boolean isExternalApi) {
209 this.isExternalApi = isExternalApi;
214 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo,
215 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
216 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
219 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo,
220 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
222 // detect auditing type
223 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
224 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
227 if (userId == null) {
228 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
229 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
230 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
231 return Either.right(responseFormat);
234 // check user existence
237 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
238 if (userResult.isRight()) {
239 return Either.right(userResult.right().value());
242 User user = userResult.left().value();
243 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
244 if (validateUserRole.isRight()) {
245 return Either.right(validateUserRole.right().value());
249 // 5. check service/resource existence
250 // 6. check service/resource check out
251 // 7. user is owner of checkout state
252 org.openecomp.sdc.be.model.Component component = null;
253 // ComponentInstance resourceInstance = null;
254 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
255 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
256 if (validateComponent.isRight()) {
257 return Either.right(validateComponent.right().value());
259 component = validateComponent.left().value();
260 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
261 if (validateWorkOnResource.isRight()) {
262 return Either.right(validateWorkOnResource.right().value());
265 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
266 shouldLock, inTransaction);
272 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
273 * For regular usage use <br>
274 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperation, String, ArtifactDefinition, String, String, String, String, String, String)}
278 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactUniqueId, ArtifactDefinition artifactDefinition,
279 String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) {
280 Component parent = component;
281 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
283 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
284 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper);
286 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
287 if (errorWrapper.isEmpty()) {
289 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction);
291 result = Either.right(errorWrapper.getInnerElement());
296 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
297 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper) {
298 if (operation == ArtifactOperation.Update || operation == ArtifactOperation.Delete || operation == ArtifactOperation.Download) {
299 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId);
300 if (validateArtifact.isRight()) {
301 ResponseFormat responseFormat = validateArtifact.right().value();
302 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
303 errorWrapper.setInnerElement(validateArtifact.right().value());
304 } else if (operation == ArtifactOperation.Download) {
305 artifactInfo = validateArtifact.left().value();
306 handleHeatEnvDownload(componentId, user, component, validateArtifact, shouldLock, errorWrapper);
312 private void handleHeatEnvDownload(String componentId, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper) {
313 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
315 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
316 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
317 ArtifactDefinition heatEnvWithHeatParams = componentInstance.getDeploymentArtifacts().values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
318 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, component, componentInstance.getName(), user, shouldLock);
319 if (eitherGenerated.isRight()) {
320 errorWrapper.setInnerElement(eitherGenerated.right().value());
325 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
326 return artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
329 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
330 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
332 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB, shouldLock, inTransaction);
333 if (generated.isRight()) {
336 byte[] decodedPayload = artifactDefinition.getPayloadData();
337 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
338 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
339 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
340 shouldLock, inTransaction);
344 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB, boolean shouldLock,
345 boolean inTransaction) {
346 log.debug("tosca artifact generation");
347 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
348 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest, shouldLock, inTransaction);
350 if (generated.isRight()) {
351 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
353 return Either.right(generated.right().value());
355 byte[] value = generated.left().value();
356 artifactInfo.setPayload(value);
359 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
360 if (exportComponent.isRight()) {
361 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
362 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
363 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
364 return Either.right(responseFormat);
366 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
367 String payload = exportComponent.left().value().getMainYaml();
368 artifactInfo.setPayloadData(payload);
370 return Either.left(Either.left(artifactInfo));
373 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
374 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
375 if (interfaceName != null && operationName != null) {
376 interfaceName = interfaceName.toLowerCase();
377 operationName = operationName.toLowerCase();
381 if (artifactGenerationRequired(parent, artifactInfo)) {
382 return generateToscaArtifact(parent, artifactInfo, false, false, shouldLock, inTransaction);
384 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
386 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
388 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
389 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
390 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
391 return handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
393 return handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
395 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
405 * @param componentType
411 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact, boolean shouldLock, boolean inTransaction) {
412 if (artifactGenerationRequired(component, csarArtifact)) {
413 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false, shouldLock, inTransaction);
415 if (generated.isRight()) {
416 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
418 return Either.right(generated.right().value());
420 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
422 return downloadArtifact(csarArtifact);
425 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
426 // perform all validation in common flow
427 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, ArtifactOperation.Download, artifactId, null, null, null, null, null, parentId, containerComponentType);
428 if (result.isRight()) {
429 return Either.right(result.right().value());
431 ArtifactDefinition artifactDefinition;
432 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
433 if (insideValue.isLeft()) {
434 artifactDefinition = insideValue.left().value();
436 artifactDefinition = insideValue.right().value().getImplementation();
438 // for tosca artifacts generated on download without saving
439 if (artifactDefinition.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactDefinition.getPayloadData() != null) {
440 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
442 return downloadArtifact(artifactDefinition);
445 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId) {
447 // check artifact existence
448 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactOperation.getArtifactById(artifactId, false);
449 if (artifactResult.isRight()) {
450 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
451 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
452 log.debug("addArtifact - artifact {} not found", artifactId);
453 return Either.right(responseFormat);
456 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
457 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
458 return Either.right(responseFormat);
462 // check artifact belong to component
463 boolean found = false;
464 switch (componentType) {
467 found = checkArtifactInComponent(component, artifactId);
469 case RESOURCE_INSTANCE:
470 found = checkArtifactInResourceInstance(component, componentId, artifactId);
476 // String component =
477 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
479 String componentName = componentType.name().toLowerCase();
480 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
481 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
482 return Either.right(responseFormat);
484 return Either.left(artifactResult.left().value());
487 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
488 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
490 String artifactId = null;
493 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
494 if (payloadEither.isRight()) {
495 return Either.right(payloadEither.right().value());
497 byte[] decodedPayload = payloadEither.left().value();
498 NodeTypeEnum parentType = convertParentType(componentType);
502 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
503 if (lockComponent.isRight()) {
504 handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
505 return Either.right(lockComponent.right().value());
508 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
511 resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
515 unlockComponent(resultOp, parent, inTransaction);
522 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
523 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
525 NodeTypeEnum parentType = convertParentType(componentType);
529 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
530 if (lockComponent.isRight()) {
531 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
532 return Either.right(lockComponent.right().value());
536 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
538 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
543 unlockComponent(resultOp, parent, inTransaction);
548 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user,
549 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
551 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
553 if (payloadEither.isRight()) {
554 return Either.right(payloadEither.right().value());
556 byte[] decodedPayload = payloadEither.left().value();
558 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
561 private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
562 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
564 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
565 if (validateMd5.isRight()) {
566 ResponseFormat responseFormat = validateMd5.right().value();
567 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
568 return Either.right(responseFormat);
572 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
573 if (validateResult.isRight()) {
574 ResponseFormat responseFormat = validateResult.right().value();
575 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
576 return Either.right(validateResult.right().value());
579 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
580 if (payloadEither.isRight()) {
581 ResponseFormat responseFormat = payloadEither.right().value();
582 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
583 log.debug("Error during handle payload");
584 return Either.right(responseFormat);
587 // validate heat parameters. this part must be after the parameters are
588 // extracted in "handlePayload"
589 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
590 if (validateAndConvertHeatParamers.isRight()) {
591 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
592 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
593 log.debug("Error during handle payload");
594 return Either.right(responseFormat);
596 return payloadEither;
599 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
600 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
602 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
606 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
610 user.setUserId("UNKNOWN");
612 switch (componentTypeEnum) {
615 Resource resource = (Resource) component;
616 if (resource == null) {
617 // In that case, component ID should be instead of name
618 resource = new Resource();
619 resource.setName(componentId);
621 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
625 Service service = (Service) component;
626 if (service == null) {
627 // In that case, component ID should be instead of name
628 service = new Service();
629 service.setName(componentId);
631 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
634 case RESOURCE_INSTANCE:
635 if (resourceInstanceName == null) {
636 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
638 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
639 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
647 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
648 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
649 String resourceInstanceName = null;
650 if (resourceInstance != null) {
651 resourceInstanceName = resourceInstance.getName();
653 return resourceInstanceName;
656 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
657 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
658 // Putting together artifact info
659 String artifactData = buildAuditingArtifactData(artifactDefinition);
660 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
661 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
662 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
663 return auditingFields;
668 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
669 StringBuilder sb = new StringBuilder();
670 if (artifactDefinition != null) {
671 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
672 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
675 if (artifactDefinition.getArtifactVersion() != null) {
677 sb.append(artifactDefinition.getArtifactVersion());
682 if (artifactDefinition.getArtifactUUID() != null) {
683 sb.append(artifactDefinition.getArtifactUUID());
688 return sb.toString();
691 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperation operation) {
693 if (origMd5 != null) {
694 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
696 if (false == encodeBase64Str.equals(origMd5)) {
697 log.debug("The calculated md5 is different then the received one");
698 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
701 if (operation == ArtifactOperation.Create) {
702 log.debug("Missing md5 header during artifact create");
703 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
706 if (payload != null && payload.length != 0) {
707 log.debug("Cannot have payload while md5 header is missing");
708 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
711 return Either.left(true);
714 private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperation operation, String artifactId, User user, String interfaceName, String operationName,
715 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
717 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
718 if (validateAndSetArtifactname.isRight()) {
719 return Either.right(validateAndSetArtifactname.right().value());
721 Either<ArtifactDefinition, ResponseFormat> artifactById = fetchCurrentArtifact(operation, artifactId);
722 if (artifactById.isRight()) {
723 return Either.right(artifactById.right().value());
725 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
726 if (operationName != null && interfaceName != null) {
727 operationName = operationName.toLowerCase();
728 interfaceName = interfaceName.toLowerCase();
730 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
731 if (logicalNameStatus.isRight()) {
732 return Either.right(logicalNameStatus.right().value());
734 // This is a patch to block possibility of updating service api fields
735 // through other artifacts flow
737 if (!operation.equals(ArtifactOperation.Create)) {
738 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
740 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
743 composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
744 if (currentArtifactInfo != null) {
745 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
748 // artifactGroupType is not allowed to be updated
749 if (!operation.equals(ArtifactOperation.Create)) {
750 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
751 if (validateGroupType.isRight()) {
752 return Either.right(validateGroupType.right().value());
756 NodeTypeEnum parentType = convertParentType(componentType);
759 boolean isCreate = operation.equals(ArtifactOperation.Create);
761 if (isDeploymentArtifact(artifactInfo)) {
762 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
763 if (deploymentValidationResult.isRight()) {
764 return Either.right(deploymentValidationResult.right().value());
767 artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
770 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
771 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
775 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
776 if (descriptionResult.isRight()) {
777 return Either.right(descriptionResult.right().value());
780 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
781 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
782 if (validateServiceApiType.isRight()) {
783 return Either.right(validateServiceApiType.right().value());
785 // Change of type is not allowed and should be ignored
787 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
789 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
790 if (validateUrl.isRight()) {
791 return Either.right(validateUrl.right().value());
794 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
795 if (validateUpdate.isRight()) {
796 log.debug("serviceApi first update cnnot be without payload.");
797 return Either.right(validateUpdate.right().value());
800 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
801 if (validateArtifactType.isRight()) {
802 return Either.right(validateArtifactType.right().value());
804 if (artifactInfo.getApiUrl() != null) {
805 artifactInfo.setApiUrl(null);
806 log.error("Artifact URL cannot be set through this API - ignoring");
809 if (artifactInfo.getServiceApi() != null) {
810 if (artifactInfo.getServiceApi()) {
811 artifactInfo.setServiceApi(false);
812 log.error("Artifact service API flag cannot be changed - ignoring");
817 return Either.left(artifactInfo);
820 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
821 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
822 return NodeTypeEnum.Resource;
823 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
824 return NodeTypeEnum.ResourceInstance;
826 return NodeTypeEnum.Service;
830 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
831 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
832 NodeTypeEnum parentType = convertParentType(componentType);
835 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
836 if (lockComponent.isRight()) {
837 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
838 return Either.right(lockComponent.right().value());
841 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
842 Either<ArtifactDefinition, Operation> insideEither = null;
843 StorageOperationStatus error = null;
844 boolean isLeft = false;
845 ArtifactDefinition artifactDefinition = null;
846 Integer artifactParentsCount = 1;
848 if (interfaceType != null && operationName != null) {
849 log.debug("Try to delete inteface lifecycle artifact {}", artifactId);
851 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.deleteInterfaceOperation(parentId, interfaceType, UniqueIdBuilder.buildOperationByInterfaceUniqueId(parentId, interfaceType, operationName),
853 isLeft = result.isLeft();
855 artifactDefinition = result.left().value().getImplementation();
856 insideEither = Either.right(result.left().value());
859 log.debug("Try to delete artifact, get parents {}", artifactId);
861 Either<Integer, StorageOperationStatus> parentsOfArtifact = artifactOperation.getParentsOfArtifact(artifactId, parentType);
862 if (parentsOfArtifact.isRight()) {
863 log.debug("Failed to delete entry on graph for artifact {}", artifactId);
864 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(parentsOfArtifact.right().value()), "");
865 resultOp = Either.right(responseFormat);
868 artifactParentsCount = parentsOfArtifact.left().value();
869 log.debug("Number of parents nodes on graph for artifact {} is {}", artifactId, artifactParentsCount);
871 Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.removeArifactFromResource(parentId, artifactId, parentType, false, true);
872 isLeft = result.isLeft();
874 log.debug("Artifact removed from graph {}", artifactId);
876 artifactDefinition = result.left().value();
877 insideEither = Either.left(result.left().value());
879 error = result.right().value();
884 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
886 StorageOperationStatus deleteIfNotOnGraph = StorageOperationStatus.OK;
887 if (artifactParentsCount < 2) {
888 log.debug("Number of parent nodes is 1. Need to delete from ES {}", artifactId);
889 deleteIfNotOnGraph = deleteIfNotOnGraph(artifactId, artifactDefinition.getEsId(), true);
891 if (deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
892 if (artifactDefinition.getMandatory() || artifactDefinition.getServiceApi()) {
893 log.debug("Artifact is mandatory or service API. Clean all fields for {}", artifactId);
894 artifactDefinition.setEsId("");
895 artifactDefinition.setArtifactName("");
896 artifactDefinition.setDescription("");
897 artifactDefinition.setApiUrl("");
898 artifactDefinition.setArtifactChecksum("");
899 setDefaultArtifactTimeout(artifactDefinition.getArtifactGroupType(), artifactDefinition);
900 artifactDefinition.setArtifactUUID("");
901 long time = System.currentTimeMillis();
902 artifactDefinition.setPayloadUpdateDate(time);
903 artifactDefinition.setHeatParameters(null);
904 artifactDefinition.setHeatParamsUpdateDate(null);
905 Either<ArtifactDefinition, StorageOperationStatus> resStatus = null;
906 if (artifactParentsCount < 2) {
907 log.debug("Only one parent , clean existing placeholder for {}", artifactId);
908 resStatus = artifactOperation.updateArifactOnResource(artifactDefinition, parentId, artifactId, parentType, true);
910 log.debug("more than one parent , create new placeholder for {}", artifactId);
911 artifactDefinition.setUniqueId(null);
912 resStatus = artifactOperation.addArifactToComponent(artifactDefinition, parentId, parentType, true, true);
914 if (resStatus.isRight()) {
915 log.debug("Failed to clean placeholder for {}", artifactId);
916 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(resStatus.right().value()), artifactDefinition.getArtifactDisplayName());
917 resultOp = Either.right(responseFormat);
919 log.debug("Placeholder was cleaned for {}", artifactId);
921 ArtifactDefinition artifactUfterChange = resStatus.left().value();
923 insideEither = Either.left(artifactUfterChange);
924 resultOp = Either.left(insideEither);
927 log.debug("Artifact isn't mandatory/service API. Removed. {}", artifactId);
928 resultOp = Either.left(insideEither);
932 log.debug("failed to delete artifact from ES {} status {}", artifactId, deleteIfNotOnGraph);
933 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(deleteIfNotOnGraph), artifactDefinition.getArtifactDisplayName());
934 resultOp = Either.right(responseFormat);
937 log.debug("Failed to delete entry on graph for artifact {}", artifactId);
938 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), "");
939 resultOp = Either.right(responseFormat);
941 handleAuditing(auditingAction, parent, parentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
945 unlockComponent(resultOp, parent, inTransaction);
951 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
952 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
953 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, false);
954 if (artifactById.isRight()) {
955 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
956 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
957 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
958 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
959 return Either.right(responseFormat);
961 ArtifactDefinition artifactDefinition = artifactById.left().value();
962 if (artifactDefinition == null) {
963 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
964 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
965 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
966 return Either.right(responseFormat);
968 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
969 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
970 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
971 return Either.left(insideEither);
974 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(ArtifactOperation operation, String artifactId) {
975 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, true);
976 if (!operation.equals(ArtifactOperation.Create) && artifactById.isRight()) {
977 // in case of update artifact must be
978 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
979 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
980 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
981 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
983 if (operation.equals(ArtifactOperation.Create) && artifactById.isLeft()) {
984 log.debug("Artifact {} already exist", artifactId);
985 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
987 ArtifactDefinition currentArtifactInfo = null;
988 if (artifactById.isLeft()) {
989 // get previous value
990 currentArtifactInfo = artifactById.left().value();
992 return Either.left(currentArtifactInfo);
995 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperation operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
996 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
997 String artifactLabel = artifactInfo.getArtifactLabel();
999 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1000 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel");
1001 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1002 log.debug("missing artifact logical name for component {}", componentId);
1003 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1005 if (operation.equals(ArtifactOperation.Create) && !artifactInfo.getMandatory()) {
1007 if (operationName != null) {
1008 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1009 log.debug("artifact label cannot be set {}", artifactLabel);
1010 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1012 artifactLabel = operationName;
1015 String displayName = artifactInfo.getArtifactDisplayName();
1016 if (displayName == null || displayName.isEmpty())
1017 displayName = artifactLabel;
1018 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1019 artifactInfo.setArtifactDisplayName(displayName);
1021 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1022 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1023 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1025 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1027 if (artifactLabel.isEmpty()) {
1028 log.debug("missing normalized artifact logical name for component {}", componentId);
1029 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1032 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1033 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1034 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1036 if (!validateLabelUniqueness(componentId, artifactLabel, componentType, inTransaction)) {
1037 log.debug("Non unique Artifact label : {}", artifactLabel);
1038 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1041 artifactInfo.setArtifactLabel(artifactLabel);
1043 if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
1044 log.info("Logical artifact's name cannot be changed {}", artifactId);
1045 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1047 return Either.left(ActionStatus.OK);
1050 private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType, boolean inTransaction) {
1051 boolean isUnique = true;
1052 NodeTypeEnum parentType;
1053 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1054 parentType = NodeTypeEnum.Resource;
1056 parentType = NodeTypeEnum.Service;
1058 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
1059 if (artifacts.isLeft()) {
1060 for (String label : artifacts.left().value().keySet()) {
1061 if (label.equals(artifactLabel)) {
1067 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1068 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, inTransaction);
1069 if (allInterfacesOfResource.isLeft()) {
1070 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1071 for (Operation operation : interace.getOperations().values()) {
1072 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1083 // ***************************************************************
1085 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1086 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1088 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1089 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1090 Either<ArtifactDefinition, Operation> insideEither = null;
1092 if (artifactData == null) {
1093 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact");
1094 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1095 log.debug("Failed to create artifact object for ES.");
1096 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1097 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1098 resultOp = Either.right(responseFormat);
1102 // set on graph object id of artifact in ES!
1103 artifactInfo.setEsId(artifactData.getId());
1105 boolean isLeft = false;
1106 String artifactUniqueId = null;
1107 ArtifactDefinition artifactDefinition = null;
1108 StorageOperationStatus error = null;
1109 if (interfaceType != null && operationName != null) {
1110 // lifecycle artifact
1111 Operation operation = convertToOperation(artifactInfo, operationName);
1113 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1115 isLeft = result.isLeft();
1117 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1118 artifactDefinition = result.left().value().getImplementation();
1120 insideEither = Either.right(result.left().value());
1121 resultOp = Either.left(insideEither);
1123 error = result.right().value();
1126 // information/deployment/api aritfacts
1127 log.debug("Try to create entry on graph");
1128 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1129 Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.addArifactToComponent(artifactInfo, parentId, nodeType, true, true);
1131 isLeft = result.isLeft();
1133 artifactUniqueId = result.left().value().getUniqueId();
1134 artifactDefinition = result.left().value();
1136 insideEither = Either.left(result.left().value());
1137 resultOp = Either.left(insideEither);
1139 error = result.right().value();
1143 boolean res = saveArtifacts(artifactData, parentId, false);
1144 // String uniqueId = artifactDefinition.getUniqueId();
1147 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1149 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1150 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, null);
1153 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Upload Artifact");
1154 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1155 log.debug("Failed to save the artifact.");
1156 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1157 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, null);
1159 resultOp = Either.right(responseFormat);
1163 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1164 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1165 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1166 resultOp = Either.right(responseFormat);
1172 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1174 Either<Boolean, ResponseFormat> result = Either.left(true);
1175 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1177 validateArtifactTypeExists(responseWrapper, artifactInfo);
1179 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1181 Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1183 if (responseWrapper.isEmpty()) {
1184 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1187 if (responseWrapper.isEmpty()) {
1188 // Common code for all types
1189 // not allowed to change artifactType
1191 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1192 if (validateServiceApiType.isRight()) {
1193 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1197 if (responseWrapper.isEmpty()) {
1198 if (parentType.equals(NodeTypeEnum.Resource)) {
1199 // if (parentComponent instanceof Resource) {
1200 Resource resource = (Resource) parentComponent;
1201 ResourceTypeEnum resourceType = resource.getResourceType();
1202 DeploymentArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1203 if (config == null) {
1204 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1206 List<String> myList = config.getValidForResourceTypes();
1207 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1208 if (either.isRight()) {
1209 responseWrapper.setInnerElement(either.right().value());
1214 if (responseWrapper.isEmpty()) {
1215 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1218 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1219 String artifactName = artifactInfo.getArtifactName();
1220 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1221 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1225 if (responseWrapper.isEmpty()) {
1226 switch (artifactType) {
1230 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1234 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1235 artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
1238 case DCAE_INVENTORY_TOSCA:
1239 case DCAE_INVENTORY_JSON:
1240 case DCAE_INVENTORY_POLICY:
1241 // Validation is done in handle payload.
1242 case DCAE_INVENTORY_DOC:
1243 case DCAE_INVENTORY_BLUEPRINT:
1244 case DCAE_INVENTORY_EVENT:
1245 // No specific validation
1247 artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
1253 if (!responseWrapper.isEmpty()) {
1254 result = Either.right(responseWrapper.getInnerElement());
1259 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts) {
1260 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1261 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1262 responseWrapper.setInnerElement(responseFormat);
1263 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1267 private Map<String, DeploymentArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1268 Map<String, DeploymentArtifactTypeConfig> resourceDeploymentArtifacts = null;
1269 if (parentType.equals(NodeTypeEnum.Resource)) {
1270 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1271 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1272 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1274 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1276 return resourceDeploymentArtifacts;
1279 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1280 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1281 if (artifactType == null) {
1282 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.GENERAL_ERROR);
1283 responseWrapper.setInnerElement(responseFormat);
1284 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1288 private DeploymentArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1289 DeploymentArtifactTypeConfig retConfig = null;
1290 String fileType = artifactType.getType();
1291 if (parentType.equals(NodeTypeEnum.Resource)) {
1292 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1293 } else if (parentType.equals(NodeTypeEnum.Service)) {
1294 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1295 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1296 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1301 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1302 // extract heat parameters
1303 if (artifactInfo.getPayloadData() != null) {
1304 String heatDecodedPayload = GeneralUtility.isBase64Encoded(artifactInfo.getPayloadData()) ? new String(Base64.decodeBase64(artifactInfo.getPayloadData())) : new String(artifactInfo.getPayloadData());
1305 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1306 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1307 log.info("failed to parse heat parameters ");
1308 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1309 return Either.right(responseFormat);
1310 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1311 artifactInfo.setHeatParameters(heatParameters.left().value());
1314 return Either.left(true);
1319 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1320 String fileType = artifactType.getType();
1321 List<String> acceptedTypes = null;
1322 DeploymentArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1323 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1324 log.debug("parent type of artifact can be either resource or service");
1325 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1329 if (deploymentAcceptedTypes == null) {
1330 log.debug("parent type of artifact can be either resource or service");
1331 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1334 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1337 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1339 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1340 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1341 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1342 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1345 String artifactName = artifactInfo.getArtifactName();
1346 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1347 // Pavel - File extension validation is case-insensitive - Ella,
1349 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1350 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1351 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1356 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1358 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1359 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1360 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1362 if (errorWrapper.isEmpty()) {
1363 validateValidYaml(errorWrapper, artifactInfo);
1366 if (errorWrapper.isEmpty()) {
1367 // Validate Heat Exist
1368 validateHeatExist(artifactInfo.getUniqueId(), errorWrapper, heatMDWrapper, getDeploymentArtifacts(parentComponent, parentType, parentId));
1371 if (errorWrapper.isEmpty() && isCreate) {
1372 // Validate Only Single HeatEnv Artifact
1373 validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1376 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1377 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1380 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1381 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1385 Either<Boolean, ResponseFormat> eitherResponse;
1386 if (errorWrapper.isEmpty()) {
1387 eitherResponse = Either.left(true);
1389 eitherResponse = Either.right(errorWrapper.getInnerElement());
1391 return eitherResponse;
1394 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1395 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1396 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1397 if (fillArtifactPayload.isRight()) {
1398 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1399 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1402 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1406 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1407 Either<Boolean, ResponseFormat> result = Either.left(true);
1408 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1409 // Either<ESArtifactData, ResourceUploadStatus> eitherArtifactData =
1410 // esCatalogDao.getArtifact(artifactMD.getEsId());
1411 if (eitherArtifactData.isLeft()) {
1412 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1413 if (!GeneralUtility.isBase64Encoded(data)) {
1414 data = Base64.encodeBase64(data);
1416 payloadWrapper.setInnerElement(data);
1418 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1419 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1420 result = Either.right(responseFormat);
1426 @SuppressWarnings("unchecked")
1427 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
1429 String envPayload = (GeneralUtility.isBase64Encoded(envArtifact.getPayloadData())) ? new String(Base64.decodeBase64(envArtifact.getPayloadData())) : new String(envArtifact.getPayloadData());
1430 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
1432 String heatDecodedPayload = (GeneralUtility.isBase64Encoded(heatPayloadData)) ? new String(Base64.decodeBase64(heatPayloadData)) : new String(heatPayloadData);
1433 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
1435 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
1436 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
1437 if (eitherHeatEnvProperties.isRight()) {
1438 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
1439 errorWrapper.setInnerElement(responseFormat);
1440 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
1441 } else if (eitherHeatProperties.isRight()) {
1442 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1443 errorWrapper.setInnerElement(responseFormat);
1444 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1446 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
1447 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
1448 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
1449 if (heatEnvPropertiesKeys.size() > 0) {
1450 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1451 errorWrapper.setInnerElement(responseFormat);
1456 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
1457 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
1458 boolean isYamlValid = yamlConvertor.isValidYaml(artifactInfo.getPayloadData());
1460 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
1461 errorWrapper.setInnerElement(responseFormat);
1462 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
1466 public boolean isValidXml(byte[] xmlToParse) {
1467 XMLReader parser = new SAXParser();
1468 boolean isXmlValid = true;
1470 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
1471 } catch (IOException | SAXException e) {
1477 public boolean isValidJson(byte[] jsonToParse) {
1478 String parsed = new String(jsonToParse);
1480 gson.fromJson(parsed, Object.class);
1481 } catch (Exception e) {
1487 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
1488 boolean typeArtifactFound = false;
1489 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
1490 // (parentType == NodeTypeEnum.Resource) ?
1491 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
1492 // parentComponent).iterator()
1493 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
1495 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
1497 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
1498 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
1499 typeArtifactFound = (foundArtifactType == allowedArtifactType);
1501 if (typeArtifactFound) {
1502 String parentName = parentComponent.getName();
1503 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
1505 errorWrapper.setInnerElement(responseFormat);
1506 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
1511 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
1512 boolean artifactNameFound = false;
1513 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
1514 // (parentType == NodeTypeEnum.Resource) ?
1515 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
1516 // parentComponent).iterator()
1517 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
1519 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
1521 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
1522 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
1524 if (artifactNameFound) {
1525 String parentName = parentComponent.getName();
1526 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
1528 errorWrapper.setInnerElement(responseFormat);
1529 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
1534 private void validateHeatExist(String heatEnvId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, Collection<ArtifactDefinition> parentDeploymentArtifacts) {
1535 boolean heatFound = false;
1536 Either<ArtifactDefinition, StorageOperationStatus> res = artifactOperation.getHeatArtifactByHeatEnvId(heatEnvId, true);
1537 if (res.isRight()) {
1540 ArtifactDefinition heatArtifact = res.left().value();
1541 Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
1542 while (!heatFound && parentArtifactsItr.hasNext()) {
1543 ArtifactDefinition currArtifact = parentArtifactsItr.next();
1544 if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
1546 heatArtifactMDWrapper.setInnerElement(currArtifact);
1547 log.trace("In validateHeatExist found artifact {}", currArtifact);
1549 * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
1550 * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
1555 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
1556 errorWrapper.setInnerElement(responseFormat);
1557 log.debug("Can't create heat env artifact because No heat Artifact exist.");
1562 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1563 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
1564 // timeout > 0 for HEAT artifacts
1565 Integer timeout = artifactInfo.getTimeout();
1566 Integer defaultTimeout = (isCreate) ? defaultHeatTimeout : currentArtifact.getTimeout();
1567 if (timeout == null) {
1568 artifactInfo.setTimeout(defaultTimeout);
1569 // HEAT artifact but timeout is invalid
1570 } else if (timeout < 1) {
1571 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
1574 // US649856 - Allow several HEAT files on Resource
1576 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
1577 * Either.right(errorWrapper.getInnerElement()); } }
1580 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
1581 return Either.left(true);
1584 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
1585 String listToString = (typeList != null) ? typeList.toString() : "";
1586 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
1587 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
1588 String resourceTypeName = resourceType.name();
1589 if (typeList != null && typeList.contains(resourceTypeName)) {
1590 either = Either.left(true);
1595 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
1596 if (artifactInfo.getHeatParameters() != null) {
1597 for (HeatParameterDefinition heatParam : artifactInfo.getHeatParameters()) {
1598 String parameterType = heatParam.getType();
1599 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
1600 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
1601 if (heatParameterType == null) {
1602 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
1603 return Either.right(responseFormat);
1606 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
1607 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
1608 log.debug("Heat parameter {} is invalid. Status is: {}", heatParam.getName(), validateAndUpdateProperty);
1609 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
1610 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
1611 return Either.right(responseFormat);
1615 return Either.left(artifactInfo);
1618 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
1619 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
1620 if (parentComponent.getDeploymentArtifacts() != null && ciId != null) {
1621 if (NodeTypeEnum.ResourceInstance == parentType) {
1622 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
1623 if (getRI.isRight()) {
1624 return deploymentArtifacts;
1626 ComponentInstance ri = getRI.left().value();
1627 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
1629 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
1632 return deploymentArtifacts;
1635 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
1636 // on create if null add informational to current
1637 if (artifactInfo.getArtifactGroupType() == null) {
1638 artifactInfo.setArtifactGroupType(type);
1640 if (artifactInfo.getUniqueId() != null) {
1641 log.error("artifact uniqid cannot be set ignoring");
1643 artifactInfo.setUniqueId(null);
1645 if (artifactInfo.getArtifactRef() != null) {
1646 log.error("artifact ref cannot be set ignoring");
1648 artifactInfo.setArtifactRef(null);
1650 if (artifactInfo.getArtifactRepository() != null) {
1651 log.error("artifact repository cannot be set ignoring");
1653 artifactInfo.setArtifactRepository(null);
1655 if (artifactInfo.getUserIdCreator() != null) {
1656 log.error("creator uuid cannot be set ignoring");
1658 artifactInfo.setArtifactCreator(user.getUserId());
1660 if (artifactInfo.getUserIdLastUpdater() != null) {
1661 log.error("userId of last updater cannot be set ignoring");
1663 artifactInfo.setUserIdLastUpdater(user.getUserId());
1665 if (artifactInfo.getCreatorFullName() != null) {
1666 log.error("creator Full name cannot be set ignoring");
1668 String fullName = user.getFirstName() + " " + user.getLastName();
1669 artifactInfo.setUpdaterFullName(fullName);
1671 if (artifactInfo.getUpdaterFullName() != null) {
1672 log.error("updater Full name cannot be set ignoring");
1674 artifactInfo.setUpdaterFullName(fullName);
1676 if (artifactInfo.getCreationDate() != null) {
1677 log.error("Creation Date cannot be set ignoring");
1679 long time = System.currentTimeMillis();
1680 artifactInfo.setCreationDate(time);
1682 if (artifactInfo.getLastUpdateDate() != null) {
1683 log.error("Last Update Date cannot be set ignoring");
1685 artifactInfo.setLastUpdateDate(time);
1687 if (artifactInfo.getEsId() != null) {
1688 log.error("es id cannot be set ignoring");
1690 artifactInfo.setEsId(null);
1694 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) {
1695 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactId, true);
1696 if (isCreate == false && artifactById.isRight()) {
1697 // in case of update artifact must be
1698 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
1699 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1700 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1701 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1703 if (isCreate && artifactById.isLeft()) {
1704 log.debug("Artifact {} already exist", artifactId);
1705 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1707 ArtifactDefinition currentArtifactInfo = null;
1708 if (artifactById.isLeft()) {
1709 // get previous value
1710 currentArtifactInfo = artifactById.left().value();
1712 return Either.left(currentArtifactInfo);
1715 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String resourceId, boolean isCreate, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName, ArtifactDefinition currentArtifactInfo,
1716 NodeTypeEnum parentType) {
1717 String artifactLabel = artifactInfo.getArtifactLabel();
1719 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1720 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Update / Upload", "artifactLabel");
1721 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1722 log.debug("missing artifact logical name for component {}", resourceId);
1723 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1725 if (isCreate && !artifactInfo.getMandatory()) {
1727 if (operationName != null) {
1728 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1729 log.debug("artifact label cannot be set {}", artifactLabel);
1730 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1732 artifactLabel = operationName;
1735 String displayName = ValidationUtils.cleanArtifactDisplayName(artifactLabel);
1736 artifactInfo.setArtifactDisplayName(displayName);
1738 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1739 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1740 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1742 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1744 if (artifactLabel.isEmpty()) {
1745 log.debug("missing normalized artifact logical name for component {}", resourceId);
1746 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1749 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1750 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1751 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1753 if (!validateLabelUniqueness(resourceId, artifactLabel, parentType)) {
1754 log.debug("Non unique Artifact label : {}", artifactLabel);
1755 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1758 artifactInfo.setArtifactLabel(artifactLabel);
1760 if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
1761 log.info("Logical artifact's name cannot be changed {}", artifactId);
1762 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1764 return Either.left(ActionStatus.OK);
1767 private boolean validateLabelUniqueness(String parentId, String artifactLabel, NodeTypeEnum parentType) {
1768 boolean isUnique = true;
1769 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, true);
1770 if (artifacts.isLeft()) {
1771 for (String label : artifacts.left().value().keySet()) {
1772 if (label.equals(artifactLabel)) {
1778 if (parentType.equals(NodeTypeEnum.Resource)) {
1779 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true);
1780 if (allInterfacesOfResource.isLeft()) {
1781 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1782 for (Operation operation : interace.getOperations().values()) {
1783 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1794 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
1795 String id = artifactId;
1796 if (artifactId == null || artifactId.isEmpty()) {
1797 String uniqueId = null;
1798 if (interfaceName != null && operationName != null) {
1799 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
1801 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
1803 artifactInfo.setUniqueId(uniqueId);
1804 artifactInfo.setEsId(uniqueId);
1807 artifactInfo.setUniqueId(artifactId);
1808 artifactInfo.setEsId(artifactId);
1813 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1814 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
1815 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeMissingArtifactInformationError, "Artifact Upload / Update");
1816 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1817 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
1818 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
1821 boolean artifactTypeExist = false;
1822 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
1823 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
1825 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
1826 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
1829 allArtifactTypes = elementOperation.getAllArtifactTypes();
1831 if (allArtifactTypes.isRight()) {
1832 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidConfigurationError, "Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
1833 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
1834 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
1835 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
1838 for (ArtifactType type : allArtifactTypes.left().value()) {
1839 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
1840 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
1841 artifactTypeExist = true;
1846 if (!artifactTypeExist) {
1847 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeInvalidTypeError, "Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
1848 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
1849 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
1850 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1853 return Either.left(ActionStatus.OK);
1856 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1858 Map<String, DeploymentArtifactTypeConfig> deploymentArtifacts = null;
1859 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
1861 if (parentType.equals(NodeTypeEnum.Service)) {
1862 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1863 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1864 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1866 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1868 if (deploymentArtifacts != null) {
1869 for (String artifactType : deploymentArtifacts.keySet()) {
1870 ArtifactType artifactT = new ArtifactType();
1871 artifactT.setName(artifactType);
1872 artifactTypes.add(artifactT);
1874 return Either.left(artifactTypes);
1876 return Either.right(ActionStatus.GENERAL_ERROR);
1881 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
1882 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
1883 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
1885 return Either.left(true);
1889 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
1890 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
1891 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
1894 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
1895 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
1896 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
1898 artifactInfo.setArtifactName(normalizeFileName);
1900 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
1901 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
1904 return Either.left(true);
1907 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
1908 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
1909 log.info("artifact type is missing operation ignored");
1910 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
1913 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
1914 log.info("artifact type cannot be changed operation ignored");
1915 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1917 return Either.left(true);
1920 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
1921 if (artifactInfo.getArtifactGroupType() == null) {
1922 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
1925 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
1926 log.info("artifact group type cannot be changed. operation failed");
1927 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1929 return Either.left(artifactInfo);
1932 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
1934 // on update if null add informational to current
1935 if (currentArtifact.getArtifactGroupType() == null && type != null) {
1936 currentArtifact.setArtifactGroupType(type);
1939 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
1940 log.error("artifact uniqid cannot be set ignoring");
1942 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
1944 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
1945 log.error("artifact ref cannot be set ignoring");
1947 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
1949 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
1950 log.error("artifact repository cannot be set ignoring");
1952 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
1954 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
1955 log.error("creator uuid cannot be set ignoring");
1957 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
1959 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
1960 log.error("artifact creator cannot be set ignoring");
1962 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
1964 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
1965 log.error("userId of last updater cannot be set ignoring");
1967 artifactInfo.setUserIdLastUpdater(user.getUserId());
1969 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
1970 log.error("creator Full name cannot be set ignoring");
1972 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
1974 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
1975 log.error("updater Full name cannot be set ignoring");
1977 String fullName = user.getFirstName() + " " + user.getLastName();
1978 artifactInfo.setUpdaterFullName(fullName);
1980 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
1981 log.error("Creation Date cannot be set ignoring");
1983 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
1985 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
1986 log.error("Last Update Date cannot be set ignoring");
1988 long time = System.currentTimeMillis();
1989 artifactInfo.setLastUpdateDate(time);
1991 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
1992 log.error("es id cannot be set ignoring");
1994 artifactInfo.setEsId(currentArtifact.getUniqueId());
1996 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
1997 log.error(" Artifact Display Name cannot be set ignoring");
1999 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2001 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2002 log.debug("serviceApi cannot be set. ignoring.");
2004 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2006 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2007 log.debug("artifact group cannot be set. ignoring.");
2009 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2011 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2013 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2014 log.debug("artifact UUID cannot be set. ignoring.");
2016 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2018 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2019 checkAndSetUnupdatableHeatParams(artifactInfo.getHeatParameters(), currentArtifact.getHeatParameters());
2023 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2025 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2026 for (HeatParameterDefinition parameter : heatParameters) {
2027 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2029 if (currentParam != null) {
2031 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2032 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2033 parameter.setName(currentParam.getName());
2035 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2036 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2037 parameter.setDefaultValue(currentParam.getDefaultValue());
2039 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2040 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2041 parameter.setType(currentParam.getType());
2043 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2044 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2045 parameter.setDescription(currentParam.getDescription());
2048 // check and set current value
2049 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2050 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2051 parameter.setCurrentValue(currentParam.getDefaultValue());
2057 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2059 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2060 for (HeatParameterDefinition param : currentParameters) {
2061 currentParamsMap.put(param.getUniqueId(), param);
2063 return currentParamsMap;
2066 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2067 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2068 log.debug("Artifact url cannot be empty.");
2069 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2071 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2073 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2074 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2076 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2077 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2080 return Either.left(true);
2083 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2084 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2085 log.debug("Artifact description cannot be empty.");
2086 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2088 String description = artifactInfo.getDescription();
2089 description = ValidationUtils.removeNoneUtf8Chars(description);
2090 description = ValidationUtils.normaliseWhitespace(description);
2091 description = ValidationUtils.stripOctets(description);
2092 description = ValidationUtils.removeHtmlTagsOnly(description);
2093 if (!ValidationUtils.validateIsEnglish(description)) {
2094 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2096 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2097 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2099 artifactInfo.setDescription(description);
2100 return Either.left(true);
2103 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2104 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2105 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2106 String prevArtifactId = null;
2107 String currArtifactId = artifactId;
2109 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2110 Either<ArtifactDefinition, Operation> insideEither = null;
2112 if (artifactData == null) {
2113 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact");
2114 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2115 log.debug("Failed to create artifact object for ES.");
2116 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2117 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2118 resultOp = Either.right(responseFormat);
2121 log.debug("Try to update entry on graph");
2122 String artifactUniqueId = null;
2123 ArtifactDefinition artifactDefinition = null;
2124 StorageOperationStatus error = null;
2126 boolean isLeft = false;
2127 if (interfaceType != null && operationName != null) {
2128 // lifecycle artifact
2129 Operation operation = convertToOperation(artifactInfo, operationName);
2131 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2133 isLeft = result.isLeft();
2135 artifactUniqueId = result.left().value().getUniqueId();
2136 artifactDefinition = result.left().value().getImplementation();
2138 insideEither = Either.right(result.left().value());
2139 resultOp = Either.left(insideEither);
2141 error = result.right().value();
2145 NodeTypeEnum convertParentType = convertParentType(componentType);
2146 Either<ArtifactDefinition, StorageOperationStatus> result = artifactOperation.updateArifactOnResource(artifactInfo, parentId, artifactId, convertParentType, true);
2147 isLeft = result.isLeft();
2149 artifactUniqueId = result.left().value().getUniqueId();
2150 artifactDefinition = result.left().value();
2152 insideEither = Either.left(result.left().value());
2153 resultOp = Either.left(insideEither);
2155 error = result.right().value();
2159 log.debug("Enty on graph is updated. Update artifact in ES");
2161 // Changing previous and current artifactId for auditing
2162 prevArtifactId = currArtifactId;
2163 currArtifactId = artifactDefinition.getUniqueId();
2165 if (!artifactDefinition.getUniqueId().equals(artifactId)) {
2166 // different ids ==> artifact node was cloned .
2167 // if no data in request get from ES
2168 if (decodedPayload == null) {
2169 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2170 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactId);
2171 // Either<ESArtifactData, ResourceUploadStatus>
2172 // artifactfromES = daoUploader.getArtifact(artifactId);
2173 if (artifactFromCassandra.isRight()) {
2174 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2175 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2176 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2177 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2178 resultOp = Either.right(responseFormat);
2181 // clone data to new artifact
2182 artifactData.setData(artifactFromCassandra.left().value().getData());
2185 artifactData.setId(artifactDefinition.getUniqueId());
2186 // create new entry in ES
2188 if (artifactData.getData() != null) {
2189 res = saveArtifacts(artifactData, parentId, false);
2190 // set on graph object id of artifact in ES!
2192 artifactInfo.setEsId(artifactData.getId());
2193 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true);
2194 if (updateArifactRes.isRight()) {
2195 log.debug("Failed to update artifact on graph - {}", artifactId);
2196 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
2197 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2198 resultOp = Either.right(responseFormat);
2202 insideEither = Either.left(updateArifactRes.left().value());
2203 resultOp = Either.left(insideEither);
2209 if (artifactData.getData() != null) {
2210 // override artifact in ES
2211 res = saveArtifacts(artifactData, parentId, true);
2212 if (res && artifactDefinition.getMandatory()) {
2213 artifactInfo.setEsId(artifactData.getId());
2214 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(artifactInfo, true);
2215 if (updateArifactRes.isRight()) {
2216 log.debug("Failed to update artifact on graph - {}", artifactId);
2217 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()), artifactId);
2218 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2219 resultOp = Either.right(responseFormat);
2227 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2228 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2229 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2230 // resultOp = Either.left(result.left().value());
2233 BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeDaoSystemError, "Update Artifact");
2234 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2235 log.debug("Failed to save the artifact.");
2236 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2237 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2238 resultOp = Either.right(responseFormat);
2242 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactDisplayName());
2243 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
2244 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2245 resultOp = Either.right(responseFormat);
2252 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2253 log.trace("Starting payload handling");
2254 byte[] payload = artifactInfo.getPayloadData();
2255 byte[] decodedPayload = null;
2257 if (payload != null && payload.length != 0) {
2259 decodedPayload = Base64.decodeBase64(payload);
2260 if (decodedPayload.length == 0) {
2261 log.debug("Failed to decode the payload.");
2262 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2263 return Either.right(responseFormat);
2266 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2267 artifactInfo.setArtifactChecksum(checkSum);
2268 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2270 // Specific payload validations of different types
2271 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2272 if (isDeploymentArtifact(artifactInfo)) {
2273 log.trace("Starting deployment artifacts payload validation");
2274 String artifactType = artifactInfo.getArtifactType();
2275 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2276 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2277 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2278 if (isValidPayload.isLeft()) {
2279 isValidPayload = extractHeatParameters(artifactInfo);
2281 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2282 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2283 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType)) {
2284 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2286 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2288 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)) {
2289 String artifactFileName = artifactInfo.getArtifactName();
2290 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2291 switch (fileExtension) {
2293 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2296 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2300 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2305 if (isValidPayload.isRight()) {
2306 ResponseFormat responseFormat = isValidPayload.right().value();
2307 return Either.right(responseFormat);
2310 } // null/empty payload is normal if called from metadata update ONLY.
2311 // The validation of whether this is metadata/payload update case is
2312 // currently done separately
2314 if (!isArtifactMetadataUpdate) {
2315 log.debug("Payload is missing.");
2316 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2317 return Either.right(responseFormat);
2320 log.trace("Ended payload handling");
2321 return Either.left(decodedPayload);
2324 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] payload, String artifactType) {
2325 // Basic YAML validation
2326 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2327 if (!yamlToObjectConverter.isValidYaml(payload)) {
2328 log.debug("Invalid YAML format");
2329 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2330 return Either.right(responseFormat);
2332 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2333 // HEAT specific YAML validation
2334 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(payload, DeploymentArtifactHeatConfiguration.class);
2335 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null || heatConfiguration.getResources() == null) {
2336 log.debug("HEAT doesn't contain required \"heat_template_version\" and \"resources\" sections ");
2337 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2338 return Either.right(responseFormat);
2342 return Either.left(true);
2345 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2346 Either<Boolean, ResponseFormat> res = Either.left(true);
2347 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2348 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2349 log.debug("Invalid YAML format");
2350 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2351 res = Either.right(responseFormat);
2357 private Either<Boolean, ResponseFormat> validateYangPayload(byte[] payload, String artifactType) {
2358 boolean isXmlValid = isValidXml(payload);
2360 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2361 log.debug("Invalid XML content");
2362 return Either.right(responseFormat);
2364 return Either.left(true);
2367 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2368 boolean isJsonValid = isValidJson(payload);
2370 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2371 log.debug("Invalid JSON content");
2372 return Either.right(responseFormat);
2374 return Either.left(true);
2377 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2378 if (opState == null || opState.isRight()) {
2379 titanGenericDao.rollback();
2381 titanGenericDao.commit();
2385 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2386 boolean inTransaction) {
2387 User user = new User();
2388 user.setUserId(userId);
2389 Either<Resource, StorageOperationStatus> parent = resourceOperation.getResource(resourceId);
2390 if (parent.isRight()) {
2391 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2392 return Either.right(responseFormat);
2394 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2395 false, inTransaction);
2396 if (handleDelete.isRight()) {
2397 return Either.right(handleDelete.right().value());
2399 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2400 return Either.left(result.right().value());
2404 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2406 if (artifacts != null && !artifacts.isEmpty()) {
2407 for (ArtifactDefinition artifactDefinition : artifacts) {
2408 String esId = artifactDefinition.getEsId();
2409 if (esId != null && !esId.isEmpty()) {
2410 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2411 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2412 return deleteIfNotOnGraph;
2417 return StorageOperationStatus.OK;
2420 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2421 Operation op = new Operation();
2422 long time = System.currentTimeMillis();
2423 op.setCreationDate(time);
2425 String artifactName = artifactInfo.getArtifactName();
2426 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2428 op.setImplementation(artifactInfo);
2429 op.setLastUpdateDate(time);
2433 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2434 String newArtifactName = operationName + "_" + artifactName;
2435 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2436 return newArtifactName;
2439 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2440 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2441 Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanGenericDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2442 if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2443 boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2445 if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2446 || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2447 // last one. need to delete in ES
2448 log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2449 artifactCassandraDao.deleteArtifact(artifactEsId);
2450 return StorageOperationStatus.OK;
2452 // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2456 log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2457 return StorageOperationStatus.OK;
2461 return StorageOperationStatus.OK;
2465 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2467 // General validation
2468 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2469 log.debug("One of the function parameteres is null");
2470 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2473 // Normalizing artifact name
2474 artifactName = ValidationUtils.normalizeFileName(artifactName);
2476 // Resource validation
2477 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2478 if (validateResourceNameAndVersion.isRight()) {
2479 return Either.right(validateResourceNameAndVersion.right().value());
2482 Resource resource = validateResourceNameAndVersion.left().value();
2483 String resourceId = resource.getUniqueId();
2485 // Service validation
2486 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2487 if (validateServiceNameAndVersion.isRight()) {
2488 return Either.right(validateServiceNameAndVersion.right().value());
2491 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2492 if (artifacts == null || artifacts.isEmpty()) {
2493 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2494 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2497 ArtifactDefinition deploymentArtifact = null;
2499 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2500 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2501 log.debug("Found deployment artifact {}", artifactName);
2502 deploymentArtifact = artifactDefinition;
2507 if (deploymentArtifact == null) {
2508 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
2509 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2512 // Downloading the artifact
2513 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2514 if (downloadArtifactEither.isRight()) {
2515 log.debug("Download artifact {} failed", artifactName);
2516 return Either.right(downloadArtifactEither.right().value());
2518 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
2519 return Either.left(downloadArtifactEither.left().value().getRight());
2523 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
2525 // General validation
2526 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
2527 log.debug("One of the function parameteres is null");
2528 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2531 // Normalizing artifact name
2532 artifactName = ValidationUtils.normalizeFileName(artifactName);
2534 // Resource validation
2536 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
2537 * Either.right(validateResourceNameAndVersion.right().value()); }
2539 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
2542 // Service validation
2543 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2544 if (validateServiceNameAndVersion.isRight()) {
2545 return Either.right(validateServiceNameAndVersion.right().value());
2548 Service service = validateServiceNameAndVersion.left().value();
2550 // ResourceInstance validation
2551 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
2552 if (validateResourceInstance.isRight()) {
2553 return Either.right(validateResourceInstance.right().value());
2556 ComponentInstance resourceInstance = validateResourceInstance.left().value();
2558 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
2560 final String finalArtifactName = artifactName;
2561 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
2563 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
2564 ArtifactDefinition deployableArtifact;
2566 if (!hasDeploymentArtifacts) {
2567 log.debug("Deployment artifact with name {} not found", artifactName);
2568 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2571 log.debug("Found deployment artifact {}", artifactName);
2572 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
2573 // Downloading the artifact
2574 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
2576 if (downloadArtifactEither.isRight()) {
2577 log.debug("Download artifact {} failed", artifactName);
2578 return Either.right(downloadArtifactEither.right().value());
2580 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
2581 return Either.left(downloadArtifactEither.left().value().getRight());
2584 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
2586 List<ComponentInstance> riList = service.getComponentInstances();
2587 for (ComponentInstance ri : riList) {
2588 if (ri.getNormalizedName().equals(resourceInstanceName))
2589 return Either.left(ri);
2592 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
2595 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
2597 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = serviceOperation.getServiceListBySystemName(serviceName, false);
2598 if (serviceListBySystemName.isRight()) {
2599 log.debug("Couldn't fetch any service with name {}", serviceName);
2600 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
2602 List<Service> serviceList = serviceListBySystemName.left().value();
2603 if (serviceList == null || serviceList.isEmpty()) {
2604 log.debug("Couldn't fetch any service with name {}", serviceName);
2605 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
2608 Service foundService = null;
2609 for (Service service : serviceList) {
2610 if (service.getVersion().equals(serviceVersion)) {
2611 log.trace("Found service with version {}", serviceVersion);
2612 foundService = service;
2617 if (foundService == null) {
2618 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
2619 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
2621 return Either.left(foundService);
2624 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
2625 Either<List<Resource>, StorageOperationStatus> resourceListBySystemName = resourceOperation.getResourceListBySystemName(resourceName, false);
2626 if (resourceListBySystemName.isRight()) {
2627 log.debug("Couldn't fetch any resource with name {}", resourceName);
2628 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
2630 List<Resource> resourceList = resourceListBySystemName.left().value();
2631 if (resourceList == null || resourceList.isEmpty()) {
2632 log.debug("Couldn't fetch any resource with name {}", resourceName);
2633 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceName));
2636 Resource foundResource = null;
2637 for (Resource resource : resourceList) {
2638 if (resource.getVersion().equals(resourceVersion)) {
2639 log.trace("Found resource with version {}", resourceVersion);
2640 foundResource = resource;
2645 if (foundResource == null) {
2646 log.debug("Couldn't find version {} for resource {}", resourceVersion, resourceName);
2647 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.RESOURCE.getValue(), resourceVersion));
2649 return Either.left(foundResource);
2652 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
2654 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
2655 if (serviceName == null || serviceVersion == null || artifactName == null) {
2656 log.debug("One of the function parameteres is null");
2657 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2660 // Normalizing artifact name
2661 artifactName = ValidationUtils.normalizeFileName(artifactName);
2663 // Service validation
2664 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2665 if (validateServiceNameAndVersion.isRight()) {
2666 return Either.right(validateServiceNameAndVersion.right().value());
2669 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
2671 // Looking for deployment artifacts
2672 Service service = validateServiceNameAndVersion.left().value();
2673 Map<String, ArtifactDefinition> artifacts = service.getDeploymentArtifacts();
2674 if (artifacts == null || artifacts.isEmpty()) {
2675 log.debug("Deployment artifacts of service {} are not found", serviceId);
2676 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2679 ArtifactDefinition deploymentArtifact = null;
2681 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2682 if (artifactDefinition.getArtifactName().equals(artifactName)) {
2683 log.debug("Found deployment artifact {}", artifactName);
2684 deploymentArtifact = artifactDefinition;
2688 if (deploymentArtifact == null) {
2689 log.debug("No deployment artifact {} was found for service {}", artifactName, serviceId);
2690 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2693 // Downloading the artifact
2694 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2695 if (downloadArtifactEither.isRight()) {
2696 log.debug("Download artifact {} failed", artifactName);
2697 return Either.right(downloadArtifactEither.right().value());
2699 log.trace("Download of service artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
2700 return Either.left(downloadArtifactEither.left().value().getRight());
2703 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String artifactUniqueId) {
2704 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
2705 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactOperation.getArtifactById(artifactUniqueId, false);
2706 if (artifactById.isRight()) {
2707 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
2708 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
2709 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
2711 ArtifactDefinition artifactDefinition = artifactById.left().value();
2712 if (artifactDefinition == null) {
2713 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
2714 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
2717 return downloadArtifact(artifactDefinition);
2720 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
2721 boolean found = false;
2722 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
2723 if (artifactsS != null) {
2724 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
2725 if (entry.getValue().getUniqueId().equals(artifactId)) {
2731 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
2732 if (!found && deploymentArtifactsS != null) {
2733 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
2734 if (entry.getValue().getUniqueId().equals(artifactId)) {
2740 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
2741 if (!found && toscaArtifactsS != null) {
2742 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
2743 if (entry.getValue().getUniqueId().equals(artifactId)) {
2749 switch (component.getComponentType()) {
2751 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
2752 if (!found && interfaces != null) {
2753 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
2754 Map<String, Operation> operations = entry.getValue().getOperations();
2755 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
2756 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
2765 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
2766 if (!found && apiArtifacts != null) {
2767 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
2768 if (entry.getValue().getUniqueId().equals(artifactId)) {
2782 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
2784 boolean found = false;
2785 List<ComponentInstance> resourceInstances = component.getComponentInstances();
2786 ComponentInstance resourceInstance = null;
2787 for (ComponentInstance ri : resourceInstances) {
2788 if (ri.getUniqueId().equals(resourceInstanceId)) {
2789 resourceInstance = ri;
2793 if (resourceInstance != null) {
2794 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
2795 if (artifacts != null) {
2796 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
2797 if (entry.getValue().getUniqueId().equals(artifactId)) {
2807 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
2808 String containerComponentType, boolean inTransaction) {
2810 NodeTypeEnum nodeType = componentType.getNodeType();
2811 if (containerComponentType != null && NodeTypeEnum.ResourceInstance == nodeType) {
2812 nodeType = (ComponentTypeEnum.findByParamName(containerComponentType)).getNodeType();
2814 ComponentOperation componentOperation = getComponentOperation(nodeType);
2816 if (componentOperation == null) {
2817 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2818 log.debug("addArtifact - not supported component type {}", componentType);
2819 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
2820 return Either.right(responseFormat);
2822 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = componentOperation.getComponent(componentId, inTransaction);
2824 if (componentResult.isRight()) {
2825 ActionStatus status = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
2826 ComponentTypeEnum componentForAudit = (componentType.equals(ComponentTypeEnum.RESOURCE)) ? ComponentTypeEnum.RESOURCE : ComponentTypeEnum.SERVICE;
2828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
2829 log.debug("Service not found, serviceId {}", componentId);
2830 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
2831 return Either.right(responseFormat);
2833 return Either.left(componentResult.left().value());
2836 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation,
2837 ComponentTypeEnum componentType) {
2838 if (operation != ArtifactOperation.Download) {
2839 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
2840 if (canWork.isRight()) {
2841 String uniqueId = component.getUniqueId();
2842 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
2843 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
2844 return Either.right(canWork.right().value());
2847 return Either.left(true);
2850 private Either<Boolean, ResponseFormat> validateWorkOnResource(Resource resource, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperation operation) {
2851 if (operation != ArtifactOperation.Download) {
2852 if (!ComponentValidationUtils.canWorkOnResource(resource, userId)) {
2853 String uniqueId = resource.getUniqueId();
2854 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
2855 log.debug("Resource status isn't CHECKOUT or user isn't owner, resourceId {}", uniqueId);
2856 handleAuditing(auditingAction, resource, uniqueId, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE, null);
2857 return Either.right(responseFormat);
2860 return Either.left(true);
2863 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperation operation) {
2865 if (operation != ArtifactOperation.Download) {
2866 String role = user.getRole();
2867 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
2868 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
2869 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
2870 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
2871 return Either.right(responseFormat);
2874 return Either.left(true);
2877 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType) {
2879 return validateUserExists(userId, auditingAction, componentId, artifactId, componentType, false);
2883 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
2884 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
2886 if (validateUserExists.isRight()) {
2887 User user = new User();
2888 user.setUserId(userId);
2889 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
2890 return Either.right(validateUserExists.right().value());
2892 return Either.left(validateUserExists.left().value());
2895 private AuditingActionEnum detectAuditingType(ArtifactOperation operation, String origMd5) {
2896 AuditingActionEnum auditingAction = null;
2897 switch (operation) {
2899 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
2902 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
2905 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
2908 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
2913 return auditingAction;
2916 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
2917 String esArtifactId = artifactDefinition.getEsId();
2918 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
2919 if (artifactfromES.isRight()) {
2920 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
2921 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
2922 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
2923 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
2924 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
2927 ESArtifactData esArtifactData = artifactfromES.left().value();
2928 byte[] data = esArtifactData.getDataAsArray();
2930 log.debug("Artifact data from ES is null");
2931 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
2933 String artifactName = artifactDefinition.getArtifactName();
2934 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
2935 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
2938 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
2939 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
2940 return artifactData;
2943 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
2945 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
2947 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
2948 log.debug("Artifact {} was saved in component {}.", artifactData.getId(), resourceId);
2950 log.info("Failed to save artifact {}.", artifactData.getId());
2956 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
2957 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
2960 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
2961 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
2964 public IResourceOperation getResourceOperation() {
2965 return this.resourceOperation;
2968 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
2969 Either<User, ActionStatus> user = userAdminManager.getUser(userId, inTransaction);
2970 if (user.isRight()) {
2971 ResponseFormat responseFormat;
2972 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
2973 log.debug("create artifact placeholder - not authorized user, userId {}", userId);
2974 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
2976 log.debug("create artifact placeholder - failed to authorize user, userId {}", userId);
2977 responseFormat = componentsUtils.getResponseFormat(user.right().value());
2979 return Either.right(responseFormat);
2982 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
2983 return Either.left(artifactDefinition);
2986 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
2987 ArtifactDefinition artifactInfo = new ArtifactDefinition();
2989 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
2990 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
2991 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
2993 artifactInfo.setArtifactDisplayName(artifactName);
2994 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
2995 artifactInfo.setArtifactType(artifactType);
2996 artifactInfo.setDescription(artifactDescription);
2997 artifactInfo.setArtifactGroupType(groupType);
2998 setDefaultArtifactTimeout(groupType, artifactInfo);
3000 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3002 return artifactInfo;
3005 private void setDefaultArtifactTimeout(ArtifactGroupTypeEnum groupType, ArtifactDefinition artifactInfo) {
3006 if (groupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
3007 artifactInfo.setTimeout(defaultHeatTimeout);
3009 artifactInfo.setTimeout(NON_HEAT_TIMEOUT);
3013 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3014 String uniqueId = null;
3016 if (resourceId != null) {
3017 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3018 artifactInfo.setUniqueId(uniqueId);
3020 artifactInfo.setUserIdCreator(user.getUserId());
3021 String fullName = user.getFullName();
3022 artifactInfo.setUpdaterFullName(fullName);
3024 long time = System.currentTimeMillis();
3026 artifactInfo.setCreatorFullName(fullName);
3027 artifactInfo.setCreationDate(time);
3029 artifactInfo.setLastUpdateDate(time);
3030 artifactInfo.setUserIdLastUpdater(user.getUserId());
3032 artifactInfo.setMandatory(true);
3035 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType) {
3036 return artifactOperation.getArtifacts(parentId, parentType, inTransaction, groupType.getType());
3039 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String parentId, NodeTypeEnum parentType, boolean inTransaction) {
3040 return artifactOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, parentId, parentType, inTransaction);
3044 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String parameters) {
3045 StringBuilder sb = new StringBuilder();
3047 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3048 sb.append(parameters);
3049 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3050 byte[] payload = sb.toString().getBytes();
3052 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
3055 * if (!yamlToObjectConverter.isValidYaml(payload)) { log.debug("Invalid YAML format"); ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, ArtifactTypeEnum.HEAT_ENV.getType()); return
3056 * Either.right(responseFormat); }
3059 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3060 return Either.left(artifactData);
3065 * @param artifactDefinition
3068 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock) {
3069 List<HeatParameterDefinition> heatParameters = artifactDefinition.getHeatParameters();
3070 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3071 StringBuilder sb = new StringBuilder("parameters:\n");
3072 if (heatParameters != null) {
3074 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3075 if (heatParameterDefinition.getCurrentValue() != null) {
3076 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3080 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatParameterDefinition.getCurrentValue())).append("\n");
3084 // (ValidationUtils.isFloatNumber(heatParameterDefinition.getCurrentValue()))
3087 // ").append(heatParameterDefinition.getName()).append(":").append("
3088 // ").append(Float.parseFloat(heatParameterDefinition.getCurrentValue())).append("\n");
3091 // ").append(heatParameterDefinition.getName()).append(":").append("
3092 // ").append(Integer.parseInt(heatParameterDefinition.getCurrentValue())).append("\n");
3094 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatParameterDefinition.getCurrentValue()).toPlainString()).append("\n");
3096 case COMMA_DELIMITED_LIST:
3098 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatParameterDefinition.getCurrentValue()).append("\n");
3101 String value = heatParameterDefinition.getCurrentValue();
3102 boolean starts = value.startsWith("\"");
3103 boolean ends = value.endsWith("\"");
3104 if (!(starts && ends)) {
3105 starts = value.startsWith("'");
3106 ends = value.endsWith("'");
3107 if (!(starts && ends)) {
3108 value = "\"" + value + "\"";
3111 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3120 return generateAndSaveHeatEnvArtifact(artifactDefinition, sb.toString(), component, resourceInstanceName, modifier, shouldLock);
3126 * @param artifactDefinition
3130 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3131 boolean shouldLock) {
3132 return generateArtifactPayload(artifactDefinition, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(), () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload));
3136 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier, boolean shouldLock,
3137 Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator) {
3139 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
3141 log.trace("Generaing payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3142 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3143 ESArtifactData artifactData = null;
3145 if (artifactDataRes.isLeft()) {
3146 artifactData = artifactDataRes.left().value();
3148 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3149 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3150 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3152 return Either.right(artifactDataRes.right().value());
3154 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3156 String esArtifactId = artifactDefinition.getEsId();
3157 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3158 ESArtifactData esArtifactData;
3159 if (esArtifactId != null && !esArtifactId.isEmpty()) {
3160 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3161 if (artifactfromES.isRight()) {
3162 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3163 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3164 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3165 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3166 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3168 esArtifactData = artifactfromES.left().value();
3169 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3171 oldCheckSum = artifactDefinition.getArtifactChecksum();
3173 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus;
3176 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3177 if (lockComponent.isRight()) {
3178 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3179 return Either.right(lockComponent.right().value());
3183 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3185 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3186 updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, false);
3187 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3188 if (updateArifactDefinitionStatus.isRight()) {
3189 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3190 log.trace("Failed to update payloadUpdateDate ", artifactDefinition.getEsId());
3191 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3192 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3194 return Either.right(responseFormat);
3198 oldCheckSum = artifactDefinition.getArtifactChecksum();
3199 artifactDefinition.setArtifactChecksum(newCheckSum);
3200 artifactOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3201 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3202 updateArifactDefinitionStatus = artifactOperation.updateArifactDefinition(artifactDefinition, true);
3204 log.trace("Update Payload ", artifactDefinition.getEsId());
3206 if (updateArifactDefinitionStatus.isLeft()) {
3208 artifactData.setId(artifactDefinition.getUniqueId());
3209 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3211 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3212 titanGenericDao.commit();
3213 log.debug("Artifact Saved In ES {}", artifactData.getId());
3214 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3215 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3216 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3219 titanGenericDao.rollback();
3220 log.info("Failed to save artifact {}.", artifactData.getId());
3221 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3222 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3223 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3225 return Either.right(responseFormat);
3228 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3229 log.debug("Failed To update artifact {}", artifactData.getId());
3230 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3231 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3233 return Either.right(responseFormat);
3239 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3244 return Either.left(artifactDefinition);
3247 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3248 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperation operation, boolean shouldLock, boolean inTransaction) {
3249 NodeTypeEnum parentType = convertParentType(componentType);
3250 String parentId = parent.getUniqueId();
3251 Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false);
3252 ArtifactDefinition currArtifact = artifactRes.left().value();
3254 if (origMd5 != null) {
3255 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3256 if (validateMd5.isRight()) {
3257 ResponseFormat responseFormat = validateMd5.right().value();
3258 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3259 return Either.right(responseFormat);
3262 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3263 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3264 if (deploymentValidationResult.isRight()) {
3265 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3266 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3267 return Either.right(responseFormat);
3270 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3271 if (payloadEither.isRight()) {
3272 ResponseFormat responseFormat = payloadEither.right().value();
3273 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3274 return Either.right(responseFormat);
3276 } else { // duplicate
3277 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3278 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3279 return Either.right(responseFormat);
3285 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3286 if (lockComponent.isRight()) {
3287 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3288 return Either.right(lockComponent.right().value());
3291 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3293 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3298 if (resultOp == null || resultOp.isRight()) {
3299 log.debug("all changes rollback");
3300 if (false == inTransaction)
3301 titanGenericDao.rollback();
3303 log.debug("all changes committed");
3304 if (false == inTransaction)
3305 titanGenericDao.commit();
3308 componentType = parent.getComponentType();
3309 NodeTypeEnum nodeType = componentType.getNodeType();
3310 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3311 // graphLockOperation.unlockComponent(parentId, parentType);
3315 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3316 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3318 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3319 Either<ArtifactDefinition, Operation> insideEither = null;
3321 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3323 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3324 if (getRI.isRight()) {
3325 return Either.right(getRI.right().value());
3327 ComponentInstance ri = getRI.left().value();
3328 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3329 if (getArtifactRes.isRight()) {
3330 return Either.right(getArtifactRes.right().value());
3332 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3334 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3335 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3336 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3337 return Either.right(responseFormat);
3339 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getHeatParameters();
3340 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getHeatParameters();
3341 List<HeatParameterDefinition> reducedHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3344 if (origMd5 != null) {
3345 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3346 updatedHeatEnvParams, currArtifact.getArtifactName());
3347 if (uploadParamsValidationResult.isRight()) {
3348 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3349 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3350 return Either.right(responseFormat);
3352 artifactInfo.setHeatParameters(updatedHeatEnvParams);
3355 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3356 if (validateAndConvertHeatParamers.isRight()) {
3357 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3358 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3359 return Either.right(responseFormat);
3362 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3364 // fill reduced heat env parameters List for updating
3365 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3366 paramName = heatEnvParam.getName();
3367 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3368 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3369 String updatedParamValue = heatEnvParam.getCurrentValue();
3370 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3371 heatEnvParam.setCurrentValue(heatEnvParam.getDefaultValue());
3372 reducedHeatEnvParams.add(heatEnvParam);
3373 } else if (updatedParamValue != null) {
3374 reducedHeatEnvParams.add(heatEnvParam);
3379 if (reducedHeatEnvParams.size() > 0) {
3380 ArtifactDefinition reducedArtifactInfo = new ArtifactDefinition(artifactInfo);
3381 reducedArtifactInfo.setHeatParameters(reducedHeatEnvParams);
3382 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactResult = artifactOperation.updateArifactOnResource(reducedArtifactInfo, componentId, artifactInfo.getUniqueId(), componentType.getNodeType(), inTransaction);
3384 if (updateArtifactResult.isRight()) {
3385 log.debug("Failed to update artifact on graph - {}", artifactId);
3386 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArtifactResult.right().value()));
3387 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3388 return Either.right(responseFormat);
3390 ArtifactDefinition updatedArtifact = updateArtifactResult.left().value();
3391 String updatedArtifactId = updatedArtifact.getUniqueId();
3392 if (!currArtifact.getUniqueId().equals(updatedArtifactId)) {
3393 currArtifact.setUniqueId(updatedArtifactId);
3394 currArtifact.setPayloadUpdateDate(updatedArtifact.getPayloadUpdateDate());
3395 currArtifact.setCreationDate(updatedArtifact.getCreationDate());
3396 currArtifact.setLastUpdateDate(updatedArtifact.getLastUpdateDate());
3397 currArtifact.setEsId(updatedArtifact.getEsId());
3399 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3401 Either<List<HeatParameterDefinition>, StorageOperationStatus> heatParamsForEnv = ((org.openecomp.sdc.be.model.operations.impl.ArtifactOperation) artifactOperation).getHeatParamsForEnv(currArtifact);
3402 if (heatParamsForEnv.isRight()) {
3403 log.debug("failed to get heat parameters values for heat artifact {}", updatedArtifact.getUniqueId());
3404 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatParamsForEnv.right().value()));
3405 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3406 return Either.right(responseFormat);
3408 List<HeatParameterDefinition> updatedHeatParaetersList = heatParamsForEnv.left().value();
3409 currArtifact.setHeatParameters(updatedHeatParaetersList);
3411 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactOperation.updateArifactDefinition(currArtifact, true);
3412 if (updateArifactRes.isRight()) {
3413 log.debug("Failed to update artifact on graph - {}", artifactId);
3414 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3415 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3416 return Either.right(responseFormat);
3421 insideEither = Either.left(currArtifact);
3422 resultOp = Either.left(insideEither);
3423 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3424 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3428 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
3429 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
3431 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
3432 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
3433 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3434 return Either.right(responseFormat);
3437 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
3438 String paramName = uploadedHeatParam.getName();
3439 boolean isExistsInHeat = false;
3440 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3441 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3443 isExistsInHeat = true;
3444 uploadedHeatParam.setType(currHeatParam.getType());
3445 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
3446 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
3447 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
3451 if (!isExistsInHeat) {
3452 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
3453 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3454 return Either.right(responseFormat);
3457 return Either.left(updatedHeatEnvParams);
3460 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3461 ResponseFormat responseFormat = null;
3462 List<ComponentInstance> ris = component.getComponentInstances();
3463 for (ComponentInstance ri : ris) {
3464 if (riID.equals(ri.getUniqueId())) {
3465 return Either.left(ri);
3468 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
3469 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
3470 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
3471 return Either.right(responseFormat);
3474 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3475 ResponseFormat responseFormat = null;
3476 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
3477 for (ArtifactDefinition artifact : rtifactsMap.values()) {
3478 if (artifactId.equals(artifact.getUniqueId())) {
3479 return Either.left(artifact);
3482 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
3483 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
3484 return Either.right(responseFormat);
3487 public ComponentOperation getComponentOperation(NodeTypeEnum componentType) {
3489 switch (componentType) {
3491 case ResourceInstance:
3492 return serviceOperation;
3494 return resourceOperation;
3500 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
3501 ArtifactDefinition ret;
3502 if (eitherArtifact.isLeft()) {
3503 ret = eitherArtifact.left().value();
3505 ret = eitherArtifact.right().value().getImplementation();
3511 * downloads artifact of component by UUIDs
3513 * @param componentType
3514 * @param componentUuid
3515 * @param artifactUUID
3516 * @param auditAdditionalParam
3519 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
3520 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3521 Either<byte[], ResponseFormat> result;
3522 byte[] downloadedArtifact = null;
3523 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
3524 if (errorWrapper.isEmpty()) {
3525 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
3526 downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
3528 if (errorWrapper.isEmpty()) {
3529 result = Either.left(downloadedArtifact);
3531 result = Either.right(errorWrapper.getInnerElement());
3537 * downloads an artifact of resource instance of component by UUIDs
3539 * @param componentType
3540 * @param componentUuid
3541 * @param resourceName
3542 * @param artifactUUID
3543 * @param auditAdditionalParam
3546 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
3547 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3548 Either<byte[], ResponseFormat> result;
3549 byte[] downloadedArtifact = null;
3550 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
3551 if (errorWrapper.isEmpty()) {
3552 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstance.getName());
3553 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
3555 if (errorWrapper.isEmpty()) {
3556 result = Either.left(downloadedArtifact);
3558 result = Either.right(errorWrapper.getInnerElement());
3564 * uploads an artifact to a component by UUID
3568 * @param componentType
3569 * @param componentUuid
3570 * @param additionalParams
3573 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams) {
3574 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3575 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3576 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
3577 ArtifactDefinition uploadArtifact;
3578 Component component = null;
3579 String componentId = null;
3580 ArtifactOperation operation = ArtifactOperation.Create;
3581 operation.setExternalApi(true);
3582 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
3583 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3584 String userId = request.getHeader(Constants.USER_ID_HEADER);
3586 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
3587 if (getComponentRes.isRight()) {
3588 StorageOperationStatus status = getComponentRes.right().value();
3589 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3590 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3592 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3593 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
3595 if (errorWrapper.isEmpty()) {
3596 if (component != null) {
3597 componentId = component.getUniqueId();
3599 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
3602 if (errorWrapper.isEmpty()) {
3603 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
3604 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
3605 if (actionResult.isRight()) {
3606 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
3607 errorWrapper.setInnerElement(actionResult.right().value());
3610 if (errorWrapper.isEmpty()) {
3611 uploadArtifact = actionResult.left().value().left().value();
3612 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
3613 uploadArtifactResult = Either.left(uploadArtifact);
3615 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
3617 return uploadArtifactResult;
3621 * upload an artifact to a resource instance by UUID
3625 * @param componentType
3626 * @param componentUuid
3627 * @param resourceInstanceName
3628 * @param additionalParams
3631 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
3632 Map<AuditingFieldsKeysEnum, Object> additionalParams) {
3633 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3634 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
3635 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3636 ArtifactDefinition uploadArtifact;
3637 Component component = null;
3638 String componentInstanceId;
3640 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3641 String userId = request.getHeader(Constants.USER_ID_HEADER);
3643 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
3644 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
3645 if (getComponentRes.isRight()) {
3646 StorageOperationStatus status = getComponentRes.right().value();
3647 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3648 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3650 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3651 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
3653 if (errorWrapper.isEmpty()) {
3654 if (component == null) {
3655 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
3657 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
3660 if (errorWrapper.isEmpty()) {
3661 componentInstanceId = componentRiPair.getRight().getUniqueId();
3662 componentId = componentRiPair.getLeft().getUniqueId();
3663 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
3664 ArtifactOperation operation = ArtifactOperation.Create;
3665 operation.setExternalApi(true);
3666 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
3668 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
3669 if (actionResult.isRight()) {
3670 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
3671 errorWrapper.setInnerElement(actionResult.right().value());
3674 if (errorWrapper.isEmpty()) {
3675 uploadArtifact = actionResult.left().value().left().value();
3676 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
3677 uploadArtifactResult = Either.left(uploadArtifact);
3679 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
3681 return uploadArtifactResult;
3685 * updates an artifact on a component by UUID
3689 * @param componentType
3690 * @param componentUuid
3691 * @param artifactUUID
3692 * @param additionalParams
3695 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
3696 Map<AuditingFieldsKeysEnum, Object> additionalParams) {
3697 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3698 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
3699 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3700 ArtifactDefinition updateArtifact;
3701 Component component = null;
3702 String componentId = null;
3703 String artifactId = null;
3704 ArtifactOperation operation = ArtifactOperation.Update;
3705 operation.setExternalApi(true);
3706 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
3707 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3708 String userId = request.getHeader(Constants.USER_ID_HEADER);
3710 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
3711 if (getComponentRes.isRight()) {
3712 StorageOperationStatus status = getComponentRes.right().value();
3713 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3714 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3716 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3717 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
3719 if (errorWrapper.isEmpty()) {
3720 if (component != null) {
3721 componentId = component.getUniqueId();
3723 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
3726 if (errorWrapper.isEmpty()) {
3727 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
3729 if (errorWrapper.isEmpty()) {
3730 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
3732 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
3733 if (actionResult.isRight()) {
3734 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
3735 errorWrapper.setInnerElement(actionResult.right().value());
3738 if (errorWrapper.isEmpty()) {
3739 updateArtifact = actionResult.left().value().left().value();
3740 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
3741 updateArtifactResult = Either.left(updateArtifact);
3744 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
3746 return updateArtifactResult;
3750 * updates an artifact on a resource instance by UUID
3754 * @param componentType
3755 * @param componentUuid
3756 * @param resourceInstanceName
3757 * @param artifactUUID
3758 * @param additionalParams
3761 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
3762 Map<AuditingFieldsKeysEnum, Object> additionalParams) {
3764 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3765 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
3766 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3767 ArtifactDefinition updateArtifact;
3768 Component component = null;
3769 String componentInstanceId = null;
3770 String componentId = null;
3771 String artifactId = null;
3772 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3773 String userId = request.getHeader(Constants.USER_ID_HEADER);
3775 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
3776 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
3777 if (getComponentRes.isRight()) {
3778 StorageOperationStatus status = getComponentRes.right().value();
3779 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3780 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3782 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3783 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
3785 if (errorWrapper.isEmpty()) {
3786 if (component == null) {
3787 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
3789 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
3792 if (errorWrapper.isEmpty()) {
3793 componentInstanceId = componentRiPair.getRight().getUniqueId();
3794 componentId = componentRiPair.getLeft().getUniqueId();
3795 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE);
3797 if (errorWrapper.isEmpty()) {
3798 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
3799 ArtifactOperation operation = ArtifactOperation.Update;
3800 operation.setExternalApi(true);
3801 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
3803 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
3804 if (actionResult.isRight()) {
3805 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
3806 errorWrapper.setInnerElement(actionResult.right().value());
3809 if (errorWrapper.isEmpty()) {
3810 updateArtifact = actionResult.left().value().left().value();
3811 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
3812 updateArtifactResult = Either.left(updateArtifact);
3814 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
3816 return updateArtifactResult;
3821 * deletes an artifact on a component by UUID
3824 * @param componentType
3825 * @param componentUuid
3826 * @param artifactUUID
3827 * @param additionalParams
3830 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams) {
3832 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3833 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
3834 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3835 ArtifactDefinition deleteArtifact;
3836 Component component = null;
3837 String componentId = null;
3838 String artifactId = null;
3839 ArtifactOperation operation = ArtifactOperation.Delete;
3840 operation.setExternalApi(true);
3841 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3842 String userId = request.getHeader(Constants.USER_ID_HEADER);
3844 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
3845 if (getComponentRes.isRight()) {
3846 StorageOperationStatus status = getComponentRes.right().value();
3847 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3848 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3850 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3851 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
3853 if (errorWrapper.isEmpty()) {
3854 if (component != null) {
3855 componentId = component.getUniqueId();
3857 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
3860 if (errorWrapper.isEmpty()) {
3861 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
3863 if (errorWrapper.isEmpty()) {
3864 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, getComponentRes.left().value().getMetadataDataDefinition().getName());
3866 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
3867 if (actionResult.isRight()) {
3868 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
3869 errorWrapper.setInnerElement(actionResult.right().value());
3872 if (errorWrapper.isEmpty()) {
3873 deleteArtifact = actionResult.left().value().left().value();
3874 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
3875 deleteArtifactResult = Either.left(deleteArtifact);
3877 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
3879 return deleteArtifactResult;
3883 * deletes an artifact an a resource instance by UUID
3886 * @param componentType
3887 * @param componentUuid
3888 * @param resourceInstanceName
3889 * @param artifactUUID
3890 * @param additionalParams
3893 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
3894 Map<AuditingFieldsKeysEnum, Object> additionalParams) {
3896 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3897 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
3898 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3899 ArtifactDefinition deleteArtifact;
3900 Component component = null;
3901 String componentInstanceId = null;
3902 String componentId = null;
3903 String artifactId = null;
3904 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3905 String userId = request.getHeader(Constants.USER_ID_HEADER);
3906 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
3907 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentMetadataByUuid(componentType.getNodeType(), componentUuid);
3908 if (getComponentRes.isRight()) {
3909 StorageOperationStatus status = getComponentRes.right().value();
3910 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3911 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3913 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3914 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
3916 if (errorWrapper.isEmpty()) {
3917 if (component == null) {
3918 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
3920 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
3923 if (errorWrapper.isEmpty()) {
3924 componentInstanceId = componentRiPair.getRight().getUniqueId();
3925 componentId = componentRiPair.getLeft().getUniqueId();
3926 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentInstanceId, ComponentTypeEnum.RESOURCE_INSTANCE);
3928 if (errorWrapper.isEmpty()) {
3930 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
3931 ArtifactOperation operation = ArtifactOperation.Delete;
3932 operation.setExternalApi(true);
3934 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
3936 if (actionResult.isRight()) {
3937 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
3938 errorWrapper.setInnerElement(actionResult.right().value());
3941 if (errorWrapper.isEmpty()) {
3942 deleteArtifact = actionResult.left().value().left().value();
3943 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
3944 deleteArtifactResult = Either.left(deleteArtifact);
3946 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
3948 return deleteArtifactResult;
3951 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
3952 ComponentInstance componentInstance = null;
3953 StorageOperationStatus status;
3954 Either<ComponentInstance, StorageOperationStatus> getResourceInstanceRes = null;
3955 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
3956 if (errorWrapper.isEmpty()) {
3957 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
3958 if (componentInstance == null) {
3959 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
3960 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
3963 if (errorWrapper.isEmpty()) {
3964 getResourceInstanceRes = resourceInstanceOperation.getResourceInstanceById(componentInstance.getUniqueId());
3965 if (getResourceInstanceRes.isRight()) {
3966 status = getResourceInstanceRes.right().value();
3967 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3970 if (errorWrapper.isEmpty()) {
3971 componentInstance = getResourceInstanceRes.left().value();
3972 getResourceInstanceRes = resourceInstanceOperation.getFullComponentInstance(componentInstance, componentType.getNodeType());
3973 if (getResourceInstanceRes.isRight()) {
3974 status = getResourceInstanceRes.right().value();
3975 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
3977 componentInstance = getResourceInstanceRes.left().value();
3980 return componentInstance;
3983 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
3985 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
3986 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
3987 if (componentInstance == null) {
3988 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
3989 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
3991 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
3993 return relatedComponentComponentInstancePair;
3996 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
3997 ComponentInstance componentInstance;
3998 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
3999 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4000 if (errorWrapper.isEmpty()) {
4001 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findAny().get();
4002 if (componentInstance == null) {
4003 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4004 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4006 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4009 return relatedComponentComponentInstancePair;
4012 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4014 byte[] downloadedArtifact = null;
4015 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4016 List<ArtifactDefinition> deploymentArtifacts = null;
4017 ArtifactDefinition deploymentArtifact = null;
4018 if (artifacts != null && !artifacts.isEmpty()) {
4019 deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4021 if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
4022 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4023 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4025 if (errorWrapper.isEmpty()) {
4026 deploymentArtifact = deploymentArtifacts.get(0);
4027 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4028 if (downloadArtifactEither.isRight()) {
4029 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4030 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4033 if (errorWrapper.isEmpty()) {
4034 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4035 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4037 return downloadedArtifact;
4040 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4041 Component component = null;
4042 Either<Component, StorageOperationStatus> getComponentRes = getComponentOperation(componentType).getLatestComponentByUuid(componentType.getNodeType(), componentUuid);
4043 if (getComponentRes.isRight()) {
4044 StorageOperationStatus status = getComponentRes.right().value();
4045 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4046 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4048 component = getComponentRes.left().value();
4053 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4054 String artifactId = null;
4055 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4056 StorageOperationStatus storageStatus;
4057 ArtifactDefinition latestArtifact = null;
4058 List<ArtifactDefinition> artifacts = null;
4059 NodeTypeEnum parentType;
4060 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
4061 parentType = NodeTypeEnum.Resource;
4063 parentType = NodeTypeEnum.Service;
4065 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactOperation.getArtifacts(parentId, parentType, false);
4066 if (getArtifactsRes.isRight()) {
4067 storageStatus = getArtifactsRes.right().value();
4068 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4069 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4070 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4072 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4074 if (errorWrapper.isEmpty()) {
4075 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4076 if (artifacts == null || artifacts.isEmpty()) {
4077 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4078 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4081 if (errorWrapper.isEmpty()) {
4082 latestArtifact = artifacts.stream().max((a1, a2) -> {
4083 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4084 if (compareRes == 0) {
4085 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4089 if (latestArtifact == null) {
4090 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4091 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4094 if (errorWrapper.isEmpty()) {
4095 artifactId = latestArtifact.getUniqueId();
4100 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4102 Component component = null;
4103 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4104 if (getUserRes.isRight()) {
4105 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4106 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4108 if (errorWrapper.isEmpty()) {
4109 User modifier = getUserRes.left().value();
4110 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4111 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4112 if (checkoutRes.isRight()) {
4113 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4114 errorWrapper.setInnerElement(checkoutRes.right().value());
4116 component = checkoutRes.left().value();
4122 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4123 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4124 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4125 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());