2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.annotations.VisibleForTesting;
24 import com.google.gson.Gson;
25 import com.google.gson.GsonBuilder;
26 import fj.data.Either;
27 import org.apache.commons.codec.binary.Base64;
28 import org.apache.commons.collections.CollectionUtils;
29 import org.apache.commons.collections.MapUtils;
30 import org.apache.commons.lang.StringUtils;
31 import org.apache.commons.lang3.tuple.ImmutablePair;
32 import org.elasticsearch.common.Strings;
33 import org.openecomp.sdc.be.components.ArtifactsResolver;
34 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
35 import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector;
36 import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
37 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
38 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
39 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
40 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
41 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
42 import org.openecomp.sdc.be.config.BeEcompErrorManager;
43 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
44 import org.openecomp.sdc.be.config.ConfigurationManager;
45 import org.openecomp.sdc.be.dao.api.ActionStatus;
46 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
47 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
48 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
49 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
53 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
54 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
56 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
57 import org.openecomp.sdc.be.model.ArtifactDefinition;
58 import org.openecomp.sdc.be.model.ArtifactType;
59 import org.openecomp.sdc.be.model.Component;
60 import org.openecomp.sdc.be.model.ComponentInstance;
61 import org.openecomp.sdc.be.model.ComponentParametersView;
62 import org.openecomp.sdc.be.model.GroupDefinition;
63 import org.openecomp.sdc.be.model.GroupInstance;
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.jsontitan.operations.NodeTemplateOperation;
74 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
75 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
76 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
77 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
78 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
79 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
80 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
81 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
82 import org.openecomp.sdc.be.resources.data.ESArtifactData;
83 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
84 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
85 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
86 import org.openecomp.sdc.be.servlets.RepresentationUtils;
87 import org.openecomp.sdc.be.tosca.CsarUtils;
88 import org.openecomp.sdc.be.tosca.ToscaError;
89 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
90 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
91 import org.openecomp.sdc.be.user.IUserBusinessLogic;
92 import org.openecomp.sdc.be.user.Role;
93 import org.openecomp.sdc.be.user.UserBusinessLogic;
94 import org.openecomp.sdc.be.utils.TypeUtils;
95 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
96 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
97 import org.openecomp.sdc.common.api.Constants;
98 import org.openecomp.sdc.common.datastructure.Wrapper;
99 import org.openecomp.sdc.common.log.wrappers.Logger;
100 import org.openecomp.sdc.common.util.GeneralUtility;
101 import org.openecomp.sdc.common.util.ValidationUtils;
102 import org.openecomp.sdc.common.util.YamlToObjectConverter;
103 import org.openecomp.sdc.exception.ResponseFormat;
104 import org.springframework.beans.factory.annotation.Autowired;
105 import org.xml.sax.InputSource;
106 import org.xml.sax.SAXException;
107 import org.xml.sax.SAXNotRecognizedException;
108 import org.xml.sax.SAXNotSupportedException;
109 import org.xml.sax.XMLReader;
110 import org.yaml.snakeyaml.Yaml;
112 import javax.servlet.http.HttpServletRequest;
113 import javax.xml.XMLConstants;
114 import javax.xml.parsers.ParserConfigurationException;
115 import javax.xml.parsers.SAXParserFactory;
116 import java.io.ByteArrayInputStream;
117 import java.io.IOException;
118 import java.math.BigDecimal;
119 import java.util.ArrayList;
120 import java.util.Collections;
121 import java.util.Comparator;
122 import java.util.HashMap;
123 import java.util.Iterator;
124 import java.util.List;
125 import java.util.Map;
126 import java.util.Map.Entry;
127 import java.util.Objects;
128 import java.util.Optional;
129 import java.util.Set;
130 import java.util.function.Predicate;
131 import java.util.function.Supplier;
132 import java.util.stream.Collectors;
134 @org.springframework.stereotype.Component("artifactBusinessLogic")
135 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
136 private static final String RESOURCE_INSTANCE = "resource instance";
137 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
138 private static final String ARTIFACT_DESCRIPTION = "artifact description";
139 private static final String ARTIFACT_LABEL = "artifact label";
140 private static final String ARTIFACT_URL = "artifact url";
141 private static final String ARTIFACT_NAME = "artifact name";
142 private static final String ARTIFACT_PAYLOAD = "artifact payload";
144 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
145 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
146 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
148 public static final String HEAT_ENV_NAME = "heatEnv";
149 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
150 public static final String HEAT_ENV_SUFFIX = "env";
151 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
153 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
154 public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
155 public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
156 public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
157 public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
158 public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
159 public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
160 public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
161 public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
162 public static final String NULL_PARAMETER = "One of the function parameteres is null";
163 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
164 public static final String ROLLBACK = "all changes rollback";
165 public static final String COMMIT = "all changes committed";
166 public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
167 public static final String UPDATE_ARTIFACT = "Update Artifact";
168 public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
169 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
171 @javax.annotation.Resource
172 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
173 @javax.annotation.Resource
174 private IUserAdminOperation userOperaton;
176 @javax.annotation.Resource
177 private IElementOperation elementOperation;
179 @javax.annotation.Resource
180 private ResourceBusinessLogic resourceBusinessLogic;
182 @javax.annotation.Resource
183 private ServiceBusinessLogic serviceBusinessLogic;
185 @javax.annotation.Resource
186 private UserBusinessLogic userAdminManager;
188 @javax.annotation.Resource
189 private IHeatParametersOperation heatParametersOperation;
192 private ArtifactCassandraDao artifactCassandraDao;
195 private ToscaExportHandler toscaExportUtils;
198 private CsarUtils csarUtils;
201 private LifecycleBusinessLogic lifecycleBusinessLogic;
204 private IUserBusinessLogic userBusinessLogic;
207 private NodeTemplateOperation nodeTemplateOperation;
210 private ArtifactsResolver artifactsResolver;
212 public enum ArtifactOperationEnum {
213 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
215 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
216 return operation == CREATE || operation == LINK;
220 public class ArtifactOperationInfo {
222 private ArtifactOperationEnum artifactOperationEnum;
223 private boolean isExternalApi;
224 private boolean ignoreLifecycleState;
226 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
227 this.artifactOperationEnum = artifactOperationEnum;
228 this.isExternalApi = isExternalApi;
229 this.ignoreLifecycleState = ignoreLifecycleState;
232 public boolean isExternalApi() {
233 return isExternalApi;
236 public boolean ignoreLifecycleState() {
237 return ignoreLifecycleState;
240 public ArtifactOperationEnum getArtifactOperationEnum() {
241 return artifactOperationEnum;
247 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
248 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
249 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
252 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
253 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
255 // step 1 - detect auditing type
256 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
257 // step 2 - check header
258 if (userId == null) {
259 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
260 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
261 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
262 return Either.right(responseFormat);
264 // step 3 - check user existence
265 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
266 if (userResult.isRight()) {
267 return Either.right(userResult.right().value());
270 // step 4 - check user's role
271 User user = userResult.left().value();
272 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
273 if (validateUserRole.isRight()) {
274 return Either.right(validateUserRole.right().value());
278 // 5. check service/resource existence
279 // 6. check service/resource check out
280 // 7. user is owner of checkout state
281 org.openecomp.sdc.be.model.Component component = null;
282 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
283 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
284 if (validateComponent.isRight()) {
285 return Either.right(validateComponent.right().value());
287 component = validateComponent.left().value();
288 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
289 if (validateWorkOnResource.isRight()) {
290 return Either.right(validateWorkOnResource.right().value());
294 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
295 shouldLock, inTransaction, true);
299 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
300 * For regular usage use <br>
301 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
305 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
306 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
307 Component parent = component;
308 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
310 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
311 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
313 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
314 if (errorWrapper.isEmpty()) {
316 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
319 result = Either.right(errorWrapper.getInnerElement());
324 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
325 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
326 ArtifactDefinition validatedArtifactInfo = artifactInfo;
327 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
328 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
329 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
330 if (validateArtifact.isRight()) {
331 ResponseFormat responseFormat = validateArtifact.right().value();
332 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
333 errorWrapper.setInnerElement(validateArtifact.right().value());
335 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
336 validatedArtifactInfo = validateArtifact.left().value();
337 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
340 return validatedArtifactInfo;
343 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
344 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
345 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
347 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
348 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
349 ComponentInstance componentInstance = component.getComponentInstances()
351 .filter(p -> p.getUniqueId().equals(componentId))
354 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
356 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
358 .filter(p -> p.getUniqueId()
359 .equals(validatedArtifact.getUniqueId()))
362 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
363 .getName(), user, componentId, shouldLock, inTransaction);
364 if (eitherGenerated.isRight()) {
365 errorWrapper.setInnerElement(eitherGenerated.right().value());
370 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
371 boolean needGenerate;
372 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
373 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
374 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
375 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
376 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
380 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
381 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
383 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
386 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
387 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
389 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
390 if (generated.isRight()) {
393 byte[] decodedPayload = artifactDefinition.getPayloadData();
394 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
395 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
396 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
397 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
398 shouldLock, inTransaction);
402 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
403 log.debug("tosca artifact generation");
404 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
405 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
407 if (generated.isRight()) {
408 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
411 return Either.right(generated.right().value());
413 byte[] value = generated.left().value();
414 artifactInfo.setPayload(value);
418 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
419 if (exportComponent.isRight()) {
420 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
422 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
423 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
424 return Either.right(responseFormat);
426 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
427 String payload = exportComponent.left().value().getMainYaml();
428 artifactInfo.setPayloadData(payload);
430 return Either.left(Either.left(artifactInfo));
433 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
434 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
435 switch (operation.getArtifactOperationEnum()) {
437 if (artifactGenerationRequired(parent, artifactInfo)) {
438 return generateNotSavedArtifact(parent, artifactInfo);
440 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
442 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
444 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
445 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
446 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
447 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
448 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
449 if (needUpdateGroup && result.isLeft()) {
450 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
451 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
452 .value(), parent, componentType, componentId);
453 if (error != ActionStatus.OK) {
454 result = Either.right(componentsUtils.getResponseFormat(error));
459 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
460 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
463 if (result == null) {
464 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
465 if (needUpdateGroup && result.isLeft()) {
466 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
468 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
469 .value(), parent, componentType);
470 if (error != ActionStatus.OK) {
471 result = Either.right(componentsUtils.getResponseFormat(error));
477 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
479 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
484 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
485 List<GroupDefinition> groups = parent.getGroups();
486 if (groups != null && !groups.isEmpty()) {
487 List<GroupDataDefinition> groupToUpdate = groups.stream()
488 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
489 .contains(artifactInfo
491 .collect(Collectors.toList());
492 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
493 groupToUpdate.forEach(g -> {
494 g.getArtifacts().remove(artifactInfo.getUniqueId());
495 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
496 g.getArtifacts().add(artAfterUpdate.getUniqueId());
497 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
499 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
500 if (status.isRight()) {
501 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
502 return componentsUtils.convertFromStorageResponse(status.right().value());
506 return ActionStatus.OK;
509 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
510 List<GroupDefinition> groups = parent.getGroups();
511 if (groups != null && !groups.isEmpty()) {
512 List<GroupDataDefinition> groupToUpdate = groups.stream()
513 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
514 .contains(artifactInfoHeat
516 .collect(Collectors.toList());
517 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
518 groupToUpdate.forEach(g -> {
519 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
520 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
521 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
522 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
523 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
524 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
526 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
527 if (status.isRight()) {
528 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
529 return componentsUtils.convertFromStorageResponse(status.right().value());
533 return ActionStatus.OK;
536 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
537 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
538 List<GroupInstance> groupInstances = null;
539 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
541 .filter(ci -> ci.getUniqueId().equals(parentId))
543 if (componentInstOp.isPresent()) {
544 groupInstances = componentInstOp.get().getGroupInstances();
546 if (CollectionUtils.isNotEmpty(groupInstances)) {
547 boolean isUpdated = false;
548 for (GroupInstance groupInstance : groupInstances) {
550 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
551 .contains(artifactInfo
553 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
554 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
557 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
558 .contains(artifactInfo
559 .getArtifactUUID())) {
560 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
561 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
565 updatedGroupInstances.add(groupInstance);
569 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
570 if (status.isRight()) {
571 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
572 return componentsUtils.convertFromStorageResponse(status.right().value());
574 return ActionStatus.OK;
577 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
578 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
579 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
580 result = generateToscaArtifact(parent, artifactInfo, false, false);
583 String heatArtifactId = artifactInfo.getGeneratedFromId();
584 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
585 if (heatRes.isRight()) {
586 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
588 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
591 return Either.right(responseFormat);
593 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
594 artifactInfo.setPayloadData(generatedPayload);
595 result = Either.left(Either.left(artifactInfo));
600 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
601 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
602 convertParentType(componentType);
603 String parentId = parent.getUniqueId();
604 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
605 .getGeneratedFromId());
606 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
608 if (origMd5 != null) {
609 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
610 if (validateMd5.isRight()) {
611 ResponseFormat responseFormat = validateMd5.right().value();
612 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
613 return Either.right(responseFormat);
616 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
618 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
619 if (payloadEither.isRight()) {
620 ResponseFormat responseFormat = payloadEither.right().value();
621 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
622 return Either.right(responseFormat);
626 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
627 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
628 return Either.right(responseFormat);
634 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
635 if (lockComponent.isRight()) {
636 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
637 .value(), componentType, null);
638 return Either.right(lockComponent.right().value());
641 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
643 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
649 if (resultOp == null || resultOp.isRight()) {
651 if (!inTransaction) {
657 if (!inTransaction) {
662 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
667 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
668 if (artifactGenerationRequired(component, csarArtifact)) {
669 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
671 if (generated.isRight()) {
672 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
675 return Either.right(generated.right().value());
677 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
680 return downloadArtifact(csarArtifact);
683 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
684 // perform all validation in common flow
685 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
686 null, parentId, containerComponentType);
687 if (result.isRight()) {
688 return Either.right(result.right().value());
690 ArtifactDefinition artifactDefinition;
691 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
692 if (insideValue.isLeft()) {
693 artifactDefinition = insideValue.left().value();
696 artifactDefinition = insideValue.right().value().getImplementationArtifact();
698 // for tosca artifacts and heat env on VF level generated on download without saving
699 if (artifactDefinition.getPayloadData() != null) {
700 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
703 return downloadArtifact(artifactDefinition);
706 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
708 // detect auditing type
709 Map<String, ArtifactDefinition> resMap = null;
710 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
715 if (userId == null) {
716 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
717 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
719 resultOp = Either.right(responseFormat);
723 // check user existence
727 validateUserExists(userId, "get artifacts", false);
729 // 5. check service/resource existence
730 // 6. check service/resource check out
731 // 7. user is owner of checkout state
732 org.openecomp.sdc.be.model.Component component = null;
733 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
734 ComponentParametersView componentFilter = new ComponentParametersView();
735 componentFilter.disableAll();
736 componentFilter.setIgnoreArtifacts(false);
737 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
738 componentFilter.setIgnoreComponentInstances(false);
741 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
742 .findByParamName(containerComponentType), componentFilter);
744 if (validateComponent.isRight()) {
745 resultOp = Either.right(validateComponent.right().value());
748 component = validateComponent.left().value();
749 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
750 if (lockComponent.isRight()) {
752 resultOp = Either.right(lockComponent.right().value());
757 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
759 if (groupType == null) {
760 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
761 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
763 resultOp = Either.right(responseFormat);
767 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
768 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
769 if (list != null && !list.isEmpty()) {
770 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
773 resMap = new HashMap<>();
775 resultOp = Either.left(resMap);
780 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
781 .getNodeType(), groupType, componentId);
782 if (artifactsMapStatus.isRight()) {
783 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
784 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
785 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
786 resultOp = Either.right(responseFormat);
789 resMap = new HashMap<>();
790 resultOp = Either.left(resMap);
794 resMap = artifactsMapStatus.left().value();
795 resultOp = Either.left(resMap);
802 if (resultOp == null || resultOp.isRight()) {
811 componentType = component.getComponentType();
812 NodeTypeEnum nodeType = componentType.getNodeType();
813 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
818 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
820 // check artifact existence
821 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
823 if (artifactResult.isRight()) {
824 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
825 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
826 log.debug("addArtifact - artifact {} not found", artifactId);
827 return Either.right(responseFormat);
831 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
834 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
836 return Either.right(responseFormat);
840 // check artifact belong to component
841 boolean found = false;
842 switch (componentType) {
845 found = checkArtifactInComponent(component, artifactId);
847 case RESOURCE_INSTANCE:
848 found = checkArtifactInResourceInstance(component, componentId, artifactId);
854 String componentName = componentType.name().toLowerCase();
855 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
856 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
857 return Either.right(responseFormat);
859 return Either.left(artifactResult.left().value());
862 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
863 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
865 String artifactId = null;
868 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
869 if (payloadEither.isRight()) {
870 return Either.right(payloadEither.right().value());
872 byte[] decodedPayload = payloadEither.left().value();
873 convertParentType(componentType);
876 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
877 if (lockComponent.isRight()) {
878 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
879 .value(), componentType, null);
880 return Either.right(lockComponent.right().value());
883 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
886 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
891 unlockComponent(resultOp, parent, inTransaction);
898 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
899 Component parent, boolean shouldLock, boolean inTransaction) {
902 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
903 if (lockComponent.isRight()) {
904 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
905 .value(), componentType, null);
906 return Either.right(lockComponent.right().value());
909 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
912 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
917 unlockComponent(resultOp, parent, inTransaction);
924 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
925 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
927 convertParentType(componentType);
931 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
933 if (lockComponent.isRight()) {
934 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
935 .value(), componentType, null);
936 return Either.right(lockComponent.right().value());
940 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
942 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
948 unlockComponent(resultOp, parent, inTransaction);
953 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
954 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
956 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
958 if (payloadEither.isRight()) {
959 return Either.right(payloadEither.right().value());
961 byte[] decodedPayload = payloadEither.left().value();
963 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
966 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
967 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
969 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
970 if (validateMd5.isRight()) {
971 ResponseFormat responseFormat = validateMd5.right().value();
972 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
973 return Either.right(responseFormat);
977 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
978 if (validateResult.isRight()) {
979 ResponseFormat responseFormat = validateResult.right().value();
980 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
981 return Either.right(validateResult.right().value());
984 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
985 if (payloadEither.isRight()) {
986 ResponseFormat responseFormat = payloadEither.right().value();
987 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
988 log.debug("Error during handle payload");
989 return Either.right(responseFormat);
992 // validate heat parameters. this part must be after the parameters are
993 // extracted in "handlePayload"
994 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
996 if (validateAndConvertHeatParamers.isRight()) {
997 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
998 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
999 log.debug("Error during handle payload");
1000 return Either.right(responseFormat);
1002 return payloadEither;
1005 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1006 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1008 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
1014 user.setUserId("UNKNOWN");
1016 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
1019 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1020 switch (componentTypeEnum) {
1022 Resource resource = (Resource) component;
1023 if (resource == null) {
1024 // In that case, component ID should be instead of name
1025 resource = new Resource();
1026 resource.setName(componentId);
1028 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1029 ResourceVersionInfo.newBuilder()
1030 .artifactUuid(prevArtifactUuid)
1031 .build(), currentArtifactUuid, artifactDefinition);
1035 Service service = (Service) component;
1036 if (service == null) {
1037 // In that case, component ID should be instead of name
1038 service = new Service();
1039 service.setName(componentId);
1041 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1042 ResourceVersionInfo.newBuilder()
1043 .artifactUuid(prevArtifactUuid)
1045 ResourceVersionInfo.newBuilder()
1046 .artifactUuid(currentArtifactUuid)
1048 null, artifactDefinition, null);
1051 case RESOURCE_INSTANCE:
1052 if (resourceInstanceName == null) {
1053 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1055 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1056 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1057 ResourceVersionInfo.newBuilder()
1058 .artifactUuid(prevArtifactUuid)
1060 ResourceVersionInfo.newBuilder()
1061 .artifactUuid(currentArtifactUuid)
1063 null, artifactDefinition, null);
1070 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1071 ComponentInstance resourceInstance = component.getComponentInstances()
1073 .filter(p -> p.getUniqueId().equals(componentId))
1076 String resourceInstanceName = null;
1077 if (resourceInstance != null) {
1078 resourceInstanceName = resourceInstance.getName();
1080 return resourceInstanceName;
1083 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1084 StringBuilder sb = new StringBuilder();
1085 if (artifactDefinition != null) {
1086 sb.append(artifactDefinition.getArtifactGroupType().getType())
1089 .append(artifactDefinition.getArtifactLabel())
1092 .append(artifactDefinition.getArtifactType())
1094 .append(artifactDefinition.getArtifactName())
1096 .append(artifactDefinition.getTimeout())
1098 .append(artifactDefinition.getEsId());
1101 if (artifactDefinition.getArtifactVersion() != null) {
1103 sb.append(artifactDefinition.getArtifactVersion());
1109 if (artifactDefinition.getArtifactUUID() != null) {
1110 sb.append(artifactDefinition.getArtifactUUID());
1116 return sb.toString();
1119 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1121 if (origMd5 != null) {
1122 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1123 if (!encodeBase64Str.equals(origMd5)) {
1124 log.debug("The calculated md5 is different then the received one");
1125 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1129 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1130 log.debug("Missing md5 header during artifact create");
1131 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1134 if (payload != null && payload.length != 0) {
1135 log.debug("Cannot have payload while md5 header is missing");
1136 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1139 return Either.left(true);
1142 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1143 ComponentTypeEnum componentType, Component parentComponent) {
1145 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1146 if (artifactById.isRight()) {
1147 return Either.right(artifactById.right().value());
1149 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1151 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1152 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1153 if (validateInformationalArtifactRes.isRight()) {
1154 return Either.right(validateInformationalArtifactRes.right().value());
1156 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1157 if (validateAndSetArtifactname.isRight()) {
1158 return Either.right(validateAndSetArtifactname.right().value());
1160 if (operationName != null && interfaceName != null) {
1161 operationName = operationName.toLowerCase();
1162 interfaceName = interfaceName.toLowerCase();
1164 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1165 if (logicalNameStatus.isRight()) {
1166 return Either.right(logicalNameStatus.right().value());
1168 // This is a patch to block possibility of updating service api fields
1169 // through other artifacts flow
1171 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1172 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1173 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1176 checkCreateFields(user, artifactInfo, artifactGroupType);
1179 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1180 if (currentArtifactInfo != null) {
1181 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1184 // artifactGroupType is not allowed to be updated
1185 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1186 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1187 if (validateGroupType.isRight()) {
1188 return Either.right(validateGroupType.right().value());
1191 NodeTypeEnum parentType = convertParentType(componentType);
1193 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1195 if (isDeploymentArtifact(artifactInfo)) {
1196 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1197 if (deploymentValidationResult.isRight()) {
1198 return Either.right(deploymentValidationResult.right().value());
1202 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1205 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1206 if (descriptionResult.isRight()) {
1207 return Either.right(descriptionResult.right().value());
1210 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1211 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1212 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1213 if (validateServiceApiType.isRight()) {
1214 return Either.right(validateServiceApiType.right().value());
1216 // Change of type is not allowed and should be ignored
1218 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1220 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1221 if (validateUrl.isRight()) {
1222 return Either.right(validateUrl.right().value());
1225 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1226 if (validateUpdate.isRight()) {
1227 log.debug("serviceApi first update cnnot be without payload.");
1228 return Either.right(validateUpdate.right().value());
1232 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1233 if (validateArtifactType.isRight()) {
1234 return Either.right(validateArtifactType.right().value());
1236 if (artifactInfo.getApiUrl() != null) {
1237 artifactInfo.setApiUrl(null);
1238 log.error("Artifact URL cannot be set through this API - ignoring");
1241 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1242 artifactInfo.setServiceApi(false);
1243 log.error("Artifact service API flag cannot be changed - ignoring");
1247 return Either.left(artifactInfo);
1250 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1251 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1252 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1253 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1254 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1258 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1260 Either<ArtifactDefinition, ResponseFormat> result = null;
1261 ArtifactDefinition foundArtifact = null;
1262 if (StringUtils.isNotEmpty(artifactId)) {
1263 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1265 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1266 log.debug("Artifact {} already exist", artifactId);
1267 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1269 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1270 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1271 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1273 if (result == null) {
1274 result = Either.left(foundArtifact);
1279 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1280 ArtifactDefinition foundArtifact;
1281 if (parentComponent.getUniqueId().equals(parentId)) {
1282 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1285 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1286 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1288 return foundArtifact;
1291 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1292 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1293 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1294 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1295 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1296 if (artifactType == null) {
1297 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1298 .getArtifactType()));
1300 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1301 String artifactTypeName = artifactType.getType();
1302 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1303 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1305 .getResourceInformationalArtifacts();
1306 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1307 if (!validArtifactTypes.contains(artifactTypeName)) {
1308 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1311 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1312 .getValidForResourceTypes();
1313 if (!validResourceType.contains(parentResourceType.name())) {
1314 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1318 return validationResult;
1321 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1322 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1323 return NodeTypeEnum.Resource;
1325 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1326 return NodeTypeEnum.ResourceInstance;
1329 return NodeTypeEnum.Service;
1333 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1334 boolean shouldLock, boolean inTransaction) {
1336 NodeTypeEnum parentType = convertParentType(componentType);
1337 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1338 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1339 ArtifactDefinition foundArtifact = null;
1340 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1341 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1342 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1343 boolean isDuplicated = false;
1345 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1348 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1349 if (lockComponent.isRight()) {
1350 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1351 .value(), componentType, null);
1352 resultOp = Either.right(lockComponent.right().value());
1355 if (resultOp == null) {
1356 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1357 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1358 if (getContainerRes.isRight()) {
1359 log.debug("Failed to fetch the container component {}. ", parentId);
1360 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1362 .value()), artifactId);
1363 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1364 resultOp = Either.right(responseFormat);
1367 if (resultOp == null) {
1368 fetchedContainerComponent = getContainerRes.left().value();
1369 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1370 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1371 if (getArtifactRes.isRight()) {
1372 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1374 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1375 .value(), artifactId);
1376 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1377 resultOp = Either.right(responseFormat);
1380 foundArtifact = getArtifactRes.left().value().getLeft();
1381 esId = foundArtifact.getEsId();
1384 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1385 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1386 .getComponentType()));
1387 if (needCloneRes.isRight()) {
1388 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1389 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1391 .value()), foundArtifact.getArtifactDisplayName());
1392 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1393 resultOp = Either.right(responseFormat);
1396 boolean isNeedToDeleteArtifactFromDB = true;
1397 if (resultOp == null) {
1399 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1400 String instanceId = parentId;
1401 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1403 if (isOnlyResourceInstanceArtifact.isRight()) {
1404 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1405 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1406 .value(), foundArtifact
1407 .getArtifactDisplayName());
1408 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1409 return Either.right(responseFormat);
1411 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1414 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1417 if (updatedArtifactRes.isRight()) {
1418 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1419 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1421 .value()), foundArtifact.getArtifactDisplayName());
1422 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1423 resultOp = Either.right(responseFormat);
1426 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1430 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1431 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1432 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1433 if (cassandraStatus != CassandraOperationStatus.OK) {
1434 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1435 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1436 .getArtifactDisplayName());
1437 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1438 resultOp = Either.right(responseFormat);
1441 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1443 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1447 .getGroupInstances());
1448 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1449 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1450 if (status.isRight()) {
1451 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1452 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1454 .value()), foundArtifact.getArtifactDisplayName());
1455 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1456 resultOp = Either.right(responseFormat);
1460 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1461 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1462 if (status != StorageOperationStatus.OK) {
1463 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1464 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1465 .getArtifactDisplayName());
1466 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1467 resultOp = Either.right(responseFormat);
1470 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1471 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1473 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1474 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1475 if (status.isRight()) {
1476 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1477 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1479 .value()), foundArtifact.getArtifactDisplayName());
1480 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1481 resultOp = Either.right(responseFormat);
1485 if (resultOp == null) {
1486 resultOp = Either.left(Either.left(foundArtifact));
1487 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1493 unlockComponent(resultOp, parent, inTransaction);
1498 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1499 Either<Boolean, ActionStatus> result = Either.left(true);
1500 ComponentInstance foundInstance = null;
1501 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1503 .filter(i -> i.getUniqueId().equals(instanceId))
1505 if (!componentInstanceOpt.isPresent()) {
1506 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1509 foundInstance = componentInstanceOpt.get();
1510 String componentUid = foundInstance.getComponentUid();
1511 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1512 if (getContainerRes.isRight()) {
1513 log.debug("Failed to fetch the container component {}. ", componentUid);
1514 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1516 Component origComponent = getContainerRes.left().value();
1517 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1518 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1519 Optional<String> op = deploymentArtifacts.keySet()
1521 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1523 if (op.isPresent()) {
1524 return Either.left(false);
1527 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1528 if (artifacts != null && !artifacts.isEmpty()) {
1529 Optional<String> op = artifacts.keySet()
1531 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1533 if (op.isPresent()) {
1534 return Either.left(false);
1542 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1543 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1544 boolean isUpdated = false;
1545 if (groups != null) {
1546 for (GroupDefinition group : groups) {
1548 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1549 group.getArtifacts().remove(artifactId);
1552 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1553 .contains(foundArtifact.getArtifactUUID())) {
1554 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1558 updatedGroups.add(group);
1562 return updatedGroups;
1565 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1566 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1567 if (CollectionUtils.isNotEmpty(groupInstances)) {
1568 boolean isUpdated = false;
1569 for (GroupInstance groupInstance : groupInstances) {
1571 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1572 .contains(artifactId)) {
1573 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1576 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1577 .contains(foundArtifact
1578 .getArtifactUUID())) {
1579 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1583 updatedGroupInstances.add(groupInstance);
1587 return updatedGroupInstances;
1590 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1592 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1593 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1594 String componentId = component.getUniqueId();
1595 String instanceId = componentId.equals(parentId) ? null : parentId;
1597 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1598 resetMandatoryArtifactFields(foundArtifact);
1599 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1601 else if (cloneIsNeeded) {
1602 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1603 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1606 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1607 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1612 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1614 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1615 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1616 ComponentInstance foundInstance = null;
1617 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1618 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1620 .filter(i -> i.getUniqueId()
1623 if (!componentInstanceOpt.isPresent()) {
1624 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1627 foundInstance = componentInstanceOpt.get();
1628 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1632 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1634 if (result == null) {
1635 if (artifacts.containsKey(artifactId)) {
1636 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1639 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1645 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1646 Map<String, ArtifactDefinition> currArtifacts;
1647 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1648 currArtifacts = component.getDeploymentArtifacts()
1651 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1652 if (MapUtils.isNotEmpty(currArtifacts)) {
1653 artifacts.putAll(currArtifacts);
1656 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1657 currArtifacts = component.getArtifacts()
1660 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1661 if (MapUtils.isNotEmpty(currArtifacts)) {
1662 artifacts.putAll(currArtifacts);
1665 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1666 currArtifacts = component.getToscaArtifacts()
1669 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1670 if (MapUtils.isNotEmpty(currArtifacts)) {
1671 artifacts.putAll(currArtifacts);
1676 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1677 Map<String, ArtifactDefinition> currArtifacts;
1678 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1679 currArtifacts = instance.getDeploymentArtifacts()
1682 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1683 if (MapUtils.isNotEmpty(currArtifacts)) {
1684 artifacts.putAll(currArtifacts);
1687 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1688 currArtifacts = instance.getArtifacts()
1691 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1692 if (MapUtils.isNotEmpty(currArtifacts)) {
1693 artifacts.putAll(currArtifacts);
1698 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1699 if (fetchedArtifact != null) {
1700 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1701 fetchedArtifact.setEsId(null);
1702 fetchedArtifact.setArtifactName(null);
1703 fetchedArtifact.setDescription(null);
1704 fetchedArtifact.setApiUrl(null);
1705 fetchedArtifact.setArtifactChecksum(null);
1706 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1707 fetchedArtifact.setArtifactUUID(null);
1708 long time = System.currentTimeMillis();
1709 fetchedArtifact.setPayloadUpdateDate(time);
1710 fetchedArtifact.setHeatParameters(null);
1711 fetchedArtifact.setHeatParamsUpdateDate(null);
1715 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1716 StorageOperationStatus error = StorageOperationStatus.OK;
1717 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1718 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1719 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1724 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1726 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1728 if (artifactById.isRight()) {
1729 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1730 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1731 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1732 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1733 return Either.right(responseFormat);
1735 ArtifactDefinition artifactDefinition = artifactById.left().value();
1736 if (artifactDefinition == null) {
1737 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1738 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1739 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1740 return Either.right(responseFormat);
1743 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1744 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1745 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1746 return Either.left(insideEither);
1749 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1750 ComponentTypeEnum componentType) {
1752 String artifactLabel = artifactInfo.getArtifactLabel();
1753 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1755 BeEcompErrorManager.getInstance()
1756 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1757 log.debug("missing artifact logical name for component {}", componentId);
1758 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1760 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1762 if (operationName != null) {
1763 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1764 log.debug("artifact label cannot be set {}", artifactLabel);
1765 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1768 artifactLabel = operationName;
1771 String displayName = artifactInfo.getArtifactDisplayName();
1772 if (displayName == null || displayName.isEmpty()) {
1773 displayName = artifactLabel;
1775 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1776 artifactInfo.setArtifactDisplayName(displayName);
1778 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1779 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1780 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1782 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1784 if (artifactLabel.isEmpty()) {
1785 log.debug("missing normalized artifact logical name for component {}", componentId);
1786 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1789 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1790 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1791 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1792 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1794 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1795 log.debug("Non unique Artifact label : {}", artifactLabel);
1796 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1799 artifactInfo.setArtifactLabel(artifactLabel);
1801 return Either.left(ActionStatus.OK);
1804 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1805 boolean isUnique = true;
1806 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1807 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1808 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1811 artifacts = artifactToscaOperation.getArtifacts(componentId);
1814 if (artifacts.isLeft()) {
1815 for (String label : artifacts.left().value().keySet()) {
1816 if (label.equals(artifactLabel)) {
1822 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1823 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1824 .getAllInterfacesOfResource(componentId, true, true);
1825 if (allInterfacesOfResource.isLeft()) {
1826 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1827 for (Operation operation : interace.getOperationsMap().values()) {
1828 if (operation.getImplementation() != null && operation.getImplementation()
1830 .equals(artifactLabel)) {
1841 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1842 ComponentTypeEnum componentType) {
1843 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1844 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1845 String artifactName = artifactInfo.getArtifactName();
1846 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1847 if (artifacts.left().value().values().stream()
1848 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1849 //check whether it is the same artifact we hold (by label)
1850 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1854 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1855 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1860 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1861 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1862 .getAllInterfacesOfResource(componentId, true, true);
1864 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1865 return !allInterfacesOfResource.left().value()
1867 .stream().map(InterfaceDefinition :: getOperationsMap)
1868 .flatMap(map -> map.values().stream())
1869 .map(OperationDataDefinition::getImplementation)
1870 .filter(Objects::nonNull)
1871 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1872 && !artifactLabel.equals(add.getArtifactLabel()));
1877 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1878 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1879 .getAllInterfacesOfResource(componentId, true, true);
1881 if (allInterfacesOfResource.isLeft()){
1882 return !allInterfacesOfResource.left().value()
1884 .stream().map(InterfaceDefinition :: getOperationsMap)
1885 .flatMap(map -> map.values().stream())
1886 .map(OperationDataDefinition::getImplementation)
1887 .filter(Objects::nonNull)
1888 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1893 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1894 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1895 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1896 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1897 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1900 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1902 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1903 log.debug("failed to retrieve artifacts for {} ", componentId);
1904 return Either.right(artifactsResponse.right().value());
1906 return Either.left(artifactsResponse.left().value().entrySet()
1908 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1909 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1912 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1913 return artifacts.entrySet()
1915 .map(x -> x.getValue().getArtifactName())
1916 .collect(Collectors.toList());
1919 // ***************************************************************
1921 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1922 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1923 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1924 Either<ArtifactDefinition, Operation> insideEither = null;
1925 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1926 String instanceId = null;
1927 String instanceName = null;
1928 if (foundInstance != null) {
1929 instanceId = foundInstance.getUniqueId();
1930 instanceName = foundInstance.getName();
1932 boolean isLeft = false;
1933 String artifactUniqueId = null;
1934 StorageOperationStatus error = null;
1935 // information/deployment/api aritfacts
1936 log.trace("Try to create entry on graph");
1937 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1938 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1939 .getUniqueId(), nodeType, true, instanceId);
1941 isLeft = result.isLeft();
1943 artifactUniqueId = result.left().value().getUniqueId();
1944 result.left().value();
1946 insideEither = Either.left(result.left().value());
1947 resultOp = Either.left(insideEither);
1949 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1950 if (error != StorageOperationStatus.OK) {
1956 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1957 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1961 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1962 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1963 .getArtifactDisplayName());
1964 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1965 resultOp = Either.right(responseFormat);
1971 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1972 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1974 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1975 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1976 Either<ArtifactDefinition, Operation> insideEither = null;
1977 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1978 String instanceId = null;
1979 String instanceName = null;
1980 if (foundInstance != null) {
1981 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1982 log.debug("Failed to create artifact, already exists");
1983 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1984 .getArtifactLabel());
1985 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1987 resultOp = Either.right(responseFormat);
1991 instanceId = foundInstance.getUniqueId();
1992 instanceName = foundInstance.getName();
1994 if (artifactData == null) {
1995 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1996 log.debug("Failed to create artifact object for ES.");
1997 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1998 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1999 resultOp = Either.right(responseFormat);
2003 // set on graph object id of artifact in ES!
2004 artifactInfo.setEsId(artifactData.getId());
2006 boolean isLeft = false;
2007 String artifactUniqueId = null;
2008 StorageOperationStatus error = null;
2009 if (interfaceType != null && operationName != null) {
2010 // lifecycle artifact
2011 Operation operation = convertToOperation(artifactInfo, operationName);
2013 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2015 isLeft = result.isLeft();
2017 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
2018 result.left().value().getImplementation();
2020 insideEither = Either.right(result.left().value());
2021 resultOp = Either.left(insideEither);
2024 error = result.right().value();
2028 // information/deployment/api aritfacts
2029 log.trace("Try to create entry on graph");
2030 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2031 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2032 .getUniqueId(), nodeType, true, instanceId);
2034 isLeft = result.isLeft();
2036 artifactUniqueId = result.left().value().getUniqueId();
2037 artifactData.setId(result.left().value().getEsId());
2038 insideEither = Either.left(result.left().value());
2039 resultOp = Either.left(insideEither);
2041 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2042 if (error != StorageOperationStatus.OK) {
2048 error = result.right().value();
2052 boolean res = saveArtifacts(artifactData, parentId);
2055 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2057 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2058 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2062 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2063 log.debug(FAILED_SAVE_ARTIFACT);
2064 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2065 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2067 resultOp = Either.right(responseFormat);
2072 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2073 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2074 .getArtifactDisplayName());
2075 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2076 resultOp = Either.right(responseFormat);
2082 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2083 ComponentInstance foundInstance = null;
2084 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2085 foundInstance = containerComponent.getComponentInstances()
2087 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2091 return foundInstance;
2094 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2096 Either<Boolean, ResponseFormat> result = Either.left(true);
2097 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2099 validateArtifactTypeExists(responseWrapper, artifactInfo);
2101 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2103 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2105 if (responseWrapper.isEmpty()) {
2106 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2109 // Common code for all types
2110 // not allowed to change artifactType
2111 if (responseWrapper.isEmpty() && !isCreate) {
2112 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2113 if (validateServiceApiType.isRight()) {
2114 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2117 if (responseWrapper.isEmpty()) {
2118 if (parentType.equals(NodeTypeEnum.Resource)) {
2119 Resource resource = (Resource) parentComponent;
2120 ResourceTypeEnum resourceType = resource.getResourceType();
2121 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2122 if (config == null) {
2123 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2124 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2125 .getArtifactType()));
2128 List<String> myList = config.getValidForResourceTypes();
2129 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2130 if (either.isRight()) {
2131 responseWrapper.setInnerElement(either.right().value());
2136 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2139 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2140 String artifactName = artifactInfo.getArtifactName();
2141 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2142 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2146 if (responseWrapper.isEmpty()) {
2147 switch (artifactType) {
2151 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2154 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2155 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2157 case DCAE_INVENTORY_TOSCA:
2158 case DCAE_INVENTORY_JSON:
2159 case DCAE_INVENTORY_POLICY:
2160 // Validation is done in handle payload.
2161 case DCAE_INVENTORY_DOC:
2162 case DCAE_INVENTORY_BLUEPRINT:
2163 case DCAE_INVENTORY_EVENT:
2164 // No specific validation
2166 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2172 if (!responseWrapper.isEmpty()) {
2173 result = Either.right(responseWrapper.getInnerElement());
2178 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2179 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2180 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2181 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2182 .getArtifactType());
2183 responseWrapper.setInnerElement(responseFormat);
2184 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2188 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2189 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2190 if (parentType.equals(NodeTypeEnum.Resource)) {
2191 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2193 .getResourceDeploymentArtifacts();
2195 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2196 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2198 .getResourceInstanceDeploymentArtifacts();
2201 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2203 .getServiceDeploymentArtifacts();
2205 return resourceDeploymentArtifacts;
2208 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2209 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2210 if (artifactType == null) {
2211 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2212 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2213 .getArtifactType());
2214 responseWrapper.setInnerElement(responseFormat);
2215 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2219 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2220 ArtifactTypeConfig retConfig = null;
2221 String fileType = artifactType.getType();
2222 if (parentType.equals(NodeTypeEnum.Resource)) {
2223 retConfig = ConfigurationManager.getConfigurationManager()
2225 .getResourceDeploymentArtifacts()
2228 else if (parentType.equals(NodeTypeEnum.Service)) {
2229 retConfig = ConfigurationManager.getConfigurationManager()
2231 .getServiceDeploymentArtifacts()
2234 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2235 retConfig = ConfigurationManager.getConfigurationManager()
2237 .getResourceInstanceDeploymentArtifacts()
2243 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2244 // extract heat parameters
2245 if (artifactInfo.getPayloadData() != null) {
2246 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2247 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2248 .getArtifactType());
2249 if (heatParameters.isRight() && (!heatParameters.right()
2251 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2252 log.info("failed to parse heat parameters ");
2253 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2254 .getArtifactType());
2255 return Either.right(responseFormat);
2257 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2258 artifactInfo.setListHeatParameters(heatParameters.left().value());
2261 return Either.left(true);
2266 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2267 String fileType = artifactType.getType();
2268 List<String> acceptedTypes = null;
2269 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2270 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2271 log.debug("parent type of artifact can be either resource or service");
2272 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2276 if (deploymentAcceptedTypes == null) {
2277 log.debug("parent type of artifact can be either resource or service");
2278 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2279 .getArtifactType()));
2283 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2286 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2289 String artifactName = artifactInfo.getArtifactName();
2290 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2291 // Pavel - File extension validation is case-insensitive - Ella,
2293 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2294 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2295 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2300 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2302 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2303 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2304 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2306 if (errorWrapper.isEmpty()) {
2307 validateValidYaml(errorWrapper, artifactInfo);
2310 if (errorWrapper.isEmpty()) {
2311 // Validate Heat Exist
2312 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2313 .getComponentType());
2316 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2317 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2320 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2321 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2325 Either<Boolean, ResponseFormat> eitherResponse;
2326 if (errorWrapper.isEmpty()) {
2327 eitherResponse = Either.left(true);
2330 eitherResponse = Either.right(errorWrapper.getInnerElement());
2332 return eitherResponse;
2335 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2336 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2337 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2338 if (fillArtifactPayload.isRight()) {
2339 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2340 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2344 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2348 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2349 Either<Boolean, ResponseFormat> result = Either.left(true);
2350 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2352 if (eitherArtifactData.isLeft()) {
2353 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2354 data = Base64.encodeBase64(data);
2355 payloadWrapper.setInnerElement(data);
2358 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2361 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2362 result = Either.right(responseFormat);
2368 @SuppressWarnings("unchecked")
2369 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2370 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2371 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2372 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2373 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2375 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2376 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2377 if (eitherHeatEnvProperties.isRight()) {
2378 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2379 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2380 errorWrapper.setInnerElement(responseFormat);
2381 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2383 else if (eitherHeatProperties.isRight()) {
2384 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2385 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2386 .getArtifactName(), heatArtifact.getArtifactName());
2387 errorWrapper.setInnerElement(responseFormat);
2388 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2389 .getArtifactName());
2392 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2393 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2394 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2395 if (!heatEnvPropertiesKeys.isEmpty()) {
2396 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2397 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2398 .getArtifactName(), heatArtifact.getArtifactName());
2399 errorWrapper.setInnerElement(responseFormat);
2404 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2405 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2406 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2408 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2409 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2410 .getArtifactType());
2411 errorWrapper.setInnerElement(responseFormat);
2412 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2416 private boolean isValidXml(byte[] xmlToParse) {
2417 boolean isXmlValid = true;
2419 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2420 setFeatures(reader);
2421 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2423 catch (ParserConfigurationException | IOException | SAXException e) {
2424 log.debug("Xml is invalid : {}", e.getMessage(), e);
2430 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2432 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2433 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2435 catch (SAXNotRecognizedException e) {
2436 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2440 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2441 boolean artifactNameFound = false;
2442 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2445 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2446 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2448 if (artifactNameFound) {
2449 String parentName = parentComponent.getName();
2450 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2451 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2452 .name(), parentName, artifactName);
2454 errorWrapper.setInnerElement(responseFormat);
2455 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2460 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2461 ComponentTypeEnum componentType) {
2462 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2463 if (res.isRight()) {
2464 ResponseFormat responseFormat;
2465 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2466 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2469 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2471 errorWrapper.setInnerElement(responseFormat);
2474 ArtifactDefinition heatArtifact = res.left().value();
2475 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2478 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2479 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2480 // timeout > 0 for HEAT artifacts
2481 Integer timeout = artifactInfo.getTimeout();
2482 if (timeout == null) {
2483 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2484 artifactInfo.setTimeout(defaultTimeout);
2485 // HEAT artifact but timeout is invalid
2487 else if (timeout < 1) {
2488 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2491 // US649856 - Allow several HEAT files on Resource
2492 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2493 return Either.left(true);
2496 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2497 String listToString = (typeList != null) ? typeList.toString() : "";
2498 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2499 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2500 .getArtifactName(), listToString, resourceType.getValue());
2501 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2502 String resourceTypeName = resourceType.name();
2503 if (typeList != null && typeList.contains(resourceTypeName)) {
2504 either = Either.left(true);
2509 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2510 if (artifactInfo.getHeatParameters() != null) {
2511 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2512 String parameterType = heatParam.getType();
2513 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2514 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2515 if (heatParameterType == null) {
2516 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2518 return Either.right(responseFormat);
2521 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2522 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2523 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2524 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2525 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2526 .getType(), heatParam.getName());
2527 return Either.right(responseFormat);
2531 return Either.left(artifactInfo);
2534 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2535 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2536 if (parentComponent.getDeploymentArtifacts() != null) {
2537 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2538 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2539 if (getRI.isRight()) {
2540 return deploymentArtifacts;
2542 ComponentInstance ri = getRI.left().value();
2543 if (ri.getDeploymentArtifacts() != null) {
2544 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2547 else if (parentComponent.getDeploymentArtifacts() != null) {
2548 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2551 return deploymentArtifacts;
2554 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2555 // on create if null add informational to current
2556 if (artifactInfo.getArtifactGroupType() == null) {
2557 artifactInfo.setArtifactGroupType(type);
2559 if (artifactInfo.getUniqueId() != null) {
2560 log.error("artifact uniqid cannot be set ignoring");
2562 artifactInfo.setUniqueId(null);
2564 if (artifactInfo.getArtifactRef() != null) {
2565 log.error("artifact ref cannot be set ignoring");
2567 artifactInfo.setArtifactRef(null);
2569 if (artifactInfo.getArtifactRepository() != null) {
2570 log.error("artifact repository cannot be set ignoring");
2572 artifactInfo.setArtifactRepository(null);
2574 if (artifactInfo.getUserIdCreator() != null) {
2575 log.error("creator uuid cannot be set ignoring");
2577 artifactInfo.setArtifactCreator(user.getUserId());
2579 if (artifactInfo.getUserIdLastUpdater() != null) {
2580 log.error("userId of last updater cannot be set ignoring");
2582 artifactInfo.setUserIdLastUpdater(user.getUserId());
2584 if (artifactInfo.getCreatorFullName() != null) {
2585 log.error("creator Full name cannot be set ignoring");
2587 String fullName = user.getFirstName() + " " + user.getLastName();
2588 artifactInfo.setUpdaterFullName(fullName);
2590 if (artifactInfo.getUpdaterFullName() != null) {
2591 log.error("updater Full name cannot be set ignoring");
2593 artifactInfo.setUpdaterFullName(fullName);
2595 if (artifactInfo.getCreationDate() != null) {
2596 log.error("Creation Date cannot be set ignoring");
2598 long time = System.currentTimeMillis();
2599 artifactInfo.setCreationDate(time);
2601 if (artifactInfo.getLastUpdateDate() != null) {
2602 log.error("Last Update Date cannot be set ignoring");
2604 artifactInfo.setLastUpdateDate(time);
2606 if (artifactInfo.getEsId() != null) {
2607 log.error("es id cannot be set ignoring");
2609 artifactInfo.setEsId(null);
2614 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2615 String id = artifactId;
2616 if (artifactId == null || artifactId.isEmpty()) {
2617 String uniqueId = null;
2618 if (interfaceName != null && operationName != null) {
2619 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2620 .getArtifactLabel());
2623 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2625 artifactInfo.setUniqueId(uniqueId);
2626 artifactInfo.setEsId(uniqueId);
2630 artifactInfo.setUniqueId(artifactId);
2631 artifactInfo.setEsId(artifactId);
2636 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2637 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2638 BeEcompErrorManager.getInstance()
2639 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2640 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2641 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2644 boolean artifactTypeExist = false;
2645 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2646 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2648 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2649 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2653 allArtifactTypes = elementOperation.getAllArtifactTypes();
2655 if (allArtifactTypes.isRight()) {
2656 BeEcompErrorManager.getInstance()
2657 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2661 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2663 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2666 for (ArtifactType type : allArtifactTypes.left().value()) {
2667 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2668 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2669 artifactTypeExist = true;
2674 if (!artifactTypeExist) {
2675 BeEcompErrorManager.getInstance()
2676 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2677 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2678 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2679 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2680 .getArtifactType()));
2683 return Either.left(ActionStatus.OK);
2686 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2688 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2689 List<ArtifactType> artifactTypes = new ArrayList<>();
2691 if (parentType.equals(NodeTypeEnum.Service)) {
2692 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2694 .getServiceDeploymentArtifacts();
2696 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2697 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2699 .getResourceInstanceDeploymentArtifacts();
2702 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2704 .getResourceDeploymentArtifacts();
2706 if (deploymentArtifacts != null) {
2707 for (String artifactType : deploymentArtifacts.keySet()) {
2708 ArtifactType artifactT = new ArtifactType();
2709 artifactT.setName(artifactType);
2710 artifactTypes.add(artifactT);
2712 return Either.left(artifactTypes);
2715 return Either.right(ActionStatus.GENERAL_ERROR);
2720 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2721 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2722 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2724 return Either.left(true);
2728 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2729 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2730 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2733 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2734 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2735 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2737 artifactInfo.setArtifactName(normalizeFileName);
2739 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2740 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2743 return Either.left(true);
2746 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2747 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2748 log.info("artifact type is missing operation ignored");
2749 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2752 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2753 log.info("artifact type cannot be changed operation ignored");
2754 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2756 return Either.left(true);
2759 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2760 if (artifactInfo.getArtifactGroupType() == null) {
2761 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2764 else if (!currentArtifact.getArtifactGroupType()
2766 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2767 log.info("artifact group type cannot be changed. operation failed");
2768 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2770 return Either.left(artifactInfo);
2773 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2775 // on update if null add informational to current
2776 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2777 currentArtifact.setArtifactGroupType(type);
2780 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2781 log.error("artifact uniqid cannot be set ignoring");
2783 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2785 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2786 .equals(artifactInfo.getArtifactRef())) {
2787 log.error("artifact ref cannot be set ignoring");
2789 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2791 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2792 .equals(artifactInfo.getArtifactRepository())) {
2793 log.error("artifact repository cannot be set ignoring");
2795 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2797 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2798 .equals(artifactInfo.getUserIdCreator())) {
2799 log.error("creator uuid cannot be set ignoring");
2801 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2803 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2804 .equals(artifactInfo.getArtifactCreator())) {
2805 log.error("artifact creator cannot be set ignoring");
2807 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2809 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2810 .equals(artifactInfo.getUserIdLastUpdater())) {
2811 log.error("userId of last updater cannot be set ignoring");
2813 artifactInfo.setUserIdLastUpdater(user.getUserId());
2815 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2816 .equals(artifactInfo.getCreatorFullName())) {
2817 log.error("creator Full name cannot be set ignoring");
2819 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2821 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2822 .equals(artifactInfo.getUpdaterFullName())) {
2823 log.error("updater Full name cannot be set ignoring");
2825 String fullName = user.getFirstName() + " " + user.getLastName();
2826 artifactInfo.setUpdaterFullName(fullName);
2828 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2829 .equals(artifactInfo.getCreationDate())) {
2830 log.error("Creation Date cannot be set ignoring");
2832 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2834 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2835 .equals(artifactInfo.getLastUpdateDate())) {
2836 log.error("Last Update Date cannot be set ignoring");
2838 long time = System.currentTimeMillis();
2839 artifactInfo.setLastUpdateDate(time);
2841 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2842 log.error("es id cannot be set ignoring");
2844 artifactInfo.setEsId(currentArtifact.getUniqueId());
2846 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2847 .equals(artifactInfo.getArtifactDisplayName())) {
2848 log.error(" Artifact Display Name cannot be set ignoring");
2850 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2852 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2853 .equals(artifactInfo.getServiceApi())) {
2854 log.debug("serviceApi cannot be set. ignoring.");
2856 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2858 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2859 .equals(artifactInfo.getArtifactGroupType())) {
2860 log.debug("artifact group cannot be set. ignoring.");
2862 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2864 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2866 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2867 .isEmpty() && !currentArtifact.getArtifactUUID()
2868 .equals(artifactInfo.getArtifactUUID())) {
2869 log.debug("artifact UUID cannot be set. ignoring.");
2871 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2873 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2874 .getHeatParameters()
2875 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2876 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2880 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2882 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2883 for (HeatParameterDefinition parameter : heatParameters) {
2884 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2886 if (currentParam != null) {
2888 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2889 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2890 parameter.setName(currentParam.getName());
2892 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2893 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2894 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2895 parameter.setDefaultValue(currentParam.getDefaultValue());
2897 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2898 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2899 parameter.setType(currentParam.getType());
2901 if (parameter.getDescription() != null && !parameter.getDescription()
2902 .equalsIgnoreCase(currentParam.getDescription())) {
2903 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2904 parameter.setDescription(currentParam.getDescription());
2907 // check and set current value
2908 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2909 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2910 parameter.setCurrentValue(currentParam.getDefaultValue());
2916 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2918 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2919 for (HeatParameterDefinition param : currentParameters) {
2920 currentParamsMap.put(param.getUniqueId(), param);
2922 return currentParamsMap;
2925 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2926 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2927 log.debug("Artifact url cannot be empty.");
2928 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2930 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2932 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2933 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2935 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2936 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2939 return Either.left(true);
2942 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2943 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2944 log.debug("Artifact description cannot be empty.");
2945 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2947 String description = artifactInfo.getDescription();
2948 description = ValidationUtils.removeNoneUtf8Chars(description);
2949 description = ValidationUtils.normaliseWhitespace(description);
2950 description = ValidationUtils.stripOctets(description);
2951 description = ValidationUtils.removeHtmlTagsOnly(description);
2952 if (!ValidationUtils.validateIsEnglish(description)) {
2953 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2955 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2956 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2957 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2959 artifactInfo.setDescription(description);
2960 return Either.left(true);
2963 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2964 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2965 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2966 String prevArtifactId = null;
2967 String currArtifactId = artifactId;
2969 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2970 Either<ArtifactDefinition, Operation> insideEither = null;
2972 log.trace("Try to update entry on graph");
2973 String artifactUniqueId = null;
2974 ArtifactDefinition artifactDefinition = artifactInfo;
2975 StorageOperationStatus error;
2978 if (interfaceType == null || operationUuid == null) {
2979 log.debug("Entity on graph is updated. Update artifact in ES");
2981 // Changing previous and current artifactId for auditing
2982 prevArtifactId = currArtifactId;
2983 currArtifactId = artifactDefinition.getUniqueId();
2986 if (decodedPayload == null) {
2987 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2988 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2990 if (artifactFromCassandra.isRight()) {
2991 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2992 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2994 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2995 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2996 resultOp = Either.right(responseFormat);
2999 // clone data to new artifact
3000 artifactData.setData(artifactFromCassandra.left().value().getData());
3001 artifactData.setId(artifactFromCassandra.left().value().getId());
3004 if (artifactDefinition.getEsId() == null) {
3005 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3006 artifactData.setId(artifactDefinition.getUniqueId());
3010 NodeTypeEnum convertParentType = convertParentType(componentType);
3011 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
3012 .getUniqueId(), artifactId, convertParentType, parentId);
3013 isLeft = result.isLeft();
3015 artifactUniqueId = result.left().value().getUniqueId();
3016 artifactDefinition = result.left().value();
3017 String artifactType = artifactInfo.getArtifactType();
3018 if (NodeTypeEnum.Resource == convertParentType
3019 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3020 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3021 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3022 && !artifactUniqueId.equals(artifactId)) {
3023 // need to update the generated id in heat env
3024 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3025 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3027 .filter(a -> a.getValue()
3028 .getGeneratedFromId() != null && a
3030 .getGeneratedFromId()
3031 .equals(artifactId))
3033 if (findFirst.isPresent()) {
3034 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3035 artifactEnvInfo.setArtifactChecksum(null);
3036 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3039 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3041 insideEither = Either.left(result.left().value());
3042 resultOp = Either.left(insideEither);
3043 if (error != StorageOperationStatus.OK) {
3048 error = result.right().value();
3052 // create new entry in ES
3054 if (artifactData.getData() != null) {
3055 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3056 artifactData.setId(artifactDefinition.getEsId());
3058 res = saveArtifacts(artifactData, parentId);
3064 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3065 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3066 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3068 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3069 log.debug(FAILED_SAVE_ARTIFACT);
3070 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3071 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3072 resultOp = Either.right(responseFormat);
3075 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3076 decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3077 currArtifactId, artifactDefinition);
3083 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3084 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3085 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3086 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3087 ArtifactDefinition artifactDefinition) {
3088 StorageOperationStatus error;
3089 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3090 if (decodedPayload == null) {
3091 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3092 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3094 if (artifactFromCassandra.isRight()) {
3095 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3096 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3098 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3099 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3100 resultOp = Either.right(responseFormat);
3103 // clone data to new artifact
3104 artifactData.setData(artifactFromCassandra.left().value().getData());
3105 artifactData.setId(artifactFromCassandra.left().value().getId());
3107 // todo if not exist(first time)
3111 if (artifactDefinition.getEsId() == null) {
3112 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3113 artifactData.setId(artifactDefinition.getUniqueId());
3116 NodeTypeEnum convertParentType = convertParentType(componentType);
3117 // Set additional fields for artifact
3118 artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
3119 artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
3121 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
3122 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
3123 if(updateArtifactOnResourceEither.isRight()){
3124 log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
3125 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
3126 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3128 if (artifactData.getData() != null) {
3129 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3130 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3131 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
3132 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3133 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3134 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3138 Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
3139 if(updateOprEither.isRight()){
3140 return Either.right(updateOprEither.right().value());
3143 return Either.left(Either.left(updateOprEither.left().value()));
3146 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3147 log.trace("Starting payload handling");
3148 byte[] payload = artifactInfo.getPayloadData();
3149 byte[] decodedPayload = null;
3151 if (payload != null && payload.length != 0) {
3152 // the generated artifacts were already decoded by the handler
3153 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3154 if (decodedPayload.length == 0) {
3155 log.debug("Failed to decode the payload.");
3156 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3157 return Either.right(responseFormat);
3160 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3161 artifactInfo.setArtifactChecksum(checkSum);
3162 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3164 // Specific payload validations of different types
3165 Either<Boolean, ResponseFormat> result = Either.left(true);
3166 if (isDeploymentArtifact(artifactInfo)) {
3167 log.trace("Starting deployment artifacts payload validation");
3168 String artifactType = artifactInfo.getArtifactType();
3169 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
3170 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
3171 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
3172 if (isPayloadValid.isRight()) {
3173 ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
3174 return Either.right(responseFormat);
3177 if (payloadType.isHeatRelated()) {
3178 log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
3179 result = extractHeatParameters(artifactInfo);
3182 if (result.isRight()) {
3183 return Either.right(result.right().value());
3186 } // null/empty payload is normal if called from metadata update ONLY.
3187 // The validation of whether this is metadata/payload update case is
3188 // currently done separately
3190 if (!isArtifactMetadataUpdate) {
3191 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3192 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3193 return Either.right(responseFormat);
3196 log.trace("Ended payload handling");
3197 return Either.left(decodedPayload);
3200 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3201 boolean inTransaction) {
3202 User user = new User();
3203 user.setUserId(userUserId);
3204 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3205 if (parent.isRight()) {
3206 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3209 return Either.right(responseFormat);
3211 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3214 false, inTransaction);
3215 if (handleDelete.isRight()) {
3216 return Either.right(handleDelete.right().value());
3218 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3219 return Either.left(result.right().value());
3223 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3224 Operation op = new Operation();
3225 long time = System.currentTimeMillis();
3226 op.setCreationDate(time);
3228 String artifactName = artifactInfo.getArtifactName();
3229 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3231 op.setImplementation(artifactInfo);
3232 op.setLastUpdateDate(time);
3236 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3237 String newArtifactName = operationName + "_" + artifactName;
3238 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3239 return newArtifactName;
3243 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3245 // General validation
3246 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3247 log.debug(NULL_PARAMETER);
3248 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3251 // Normalizing artifact name
3252 artifactName = ValidationUtils.normalizeFileName(artifactName);
3254 // Resource validation
3255 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3256 if (validateResourceNameAndVersion.isRight()) {
3257 return Either.right(validateResourceNameAndVersion.right().value());
3260 Resource resource = validateResourceNameAndVersion.left().value();
3261 String resourceId = resource.getUniqueId();
3263 // Service validation
3264 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3265 if (validateServiceNameAndVersion.isRight()) {
3266 return Either.right(validateServiceNameAndVersion.right().value());
3269 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3270 if (artifacts == null || artifacts.isEmpty()) {
3271 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3272 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3275 ArtifactDefinition deploymentArtifact = null;
3277 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3278 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3279 .equals(artifactName)) {
3280 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3281 deploymentArtifact = artifactDefinition;
3286 if (deploymentArtifact == null) {
3287 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3288 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3291 // Downloading the artifact
3292 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3293 if (downloadArtifactEither.isRight()) {
3294 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3295 return Either.right(downloadArtifactEither.right().value());
3297 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3298 return Either.left(downloadArtifactEither.left().value().getRight());
3302 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3304 // General validation
3305 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3306 log.debug(NULL_PARAMETER);
3307 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3310 // Normalizing artifact name
3311 artifactName = ValidationUtils.normalizeFileName(artifactName);
3313 // Service validation
3314 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3315 if (validateServiceNameAndVersion.isRight()) {
3316 return Either.right(validateServiceNameAndVersion.right().value());
3319 Service service = validateServiceNameAndVersion.left().value();
3321 // ResourceInstance validation
3322 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3323 if (validateResourceInstance.isRight()) {
3324 return Either.right(validateResourceInstance.right().value());
3327 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3329 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3331 final String finalArtifactName = artifactName;
3332 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3334 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3336 .anyMatch(filterArtifactByName);
3337 ArtifactDefinition deployableArtifact;
3339 if (!hasDeploymentArtifacts) {
3340 log.debug("Deployment artifact with name {} not found", artifactName);
3341 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3344 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3345 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3346 // Downloading the artifact
3347 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3349 if (downloadArtifactEither.isRight()) {
3350 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3351 return Either.right(downloadArtifactEither.right().value());
3353 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3354 return Either.left(downloadArtifactEither.left().value().getRight());
3357 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3359 List<ComponentInstance> riList = service.getComponentInstances();
3360 for (ComponentInstance ri : riList) {
3361 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3362 return Either.left(ri);
3366 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3369 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3371 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3372 if (serviceListBySystemName.isRight()) {
3373 log.debug("Couldn't fetch any service with name {}", serviceName);
3374 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3376 .value(), ComponentTypeEnum.SERVICE), serviceName));
3378 List<Service> serviceList = serviceListBySystemName.left().value();
3379 if (serviceList == null || serviceList.isEmpty()) {
3380 log.debug("Couldn't fetch any service with name {}", serviceName);
3381 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3384 Service foundService = null;
3385 for (Service service : serviceList) {
3386 if (service.getVersion().equals(serviceVersion)) {
3387 log.trace("Found service with version {}", serviceVersion);
3388 foundService = service;
3393 if (foundService == null) {
3394 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3395 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3396 .getValue(), serviceVersion));
3398 return Either.left(foundService);
3401 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3403 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3404 if (resourceListBySystemName.isRight()) {
3405 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3406 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3408 .value()), resourceName));
3410 return Either.left(resourceListBySystemName.left().value());
3413 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3415 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3416 if (serviceName == null || serviceVersion == null || artifactName == null) {
3417 log.debug(NULL_PARAMETER);
3418 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3421 // Normalizing artifact name
3422 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3424 // Service validation
3425 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3426 if (validateServiceNameAndVersion.isRight()) {
3427 return Either.right(validateServiceNameAndVersion.right().value());
3430 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3432 // Looking for deployment or tosca artifacts
3433 Service service = validateServiceNameAndVersion.left().value();
3435 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3436 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3437 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3440 Optional<ArtifactDefinition> foundArtifactOptl = null;
3442 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3443 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3444 // filters artifact by name
3445 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3447 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3448 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3449 // filters TOSCA artifact by name
3450 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3452 if (!foundArtifactOptl.isPresent()) {
3453 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3454 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3456 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3457 // Downloading the artifact
3458 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3460 if (downloadArtifactEither.isRight()) {
3461 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3462 return Either.right(downloadArtifactEither.right().value());
3464 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3465 return Either.left(downloadArtifactEither.left().value().getRight());
3468 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3469 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3470 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3471 if (artifactById.isRight()) {
3472 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3473 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3474 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3476 ArtifactDefinition artifactDefinition = artifactById.left().value();
3477 if (artifactDefinition == null) {
3478 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3479 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3482 return downloadArtifact(artifactDefinition);
3485 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3486 boolean found = false;
3487 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3488 if (artifactsS != null) {
3489 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3490 if (entry.getValue().getUniqueId().equals(artifactId)) {
3496 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3497 if (!found && deploymentArtifactsS != null) {
3498 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3499 if (entry.getValue().getUniqueId().equals(artifactId)) {
3505 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3506 if (!found && toscaArtifactsS != null) {
3507 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3508 if (entry.getValue().getUniqueId().equals(artifactId)) {
3515 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3516 if (!found && interfaces != null) {
3517 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3518 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3519 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3520 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3521 .getImplementation()
3523 .equals(artifactId)) {
3531 switch (component.getComponentType()) {
3535 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3536 if (!found && apiArtifacts != null) {
3537 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3538 if (entry.getValue().getUniqueId().equals(artifactId)) {
3552 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3554 boolean found = false;
3555 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3556 ComponentInstance resourceInstance = null;
3557 for (ComponentInstance ri : resourceInstances) {
3558 if (ri.getUniqueId().equals(resourceInstanceId)) {
3559 resourceInstance = ri;
3563 if (resourceInstance != null) {
3564 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3565 if (artifacts != null) {
3566 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3567 if (entry.getValue().getUniqueId().equals(artifactId)) {
3574 artifacts = resourceInstance.getArtifacts();
3575 if (artifacts != null) {
3576 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3577 if (entry.getValue().getUniqueId().equals(artifactId)) {
3588 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3589 String containerComponentType) {
3591 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3592 componentForAudit.getNodeType();
3594 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3595 .getToscaFullElement(componentId);
3597 if (componentResult.isRight()) {
3598 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3599 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3600 log.debug("Service not found, serviceId {}", componentId);
3601 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3602 return Either.right(responseFormat);
3604 return Either.left(componentResult.left().value());
3607 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3608 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3609 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3610 if (canWork.isRight()) {
3611 String uniqueId = component.getUniqueId();
3612 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3613 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3615 .getComponentType(), null);
3616 return Either.right(canWork.right().value());
3619 return Either.left(true);
3622 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3624 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3625 String role = user.getRole();
3626 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3627 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3628 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3629 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3630 return Either.right(responseFormat);
3633 return Either.left(true);
3636 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3639 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3640 } catch(ComponentException e){
3642 user.setUserId(userId);
3643 ResponseFormat responseFormat = e.getResponseFormat() != null ? e.getResponseFormat() :
3644 componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3645 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3648 return Either.left(user);
3651 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3652 AuditingActionEnum auditingAction = null;
3653 switch (operation.getArtifactOperationEnum()) {
3655 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3658 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3661 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3664 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3669 return auditingAction;
3672 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3673 String esArtifactId = artifactDefinition.getEsId();
3674 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3675 if (artifactfromES.isRight()) {
3676 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3677 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3678 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3679 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3680 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3681 .getArtifactDisplayName());
3683 return Either.right(responseFormat);
3686 ESArtifactData esArtifactData = artifactfromES.left().value();
3687 byte[] data = esArtifactData.getDataAsArray();
3689 log.debug("Artifact data from ES is null");
3690 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3692 String artifactName = artifactDefinition.getArtifactName();
3693 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3694 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3697 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3698 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3701 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3702 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3704 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3705 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3708 log.info("Failed to save artifact {}.", artifactData.getId());
3714 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3715 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3718 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3719 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3722 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3723 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3724 if (user.isRight()) {
3725 ResponseFormat responseFormat;
3726 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3727 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3728 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3731 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3732 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3734 return Either.right(responseFormat);
3737 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3739 .value(), groupType);
3740 return Either.left(artifactDefinition);
3743 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3744 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3746 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3747 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3748 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3750 artifactInfo.setArtifactDisplayName(artifactName);
3751 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3752 artifactInfo.setArtifactType(artifactType);
3753 artifactInfo.setDescription(artifactDescription);
3754 artifactInfo.setArtifactGroupType(groupType);
3755 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3757 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3759 return artifactInfo;
3762 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3763 String uniqueId = null;
3765 if (resourceId != null) {
3766 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3768 artifactInfo.setUniqueId(uniqueId);
3770 artifactInfo.setUserIdCreator(user.getUserId());
3771 String fullName = user.getFullName();
3772 artifactInfo.setUpdaterFullName(fullName);
3774 long time = System.currentTimeMillis();
3776 artifactInfo.setCreatorFullName(fullName);
3777 artifactInfo.setCreationDate(time);
3779 artifactInfo.setLastUpdateDate(time);
3780 artifactInfo.setUserIdLastUpdater(user.getUserId());
3782 artifactInfo.setMandatory(true);
3785 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3786 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3789 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3790 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3793 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3795 byte[] payload = payloadStr.getBytes();
3797 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3798 return Either.left(artifactData);
3802 * @param artifactDefinition
3805 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3806 String instanceId, boolean shouldLock, boolean inTransaction) {
3807 String payload = generateHeatEnvPayload(artifactDefinition);
3808 String prevUUID = artifactDefinition.getArtifactUUID();
3809 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3810 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3812 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3815 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3816 boolean shouldLock, boolean inTransaction, String instanceId) {
3817 String payload = generateHeatEnvPayload(artifactDefinition);
3818 String prevUUID = artifactDefinition.getArtifactUUID();
3819 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3820 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3822 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3825 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3826 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3827 List<ComponentInstance> componentInstances = component.getComponentInstances();
3828 if (componentInstances != null) {
3829 Optional<ComponentInstance> findFirst = componentInstances.stream()
3830 .filter(ci -> ci.getUniqueId()
3831 .equals(instanceId))
3833 if (findFirst.isPresent()) {
3834 ComponentInstance relevantInst = findFirst.get();
3835 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3836 .getGroupInstances());
3838 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3839 updatedGroupInstances.forEach(gi -> {
3840 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3841 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3843 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3844 if (status.isRight()) {
3845 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3846 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3847 .convertFromStorageResponse(status.right()
3848 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3849 return Either.right(responseFormat);
3855 return Either.left(updatedArtDef);
3858 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3859 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3860 StringBuilder sb = new StringBuilder();
3861 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3862 sb.append("parameters:\n");
3863 if (heatParameters != null) {
3864 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3866 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3868 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3870 String heatValue = heatParameterDefinition.getCurrentValue();
3871 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3872 heatValue = heatParameterDefinition.getDefaultValue();
3873 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3874 empltyHeatValues.add(heatParameterDefinition);
3878 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3883 .append(heatParameterDefinition.getName())
3886 .append(Boolean.parseBoolean(heatValue))
3891 .append(heatParameterDefinition.getName())
3894 .append(new BigDecimal(heatValue).toPlainString())
3897 case COMMA_DELIMITED_LIST:
3900 .append(heatParameterDefinition.getName())
3907 String value = heatValue;
3908 boolean starts = value.startsWith("\"");
3909 boolean ends = value.endsWith("\"");
3910 if (!(starts && ends)) {
3911 starts = value.startsWith("'");
3912 ends = value.endsWith("'");
3913 if (!(starts && ends)) {
3914 value = "\"" + value + "\"";
3918 .append(heatParameterDefinition.getName())
3928 if (!empltyHeatValues.isEmpty()) {
3929 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3930 empltyHeatValues.forEach(hv -> {
3931 sb.append(" ").append(hv.getName()).append(":");
3932 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3933 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3934 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3935 sb.append(" \"\"").append("\n");
3938 sb.append(" ").append("\n");
3943 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3946 return sb.toString().replaceAll("\\\\n", "\n");
3950 * @param artifactDefinition
3954 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3955 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3956 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
3957 .getHeatParamsUpdateDate(),
3958 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3962 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3963 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3964 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3965 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3969 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3970 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3972 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3974 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3975 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3977 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3978 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3979 ESArtifactData artifactData = null;
3981 if (artifactDataRes.isLeft()) {
3982 artifactData = artifactDataRes.left().value();
3985 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3986 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3987 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3988 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3990 return Either.right(artifactDataRes.right().value());
3992 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
3994 String esArtifactId = artifactDefinition.getEsId();
3995 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3996 ESArtifactData esArtifactData;
3997 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3998 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
3999 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4000 if (artifactfromES.isRight()) {
4001 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4002 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4003 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4004 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4005 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4007 esArtifactData = artifactfromES.left().value();
4008 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4011 oldCheckSum = artifactDefinition.getArtifactChecksum();
4014 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4017 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4018 if (lockComponent.isRight()) {
4019 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4020 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4021 return Either.right(lockComponent.right().value());
4025 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4027 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4028 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4029 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4030 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4031 .getArtifactType(), artifactDefinition.getEsId());
4032 if (updateArifactDefinitionStatus.isRight()) {
4033 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4035 .value()), artifactDefinition.getArtifactDisplayName());
4036 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4037 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4038 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4039 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4041 return Either.right(responseFormat);
4046 oldCheckSum = artifactDefinition.getArtifactChecksum();
4047 artifactDefinition.setArtifactChecksum(newCheckSum);
4048 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4049 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4050 .getArtifactType(), artifactDefinition.getEsId());
4051 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4052 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4054 log.trace("Update Payload ", artifactDefinition.getEsId());
4056 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4058 artifactDefinition = updateArifactDefinitionStatus.left().value();
4059 artifactData.setId(artifactDefinition.getUniqueId());
4060 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4062 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4063 if (!inTransaction) {
4066 log.debug("Artifact Saved In ES {}", artifactData.getId());
4067 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4068 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4069 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4070 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4074 if (!inTransaction) {
4075 titanDao.rollback();
4077 log.info("Failed to save artifact {}.", artifactData.getId());
4078 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4079 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4080 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4081 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4083 return Either.right(responseFormat);
4087 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4089 .value()), artifactDefinition.getArtifactDisplayName());
4090 log.debug("Failed To update artifact {}", artifactData.getId());
4091 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4092 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4093 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4095 return Either.right(responseFormat);
4101 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4107 return Either.left(artifactDefinition);
4111 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4112 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4113 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4114 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4118 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4119 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4121 Map<String, Object> json = new HashMap<>();
4122 if (artifactId != null && !artifactId.isEmpty()) {
4123 json.put(Constants.ARTIFACT_ID, artifactId);
4126 json.put(Constants.ARTIFACT_NAME, artifactName);
4127 json.put(Constants.ARTIFACT_TYPE, artifactType);
4128 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4130 if (artifactContent != null) {
4131 log.debug("payload is encoded. perform decode");
4132 String encodedPayload = Base64.encodeBase64String(artifactContent);
4133 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4135 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4136 json.put(Constants.ARTIFACT_LABEL, label);
4137 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4138 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4139 : updatedRequiredArtifacts.stream()
4140 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4142 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4143 .map(e -> e.getFileName())
4144 .collect(Collectors.toList()));
4145 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4150 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4152 String jsonStr = gson.toJson(json);
4153 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4154 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4155 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4156 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4157 if (uploadArtifactToService.isRight()) {
4158 return Either.right(uploadArtifactToService.right().value());
4161 return Either.left(uploadArtifactToService.left().value());
4164 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4165 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4166 convertParentType(componentType);
4167 String parentId = parent.getUniqueId();
4168 ArtifactDefinition currArtifact = artifactInfo;
4170 if (origMd5 != null) {
4171 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4172 if (validateMd5.isRight()) {
4173 ResponseFormat responseFormat = validateMd5.right().value();
4174 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4175 return Either.right(responseFormat);
4178 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4179 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4180 if (deploymentValidationResult.isRight()) {
4181 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4182 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4183 return Either.right(responseFormat);
4186 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4187 if (payloadEither.isRight()) {
4188 ResponseFormat responseFormat = payloadEither.right().value();
4189 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4190 return Either.right(responseFormat);
4194 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4195 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4196 return Either.right(responseFormat);
4202 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4203 if (lockComponent.isRight()) {
4204 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4205 .value(), componentType, null);
4206 return Either.right(lockComponent.right().value());
4209 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4211 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4217 if (resultOp == null || resultOp.isRight()) {
4218 log.debug(ROLLBACK);
4219 if (!inTransaction) {
4220 titanDao.rollback();
4225 if (!inTransaction) {
4230 componentType = parent.getComponentType();
4232 NodeTypeEnum nodeType = componentType.getNodeType();
4233 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4237 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4238 ComponentTypeEnum componentType, String origMd5) {
4240 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4241 Either<ArtifactDefinition, Operation> insideEither = null;
4242 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4243 if (getRI.isRight()) {
4244 return Either.right(getRI.right().value());
4246 ComponentInstance ri = getRI.left().value();
4247 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4248 if (getArtifactRes.isRight()) {
4249 return Either.right(getArtifactRes.right().value());
4251 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4253 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4254 .equals(ArtifactTypeEnum.HEAT_VOL
4255 .getType()) || currArtifact
4257 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4258 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4259 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4261 return Either.right(responseFormat);
4263 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4264 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4265 new ArrayList<HeatParameterDefinition>();
4268 if (origMd5 != null) {
4269 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4270 .getName(), currentHeatEnvParams,
4271 updatedHeatEnvParams, currArtifact.getArtifactName());
4272 if (uploadParamsValidationResult.isRight()) {
4273 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4274 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4276 return Either.right(responseFormat);
4278 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4281 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4283 if (validateAndConvertHeatParamers.isRight()) {
4284 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4285 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4287 return Either.right(responseFormat);
4290 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4291 // fill reduced heat env parameters List for updating
4292 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4293 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4294 currArtifact.setListHeatParameters(currentHeatEnvParams);
4296 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4297 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4298 if (updateArifactRes.isRight()) {
4299 log.debug("Failed to update artifact on graph - {}", artifactId);
4300 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4303 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4305 return Either.right(responseFormat);
4307 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4308 if (error != StorageOperationStatus.OK) {
4309 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4310 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4312 return Either.right(responseFormat);
4315 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4317 .getUniqueId(), parent.getUniqueId());
4318 if (error != StorageOperationStatus.OK) {
4319 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4320 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4322 return Either.right(responseFormat);
4326 insideEither = Either.left(currArtifact);
4327 resultOp = Either.left(insideEither);
4328 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4329 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4334 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4335 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4336 String paramName = heatEnvParam.getName();
4337 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4338 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4339 String updatedParamValue = heatEnvParam.getCurrentValue();
4340 currHeatParam.setCurrentValue(updatedParamValue);
4346 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4347 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4349 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4350 Either<ArtifactDefinition, Operation> insideEither = null;
4351 String currentHeatId = currHeatArtifact.getUniqueId();
4353 String esArtifactId = currHeatArtifact.getEsId();
4354 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4355 if (artifactFromES.isRight()) {
4356 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4357 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4358 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4359 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4360 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4363 ESArtifactData esArtifactData = artifactFromES.left().value();
4365 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4367 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4368 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4369 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4371 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4375 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4377 paramName = heatEnvParam.getName();
4378 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4379 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4381 String updatedParamValue = heatEnvParam.getCurrentValue();
4382 if (updatedParamValue == null) {
4383 updatedParamValue = heatEnvParam.getDefaultValue();
4385 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4386 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4387 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4388 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4389 .getType(), paramType.getType(), paramName);
4390 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4391 return Either.right(responseFormat);
4394 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4395 newHeatEnvParams.add(currHeatParam);
4400 if (!newHeatEnvParams.isEmpty()) {
4401 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4402 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4403 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4405 if (operationStatus.isRight()) {
4406 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4408 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4411 return Either.right(responseFormat);
4414 updatedHeatArt = operationStatus.left().value();
4416 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4417 esArtifactData.setId(updatedHeatArt.getEsId());
4419 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4422 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4423 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4424 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4425 .getUniqueId(), responseFormat, componentType, null);
4428 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4429 log.debug(FAILED_SAVE_ARTIFACT);
4430 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4431 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4432 .getUniqueId(), responseFormat, componentType, null);
4433 resultOp = Either.right(responseFormat);
4436 insideEither = Either.left(updatedHeatArt);
4439 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4440 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4441 artifactEnvInfo.setArtifactChecksum(null);
4442 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4443 .getUniqueId(), componentType.getNodeType(), componentId);
4446 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4450 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4451 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4453 .value(), parent, componentType);
4454 if (result != ActionStatus.OK) {
4455 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4456 return Either.right(responseFormat);
4460 if (updatedHeatEnvParams.isEmpty()) {
4461 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4463 resultOp = Either.left(insideEither);
4464 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4465 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4470 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4471 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4472 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4473 return Either.right(responseFormat);
4477 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4478 StorageOperationStatus error = StorageOperationStatus.OK;
4479 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4480 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4481 List<String> groupInstancesId = null;
4482 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4483 groupInstancesId = groupsInstances.stream()
4484 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4485 .contains(artifactId))
4486 .map(GroupInstanceDataDefinition::getUniqueId)
4487 .collect(Collectors.toList());
4489 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4490 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4496 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4497 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4499 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4500 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4501 .getArtifactName(), currArtifactName);
4502 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4503 return Either.right(responseFormat);
4506 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4507 String paramName = uploadedHeatParam.getName();
4508 boolean isExistsInHeat = false;
4509 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4510 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4512 isExistsInHeat = true;
4513 uploadedHeatParam.setType(currHeatParam.getType());
4514 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4515 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4516 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4520 if (!isExistsInHeat) {
4521 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4522 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4523 return Either.right(responseFormat);
4526 return Either.left(updatedHeatEnvParams);
4529 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4530 ResponseFormat responseFormat = null;
4531 List<ComponentInstance> ris = component.getComponentInstances();
4532 for (ComponentInstance ri : ris) {
4533 if (riID.equals(ri.getUniqueId())) {
4534 return Either.left(ri);
4537 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4538 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4539 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4540 return Either.right(responseFormat);
4543 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4544 ResponseFormat responseFormat = null;
4545 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4546 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4547 if (artifactId.equals(artifact.getUniqueId())) {
4548 return Either.left(artifact);
4551 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4552 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4554 return Either.right(responseFormat);
4557 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4558 ArtifactDefinition ret;
4559 if (eitherArtifact.isLeft()) {
4560 ret = eitherArtifact.left().value();
4563 ret = eitherArtifact.right().value().getImplementationArtifact();
4569 * downloads artifact of component by UUIDs
4571 * @param componentType
4572 * @param componentUuid
4573 * @param artifactUUID
4574 * @param resourceCommonInfo
4577 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4578 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4579 Either<byte[], ResponseFormat> result;
4580 byte[] downloadedArtifact = null;
4581 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4582 if (errorWrapper.isEmpty() && component != null) {
4583 resourceCommonInfo.setResourceName(component.getName());
4584 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4586 if (errorWrapper.isEmpty()) {
4587 result = Either.left(downloadedArtifact);
4590 result = Either.right(errorWrapper.getInnerElement());
4596 * downloads an artifact of resource instance of component by UUIDs
4598 * @param componentType
4599 * @param componentUuid
4600 * @param resourceInstanceName
4601 * @param artifactUUID
4604 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4605 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4606 Either<byte[], ResponseFormat> result;
4607 byte[] downloadedArtifact = null;
4608 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4609 if (errorWrapper.isEmpty()) {
4610 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4613 if (errorWrapper.isEmpty()) {
4614 result = Either.left(downloadedArtifact);
4617 result = Either.right(errorWrapper.getInnerElement());
4623 * uploads an artifact to a component by UUID
4627 * @param componentType
4628 * @param componentUuid
4629 * @param resourceCommonInfo
4633 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4634 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4635 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4636 Component component = null;
4637 String componentId = null;
4638 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4639 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4640 String userId = request.getHeader(Constants.USER_ID_HEADER);
4642 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4643 if (getComponentRes.isRight()) {
4644 StorageOperationStatus status = getComponentRes.right().value();
4645 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4646 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4648 if (errorWrapper.isEmpty()) {
4649 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4650 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4652 if (!getComponentRes.left()
4654 .getMetadataDataDefinition()
4656 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4657 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4658 if (component != null) {
4659 componentId = component.getUniqueId();
4660 componentName = component.getName();
4663 resourceCommonInfo.setResourceName(componentName);
4665 if (errorWrapper.isEmpty()) {
4666 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4667 if (actionResult.isRight()) {
4668 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4671 return Either.right(actionResult.right().value());
4673 return Either.left(actionResult.left().value().left().value());
4675 return Either.right(errorWrapper.getInnerElement());
4678 * upload an artifact to a resource instance by UUID
4682 * @param componentType
4683 * @param componentUuid
4684 * @param resourceInstanceName
4688 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4689 ArtifactOperationInfo operation) {
4690 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4691 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4692 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4693 ArtifactDefinition uploadArtifact = null;
4694 Component component = null;
4695 String componentInstanceId;
4697 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4698 String userId = request.getHeader(Constants.USER_ID_HEADER);
4700 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4701 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4702 if (getComponentRes.isRight()) {
4703 StorageOperationStatus status = getComponentRes.right().value();
4704 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4705 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4707 if (errorWrapper.isEmpty() && !getComponentRes.left()
4709 .getMetadataDataDefinition()
4711 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4712 component = checkoutParentComponent(componentType, getComponentRes.left()
4714 .getMetadataDataDefinition()
4715 .getUniqueId(), userId, errorWrapper);
4717 if (errorWrapper.isEmpty()) {
4718 if (component == null) {
4719 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4722 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4725 if (errorWrapper.isEmpty()) {
4726 componentInstanceId = componentRiPair.getRight().getUniqueId();
4727 componentId = componentRiPair.getLeft().getUniqueId();
4728 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4730 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4731 .findParamByType(componentType));
4732 if (actionResult.isRight()) {
4733 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4736 errorWrapper.setInnerElement(actionResult.right().value());
4739 if (errorWrapper.isEmpty()) {
4740 uploadArtifact = actionResult.left().value().left().value();
4741 uploadArtifactResult = Either.left(uploadArtifact);
4744 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4746 return uploadArtifactResult;
4750 * updates an artifact on a component by UUID
4754 * @param componentType
4755 * @param componentUuid
4756 * @param artifactUUID
4760 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4761 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4762 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4763 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4764 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4765 ArtifactDefinition updateArtifact = null;
4766 Component component = null;
4767 String componentId = null;
4768 String artifactId = null;
4769 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4770 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4771 String userId = request.getHeader(Constants.USER_ID_HEADER);
4773 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4774 if (getComponentRes.isRight()) {
4775 StorageOperationStatus status = getComponentRes.right().value();
4776 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4777 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4779 if (errorWrapper.isEmpty()) {
4780 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4781 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4783 if (!getComponentRes.left()
4785 .getMetadataDataDefinition()
4787 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4788 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4789 if (component != null) {
4790 componentId = component.getUniqueId();
4791 componentName = component.getName();
4794 resourceCommonInfo.setResourceName(componentName);
4796 if (errorWrapper.isEmpty()) {
4797 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4799 if (errorWrapper.isEmpty()) {
4800 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4801 if (actionResult.isRight()) {
4802 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4805 errorWrapper.setInnerElement(actionResult.right().value());
4808 if (errorWrapper.isEmpty()) {
4809 updateArtifact = actionResult.left().value().left().value();
4810 updateArtifactResult = Either.left(updateArtifact);
4814 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4816 return updateArtifactResult;
4820 * updates an artifact on a resource instance by UUID
4824 * @param componentType
4825 * @param componentUuid
4826 * @param resourceInstanceName
4827 * @param artifactUUID
4828 * @param operation TODO
4831 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4832 ArtifactOperationInfo operation) {
4834 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4835 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4836 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4837 ArtifactDefinition updateArtifact = null;
4838 Component component = null;
4839 String componentInstanceId = null;
4840 String componentId = null;
4841 String artifactId = null;
4842 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4843 String userId = request.getHeader(Constants.USER_ID_HEADER);
4845 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4846 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4847 if (getComponentRes.isRight()) {
4848 StorageOperationStatus status = getComponentRes.right().value();
4849 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4850 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4852 if (errorWrapper.isEmpty() && !getComponentRes.left()
4854 .getMetadataDataDefinition()
4856 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4857 component = checkoutParentComponent(componentType, getComponentRes.left()
4859 .getMetadataDataDefinition()
4860 .getUniqueId(), userId, errorWrapper);
4862 if (errorWrapper.isEmpty()) {
4863 if (component == null) {
4864 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4867 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4870 if (errorWrapper.isEmpty()) {
4871 componentInstanceId = componentRiPair.getRight().getUniqueId();
4872 componentId = componentRiPair.getLeft().getUniqueId();
4873 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4875 if (errorWrapper.isEmpty()) {
4876 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4878 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4879 .findParamByType(componentType));
4880 if (actionResult.isRight()) {
4881 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4884 errorWrapper.setInnerElement(actionResult.right().value());
4887 if (errorWrapper.isEmpty()) {
4888 updateArtifact = actionResult.left().value().left().value();
4889 updateArtifactResult = Either.left(updateArtifact);
4892 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4894 return updateArtifactResult;
4897 private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4898 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4899 if (componentStorageOperationStatusEither.isRight()) {
4900 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4901 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4902 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4904 Component storedComponent = componentStorageOperationStatusEither.left().value();
4906 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4907 if(!optionalInterface.isPresent()) {
4908 log.debug("Failed to get resource interface for resource Id {}", componentId);
4909 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4912 //fetch the operation from storage
4913 InterfaceDefinition gotInterface = optionalInterface.get();
4914 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4915 Optional<Operation> optionalOperation = operationsMap.values()
4917 .filter(o -> o.getUniqueId().equals(operationUuid))
4919 if (!optionalOperation.isPresent()) {
4920 log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4921 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4922 return Either.right(responseFormat);
4925 Operation operation = optionalOperation.get();
4926 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
4927 implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
4928 implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
4929 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
4930 implementationArtifact.setDescription(artifactInfo.getDescription());
4931 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
4932 implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
4933 implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
4934 implementationArtifact.setEsId(artifactInfo.getEsId());
4935 operation.setImplementation(implementationArtifact);
4936 gotInterface.setOperationsMap(operationsMap);
4937 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
4938 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
4939 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
4940 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
4941 ActionStatus actionStatus =
4942 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
4943 return Either.right(componentsUtils.getResponseFormat(actionStatus));
4946 return Either.left(artifactInfo);
4950 * updates an artifact on a component by UUID
4954 * @param componentType
4955 * @param componentUuid
4956 * @param artifactUUID
4960 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4961 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4962 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
4963 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4964 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4965 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4966 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4967 ArtifactDefinition updateArtifact = null;
4968 String componentId = null;
4969 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4970 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4971 String userId = request.getHeader(Constants.USER_ID_HEADER);
4972 ArtifactDefinition existingArtifactInfo = null;
4973 String interfaceName = null;
4975 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4976 if (getComponentRes.isRight()) {
4977 StorageOperationStatus status = getComponentRes.right().value();
4978 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4979 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4982 if (errorWrapper.isEmpty()) {
4983 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4984 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4985 if (!getComponentRes.left()
4987 .getMetadataDataDefinition()
4989 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4990 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4991 if (component != null) {
4992 componentId = component.getUniqueId();
4993 componentName = component.getName();
4997 resourceCommonInfo.setResourceName(componentName);
5000 if(errorWrapper.isEmpty()){
5001 Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
5002 if (interfaceNameEither.isRight()) {
5003 errorWrapper.setInnerElement(interfaceNameEither.right().value());
5006 interfaceName = interfaceNameEither.left().value();
5009 if(errorWrapper.isEmpty()){
5010 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
5011 if (toscaComponentEither.isRight()) {
5012 StorageOperationStatus status = toscaComponentEither.right().value();
5013 log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
5014 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5017 if (errorWrapper.isEmpty()) {
5018 NodeTypeEnum parentType = convertParentType(componentType);
5019 List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
5020 for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
5021 if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
5022 existingArtifactInfo = artifactDefinition;
5026 if(existingArtifactInfo != null){
5027 return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
5033 if (errorWrapper.isEmpty()) {
5034 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5035 artifactUUID, artifactInfo, origMd5, data, interfaceName,
5036 operationUUID, null, null);
5037 if (actionResult.isRight()) {
5038 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5041 errorWrapper.setInnerElement(actionResult.right().value());
5045 if (errorWrapper.isEmpty()) {
5046 updateArtifact = actionResult.left().value().left().value();
5047 updateArtifactResult = Either.left(updateArtifact);
5051 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5053 return updateArtifactResult;
5056 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5057 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5058 if (componentStorageOperationStatusEither.isRight()) {
5059 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5060 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5061 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5063 Component storedComponent = componentStorageOperationStatusEither.left().value();
5065 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5066 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5067 if(!optionalInterface.isPresent()) {
5068 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5070 return Either.left(optionalInterface.get().getType());
5075 * deletes an artifact on a component by UUID
5078 * @param componentType
5079 * @param componentUuid
5080 * @param artifactUUID
5081 * @param resourceCommonInfo
5082 * @param operation TODO
5085 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5086 ArtifactOperationInfo operation) {
5088 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5089 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5090 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5091 ArtifactDefinition deleteArtifact = null;
5092 Component component = null;
5093 String componentId = null;
5094 String artifactId = null;
5095 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5096 String userId = request.getHeader(Constants.USER_ID_HEADER);
5098 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5099 if (getComponentRes.isRight()) {
5100 StorageOperationStatus status = getComponentRes.right().value();
5101 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5102 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5104 if (errorWrapper.isEmpty()) {
5105 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5106 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5107 if (!getComponentRes.left()
5109 .getMetadataDataDefinition()
5111 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5112 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5113 if (component != null) {
5114 componentId = component.getUniqueId();
5115 componentName = component.getName();
5118 resourceCommonInfo.setResourceName(componentName);
5120 if (errorWrapper.isEmpty()) {
5121 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5123 if (errorWrapper.isEmpty()) {
5124 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5125 if (actionResult.isRight()) {
5126 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5129 errorWrapper.setInnerElement(actionResult.right().value());
5132 if (errorWrapper.isEmpty()) {
5133 deleteArtifact = actionResult.left().value().left().value();
5134 deleteArtifactResult = Either.left(deleteArtifact);
5137 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5139 return deleteArtifactResult;
5143 * deletes an artifact from a resource instance by UUID
5146 * @param componentType
5147 * @param componentUuid
5148 * @param resourceInstanceName
5149 * @param artifactUUID
5150 * @param operation TODO
5153 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5154 ArtifactOperationInfo operation) {
5156 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5157 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5158 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5159 ArtifactDefinition deleteArtifact = null;
5160 Component component = null;
5161 String componentInstanceId = null;
5162 String componentId = null;
5163 String artifactId = null;
5164 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5165 String userId = request.getHeader(Constants.USER_ID_HEADER);
5166 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5167 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5168 if (getComponentRes.isRight()) {
5169 StorageOperationStatus status = getComponentRes.right().value();
5170 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5171 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5173 if (errorWrapper.isEmpty() && !getComponentRes.left()
5175 .getMetadataDataDefinition()
5177 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5178 component = checkoutParentComponent(componentType, getComponentRes.left()
5180 .getMetadataDataDefinition()
5181 .getUniqueId(), userId, errorWrapper);
5183 if (errorWrapper.isEmpty()) {
5184 if (component == null) {
5185 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5188 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5191 if (errorWrapper.isEmpty()) {
5192 componentInstanceId = componentRiPair.getRight().getUniqueId();
5193 componentId = componentRiPair.getLeft().getUniqueId();
5194 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5196 if (errorWrapper.isEmpty()) {
5198 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5199 .findParamByType(componentType));
5201 if (actionResult.isRight()) {
5202 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5205 errorWrapper.setInnerElement(actionResult.right().value());
5208 if (errorWrapper.isEmpty()) {
5209 deleteArtifact = actionResult.left().value().left().value();
5210 deleteArtifactResult = Either.left(deleteArtifact);
5213 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5215 return deleteArtifactResult;
5218 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5219 String artifactId = null;
5220 ArtifactDefinition foundArtifact = null;
5221 if (instance.getDeploymentArtifacts() != null) {
5222 foundArtifact = instance.getDeploymentArtifacts()
5225 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5226 .equals(artifactUUID))
5230 if (foundArtifact == null && instance.getArtifacts() != null) {
5231 foundArtifact = instance.getArtifacts()
5234 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5235 .equals(artifactUUID))
5239 if (foundArtifact == null) {
5240 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5241 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5244 artifactId = foundArtifact.getUniqueId();
5249 @SuppressWarnings("unchecked")
5250 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5251 Map<String, String> existingEnvVersions) {
5252 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5254 .getDeploymentResourceInstanceArtifacts();
5255 if (deploymentResourceArtifacts == null) {
5256 log.debug("no deployment artifacts are configured for generated artifacts");
5257 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5259 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5260 if (placeHolderData == null) {
5261 log.debug("no env type {} are configured for generated artifacts", envType);
5262 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5265 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5266 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5267 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5268 if (createArtifactPlaceHolder.isRight()) {
5269 return Either.right(createArtifactPlaceHolder.right().value());
5271 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5272 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5273 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5274 artifactHeatEnv.setTimeout(0);
5275 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5276 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5277 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5278 ArtifactDefinition heatEnvPlaceholder;
5279 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5280 if (parentType != NodeTypeEnum.ResourceInstance) {
5281 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5282 .getUniqueId(), parentType, parentId);
5283 if (addHeatEnvArtifact.isRight()) {
5284 log.debug("failed to create heat env artifact on resource instance");
5285 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5287 .value(), false), "", null));
5289 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5292 heatEnvPlaceholder = artifactHeatEnv;
5293 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5294 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5297 ComponentTypeEnum componentType = component.getComponentType();
5298 if (parentType == NodeTypeEnum.ResourceInstance) {
5299 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5301 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5302 new ResourceCommonInfo(parentName, componentType.getValue()),
5303 ResourceVersionInfo.newBuilder().build(),
5304 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5305 null, heatEnvPlaceholder, null);
5306 return Either.left(heatEnvPlaceholder);
5309 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5310 if (artifact.getListHeatParameters() == null) {
5313 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5314 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5315 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5316 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5317 heatEnvParameter.setCurrentValue(null);
5318 heatEnvParameters.add(heatEnvParameter);
5320 artifactDefinition.setListHeatParameters(heatEnvParameters);
5323 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5324 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5325 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5326 String name = heatArtifact.getArtifactName();
5329 name = heatArtifact.getArtifactLabel();
5330 fileName = name + "." + envExtension;
5333 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5335 heatEnvArtifact.setArtifactName(fileName);
5338 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5339 if (null != existingEnvVersions) {
5340 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5341 if (null != prevVersion) {
5342 heatEnvArtifact.setArtifactVersion(prevVersion);
5348 * Handles Artifacts Request For Inner Component
5350 * @param artifactsToHandle
5353 * @param vfcsNewCreatedArtifacts
5356 * @param inTransaction
5359 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5360 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5362 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5363 ComponentTypeEnum componentType = component.getComponentType();
5364 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5365 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5366 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5370 for (ArtifactDefinition artifact : artifactsToHandle) {
5371 originData = buildJsonStringForCsarVfcArtifact(artifact);
5372 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5373 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5374 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5375 if (actionResult.isRight()) {
5376 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5377 .getName(), actionResult.right().value());
5378 errorWrapper.setInnerElement(actionResult.right().value());
5379 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5380 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5384 uploadedArtifacts.add(actionResult.left().value().left().value());
5386 if (errorWrapper.isEmpty()) {
5387 handleArtifactsResult = Either.left(uploadedArtifacts);
5390 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5393 catch (Exception e) {
5394 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5395 handleArtifactsResult = Either.right(responseFormat);
5396 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5398 return handleArtifactsResult;
5401 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5402 ComponentInstance componentInstance = null;
5403 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5404 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5405 if (errorWrapper.isEmpty()) {
5406 componentInstance = component.getComponentInstances()
5408 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5409 .equals(normalizedName))
5412 if (componentInstance == null) {
5413 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5415 .getValue(), component.getName()));
5416 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5419 return componentInstance;
5422 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5424 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5425 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5426 ComponentInstance componentInstance = component.getComponentInstances()
5428 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5429 .equals(normalizedName))
5432 if (componentInstance == null) {
5433 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5435 .getValue(), component.getName()));
5436 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5439 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5441 return relatedComponentComponentInstancePair;
5444 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5445 ComponentInstance componentInstance;
5446 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5447 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5448 if (errorWrapper.isEmpty()) {
5449 componentInstance = component.getComponentInstances()
5451 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5454 if (componentInstance == null) {
5455 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5457 .getValue(), component.getName()));
5458 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5461 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5464 return relatedComponentComponentInstancePair;
5467 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5469 byte[] downloadedArtifact = null;
5470 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5471 List<ArtifactDefinition> artifactsList = null;
5472 ArtifactDefinition deploymentArtifact = null;
5473 if (artifacts != null && !artifacts.isEmpty()) {
5474 artifactsList = artifacts.values()
5476 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5477 .equals(artifactUUID))
5478 .collect(Collectors.toList());
5480 if (artifactsList == null || artifactsList.isEmpty()) {
5481 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5482 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5484 if (errorWrapper.isEmpty()) {
5485 deploymentArtifact = artifactsList.get(0);
5486 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5487 if (downloadArtifactEither.isRight()) {
5488 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5489 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5492 if (errorWrapper.isEmpty()) {
5493 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5494 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5496 return downloadedArtifact;
5499 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5500 Component component = null;
5501 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5502 if (getComponentRes.isRight()) {
5503 StorageOperationStatus status = getComponentRes.right().value();
5504 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5505 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5508 component = getComponentRes.left().value();
5513 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5514 Component component = null;
5515 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5516 if (getComponentRes.isRight()) {
5517 StorageOperationStatus status = getComponentRes.right().value();
5518 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5519 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5522 List<Component> value = getComponentRes.left().value();
5523 if (value.isEmpty()) {
5524 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5525 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5526 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5529 component = value.get(0);
5535 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5536 String artifactId = null;
5537 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5538 StorageOperationStatus storageStatus;
5539 ArtifactDefinition latestArtifact = null;
5540 List<ArtifactDefinition> artifacts = null;
5541 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5542 if (getArtifactsRes.isRight()) {
5543 storageStatus = getArtifactsRes.right().value();
5544 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5545 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5546 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5548 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5550 if (errorWrapper.isEmpty()) {
5551 artifacts = getArtifactsRes.left()
5555 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5556 .equals(artifactUUID))
5557 .collect(Collectors.toList());
5558 if (artifacts == null || artifacts.isEmpty()) {
5559 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5560 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5563 if (errorWrapper.isEmpty()) {
5564 latestArtifact = artifacts.stream().max((a1, a2) -> {
5565 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5566 if (compareRes == 0) {
5567 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5568 .getLastUpdateDate());
5572 if (latestArtifact == null) {
5573 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5574 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5577 if (errorWrapper.isEmpty()) {
5578 artifactId = latestArtifact.getUniqueId();
5583 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5585 Component component = null;
5586 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5587 if (getUserRes.isRight()) {
5588 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5591 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5593 if (errorWrapper.isEmpty()) {
5594 User modifier = getUserRes.left().value();
5595 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5596 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5597 if (checkoutRes.isRight()) {
5598 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5599 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5600 errorWrapper.setInnerElement(checkoutRes.right().value());
5603 component = checkoutRes.left().value();
5609 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5610 Map<String, Object> json = new HashMap<>();
5611 String artifactName = artifact.getArtifactName();
5612 json.put(Constants.ARTIFACT_NAME, artifactName);
5613 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5614 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5615 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5616 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5617 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5618 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5619 return gson.toJson(json);
5623 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5624 this.nodeTemplateOperation = nodeTemplateOperation;