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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import com.google.gson.Gson;
26 import com.google.gson.GsonBuilder;
27 import fj.data.Either;
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.commons.collections.CollectionUtils;
30 import org.apache.commons.collections.MapUtils;
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.commons.lang3.tuple.ImmutablePair;
33 import org.elasticsearch.common.Strings;
34 import org.openecomp.sdc.be.components.ArtifactsResolver;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
36 import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector;
37 import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
38 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
40 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
41 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
43 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
46 import org.openecomp.sdc.be.config.ConfigurationManager;
47 import org.openecomp.sdc.be.dao.api.ActionStatus;
48 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
49 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
50 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
51 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.ToscaArtifactDataDefinition;
56 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
58 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
59 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
60 import org.openecomp.sdc.be.model.ArtifactDefinition;
61 import org.openecomp.sdc.be.model.ArtifactType;
62 import org.openecomp.sdc.be.model.Component;
63 import org.openecomp.sdc.be.model.ComponentInstance;
64 import org.openecomp.sdc.be.model.ComponentParametersView;
65 import org.openecomp.sdc.be.model.GroupDefinition;
66 import org.openecomp.sdc.be.model.GroupInstance;
67 import org.openecomp.sdc.be.model.HeatParameterDefinition;
68 import org.openecomp.sdc.be.model.InterfaceDefinition;
69 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
70 import org.openecomp.sdc.be.model.LifecycleStateEnum;
71 import org.openecomp.sdc.be.model.Operation;
72 import org.openecomp.sdc.be.model.Resource;
73 import org.openecomp.sdc.be.model.Service;
74 import org.openecomp.sdc.be.model.User;
75 import org.openecomp.sdc.be.model.heat.HeatParameterType;
76 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
77 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
78 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
79 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
80 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
81 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
82 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
83 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
84 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
85 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
86 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
87 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
88 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
89 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
90 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
91 import org.openecomp.sdc.be.resources.data.ESArtifactData;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
94 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
95 import org.openecomp.sdc.be.servlets.RepresentationUtils;
96 import org.openecomp.sdc.be.tosca.CsarUtils;
97 import org.openecomp.sdc.be.tosca.ToscaError;
98 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
99 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
100 import org.openecomp.sdc.be.user.IUserBusinessLogic;
101 import org.openecomp.sdc.be.user.Role;
102 import org.openecomp.sdc.be.user.UserBusinessLogic;
103 import org.openecomp.sdc.be.utils.TypeUtils;
104 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
105 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
106 import org.openecomp.sdc.common.api.Constants;
107 import org.openecomp.sdc.common.datastructure.Wrapper;
108 import org.openecomp.sdc.common.log.wrappers.Logger;
109 import org.openecomp.sdc.common.util.GeneralUtility;
110 import org.openecomp.sdc.common.util.ValidationUtils;
111 import org.openecomp.sdc.common.util.YamlToObjectConverter;
112 import org.openecomp.sdc.exception.ResponseFormat;
113 import org.springframework.beans.factory.annotation.Autowired;
114 import org.xml.sax.InputSource;
115 import org.xml.sax.SAXException;
116 import org.xml.sax.SAXNotRecognizedException;
117 import org.xml.sax.SAXNotSupportedException;
118 import org.xml.sax.XMLReader;
119 import org.yaml.snakeyaml.Yaml;
121 import javax.servlet.http.HttpServletRequest;
122 import javax.xml.XMLConstants;
123 import javax.xml.parsers.ParserConfigurationException;
124 import javax.xml.parsers.SAXParserFactory;
125 import java.io.ByteArrayInputStream;
126 import java.io.IOException;
127 import java.math.BigDecimal;
128 import java.util.ArrayList;
129 import java.util.Collections;
130 import java.util.Comparator;
131 import java.util.HashMap;
132 import java.util.Iterator;
133 import java.util.List;
134 import java.util.Map;
135 import java.util.Map.Entry;
136 import java.util.Objects;
137 import java.util.Optional;
138 import java.util.Set;
139 import java.util.function.Predicate;
140 import java.util.function.Supplier;
141 import java.util.stream.Collectors;
143 @org.springframework.stereotype.Component("artifactBusinessLogic")
144 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
145 private static final String RESOURCE_INSTANCE = "resource instance";
146 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
147 private static final String ARTIFACT_DESCRIPTION = "artifact description";
148 private static final String ARTIFACT_LABEL = "artifact label";
149 private static final String ARTIFACT_URL = "artifact url";
150 private static final String ARTIFACT_NAME = "artifact name";
151 private static final String ARTIFACT_PAYLOAD = "artifact payload";
153 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
154 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
155 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
157 public static final String HEAT_ENV_NAME = "heatEnv";
158 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
159 public static final String HEAT_ENV_SUFFIX = "env";
160 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
162 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
163 private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
164 private static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
165 private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
166 private static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
167 private static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
168 private static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
169 private static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
170 private static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
171 private static final String NULL_PARAMETER = "One of the function parameteres is null";
172 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
173 private static final String ROLLBACK = "all changes rollback";
174 private static final String COMMIT = "all changes committed";
175 private static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
176 private static final String UPDATE_ARTIFACT = "Update Artifact";
177 private static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
178 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
180 @javax.annotation.Resource
181 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
182 @javax.annotation.Resource
183 private IUserAdminOperation userOperaton;
185 @javax.annotation.Resource
186 private IElementOperation elementOperation;
188 @javax.annotation.Resource
189 private UserBusinessLogic userAdminManager;
191 @javax.annotation.Resource
192 private IHeatParametersOperation heatParametersOperation;
194 private final ArtifactCassandraDao artifactCassandraDao;
195 private final ToscaExportHandler toscaExportUtils;
196 private final CsarUtils csarUtils;
197 private final LifecycleBusinessLogic lifecycleBusinessLogic;
198 private final IUserBusinessLogic userBusinessLogic;
199 private final ArtifactsResolver artifactsResolver;
200 private NodeTemplateOperation nodeTemplateOperation;
203 public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils,
204 CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, IUserBusinessLogic userBusinessLogic,
205 ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation,
206 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
207 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
208 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
209 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
210 this.artifactCassandraDao = artifactCassandraDao;
211 this.toscaExportUtils = toscaExportUtils;
212 this.csarUtils = csarUtils;
213 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
214 this.userBusinessLogic = userBusinessLogic;
215 this.artifactsResolver = artifactsResolver;
218 public enum ArtifactOperationEnum {
219 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
221 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
222 return operation == CREATE || operation == LINK;
226 public class ArtifactOperationInfo {
228 private ArtifactOperationEnum artifactOperationEnum;
229 private boolean isExternalApi;
230 private boolean ignoreLifecycleState;
232 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
233 this.artifactOperationEnum = artifactOperationEnum;
234 this.isExternalApi = isExternalApi;
235 this.ignoreLifecycleState = ignoreLifecycleState;
238 public boolean isExternalApi() {
239 return isExternalApi;
242 public boolean ignoreLifecycleState() {
243 return ignoreLifecycleState;
246 public ArtifactOperationEnum getArtifactOperationEnum() {
247 return artifactOperationEnum;
253 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
254 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
255 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
258 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
259 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
261 // step 1 - detect auditing type
262 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
263 // step 2 - check header
264 if (userId == null) {
265 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
266 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
267 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
268 return Either.right(responseFormat);
270 // step 3 - check user existence
271 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
272 if (userResult.isRight()) {
273 return Either.right(userResult.right().value());
276 // step 4 - check user's role
277 User user = userResult.left().value();
278 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
279 if (validateUserRole.isRight()) {
280 return Either.right(validateUserRole.right().value());
284 // 5. check service/resource existence
285 // 6. check service/resource check out
286 // 7. user is owner of checkout state
287 org.openecomp.sdc.be.model.Component component = null;
288 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
289 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
290 if (validateComponent.isRight()) {
291 return Either.right(validateComponent.right().value());
293 component = validateComponent.left().value();
294 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
295 if (validateWorkOnResource.isRight()) {
296 return Either.right(validateWorkOnResource.right().value());
300 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
301 shouldLock, inTransaction, true);
305 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
306 * For regular usage use <br>
307 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
311 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
312 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
313 Component parent = component;
314 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
316 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
317 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
319 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
320 if (errorWrapper.isEmpty()) {
322 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
325 result = Either.right(errorWrapper.getInnerElement());
330 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
331 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
332 ArtifactDefinition validatedArtifactInfo = artifactInfo;
333 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
334 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
335 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
336 if (validateArtifact.isRight()) {
337 ResponseFormat responseFormat = validateArtifact.right().value();
338 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
339 errorWrapper.setInnerElement(validateArtifact.right().value());
341 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
342 validatedArtifactInfo = validateArtifact.left().value();
343 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
346 return validatedArtifactInfo;
349 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
350 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
351 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
353 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
354 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
355 ComponentInstance componentInstance = component.getComponentInstances()
357 .filter(p -> p.getUniqueId().equals(componentId))
360 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
362 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
364 .filter(p -> p.getUniqueId()
365 .equals(validatedArtifact.getUniqueId()))
368 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
369 .getName(), user, componentId, shouldLock, inTransaction);
370 if (eitherGenerated.isRight()) {
371 errorWrapper.setInnerElement(eitherGenerated.right().value());
376 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
377 boolean needGenerate;
378 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
379 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
380 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
381 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
382 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
386 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
387 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
389 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
392 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(
393 ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component,
394 User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction,
395 boolean fetchTemplatesFromDB) {
397 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
398 if (generated.isRight()) {
401 byte[] decodedPayload = artifactDefinition.getPayloadData();
402 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
403 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
404 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
405 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
406 shouldLock, inTransaction);
410 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
411 log.debug("tosca artifact generation");
412 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
413 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
415 if (generated.isRight()) {
416 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
419 return Either.right(generated.right().value());
421 byte[] value = generated.left().value();
422 artifactInfo.setPayload(value);
426 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
427 if (exportComponent.isRight()) {
428 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
430 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
431 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
432 return Either.right(responseFormat);
434 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
435 String payload = exportComponent.left().value().getMainYaml();
436 artifactInfo.setPayloadData(payload);
438 return Either.left(Either.left(artifactInfo));
441 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
442 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
443 switch (operation.getArtifactOperationEnum()) {
445 if (artifactGenerationRequired(parent, artifactInfo)) {
446 return generateNotSavedArtifact(parent, artifactInfo);
448 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
450 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
452 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
453 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
454 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
455 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
456 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
457 if (needUpdateGroup && result.isLeft()) {
458 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
459 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
460 .value(), parent, componentType, componentId);
461 if (error != ActionStatus.OK) {
462 result = Either.right(componentsUtils.getResponseFormat(error));
467 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
468 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
471 if (result == null) {
472 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
473 if (needUpdateGroup && result.isLeft()) {
474 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
476 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
477 .value(), parent, componentType);
478 if (error != ActionStatus.OK) {
479 result = Either.right(componentsUtils.getResponseFormat(error));
485 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
487 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
492 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
493 List<GroupDefinition> groups = parent.getGroups();
494 if (groups != null && !groups.isEmpty()) {
495 List<GroupDataDefinition> groupToUpdate = groups.stream()
496 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
497 .contains(artifactInfo
499 .collect(Collectors.toList());
500 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
501 groupToUpdate.forEach(g -> {
502 g.getArtifacts().remove(artifactInfo.getUniqueId());
503 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
504 g.getArtifacts().add(artAfterUpdate.getUniqueId());
505 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
507 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
508 if (status.isRight()) {
509 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
510 return componentsUtils.convertFromStorageResponse(status.right().value());
514 return ActionStatus.OK;
517 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
518 List<GroupDefinition> groups = parent.getGroups();
519 if (groups != null && !groups.isEmpty()) {
520 List<GroupDataDefinition> groupToUpdate = groups.stream()
521 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
522 .contains(artifactInfoHeat
524 .collect(Collectors.toList());
525 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
526 groupToUpdate.forEach(g -> {
527 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
528 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
529 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
530 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
531 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
532 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
534 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
535 if (status.isRight()) {
536 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
537 return componentsUtils.convertFromStorageResponse(status.right().value());
541 return ActionStatus.OK;
544 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
545 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
546 List<GroupInstance> groupInstances = null;
547 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
549 .filter(ci -> ci.getUniqueId().equals(parentId))
551 if (componentInstOp.isPresent()) {
552 groupInstances = componentInstOp.get().getGroupInstances();
554 if (CollectionUtils.isNotEmpty(groupInstances)) {
555 boolean isUpdated = false;
556 for (GroupInstance groupInstance : groupInstances) {
558 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
559 .contains(artifactInfo
561 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
562 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
565 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
566 .contains(artifactInfo
567 .getArtifactUUID())) {
568 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
569 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
573 updatedGroupInstances.add(groupInstance);
577 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
578 if (status.isRight()) {
579 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
580 return componentsUtils.convertFromStorageResponse(status.right().value());
582 return ActionStatus.OK;
585 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
586 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
587 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
588 result = generateToscaArtifact(parent, artifactInfo, false, false);
591 String heatArtifactId = artifactInfo.getGeneratedFromId();
592 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
593 if (heatRes.isRight()) {
594 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
596 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
599 return Either.right(responseFormat);
601 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
602 artifactInfo.setPayloadData(generatedPayload);
603 result = Either.left(Either.left(artifactInfo));
608 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
609 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
610 convertParentType(componentType);
611 String parentId = parent.getUniqueId();
612 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
613 .getGeneratedFromId());
614 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
616 if (origMd5 != null) {
617 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
618 if (validateMd5.isRight()) {
619 ResponseFormat responseFormat = validateMd5.right().value();
620 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
621 return Either.right(responseFormat);
624 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
626 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
627 if (payloadEither.isRight()) {
628 ResponseFormat responseFormat = payloadEither.right().value();
629 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
630 return Either.right(responseFormat);
634 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
635 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
636 return Either.right(responseFormat);
642 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
643 if (lockComponent.isRight()) {
644 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
645 .value(), componentType, null);
646 return Either.right(lockComponent.right().value());
649 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
651 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
657 if (resultOp == null || resultOp.isRight()) {
659 if (!inTransaction) {
660 janusGraphDao.rollback();
665 if (!inTransaction) {
666 janusGraphDao.commit();
670 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
675 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
676 if (artifactGenerationRequired(component, csarArtifact)) {
677 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
679 if (generated.isRight()) {
680 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
683 return Either.right(generated.right().value());
685 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
688 return downloadArtifact(csarArtifact);
691 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
692 // perform all validation in common flow
693 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
694 null, parentId, containerComponentType);
695 if (result.isRight()) {
696 return Either.right(result.right().value());
698 ArtifactDefinition artifactDefinition;
699 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
700 if (insideValue.isLeft()) {
701 artifactDefinition = insideValue.left().value();
704 artifactDefinition = insideValue.right().value().getImplementationArtifact();
706 // for tosca artifacts and heat env on VF level generated on download without saving
707 if (artifactDefinition.getPayloadData() != null) {
708 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
711 return downloadArtifact(artifactDefinition);
714 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
716 // detect auditing type
717 Map<String, ArtifactDefinition> resMap = null;
718 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
723 if (userId == null) {
724 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
725 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
727 resultOp = Either.right(responseFormat);
731 // check user existence
735 validateUserExists(userId, "get artifacts", false);
737 // 5. check service/resource existence
738 // 6. check service/resource check out
739 // 7. user is owner of checkout state
740 org.openecomp.sdc.be.model.Component component = null;
741 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
742 ComponentParametersView componentFilter = new ComponentParametersView();
743 componentFilter.disableAll();
744 componentFilter.setIgnoreArtifacts(false);
745 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
746 componentFilter.setIgnoreComponentInstances(false);
749 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
750 .findByParamName(containerComponentType), componentFilter);
752 if (validateComponent.isRight()) {
753 resultOp = Either.right(validateComponent.right().value());
756 component = validateComponent.left().value();
757 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
758 if (lockComponent.isRight()) {
760 resultOp = Either.right(lockComponent.right().value());
765 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
767 if (groupType == null) {
768 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
769 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
771 resultOp = Either.right(responseFormat);
775 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
776 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
777 if (list != null && !list.isEmpty()) {
778 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
781 resMap = new HashMap<>();
783 resultOp = Either.left(resMap);
788 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
789 .getNodeType(), groupType, componentId);
790 if (artifactsMapStatus.isRight()) {
791 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
792 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
793 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
794 resultOp = Either.right(responseFormat);
797 resMap = new HashMap<>();
798 resultOp = Either.left(resMap);
802 resMap = artifactsMapStatus.left().value();
803 resultOp = Either.left(resMap);
810 if (resultOp == null || resultOp.isRight()) {
812 janusGraphDao.rollback();
816 janusGraphDao.commit();
819 componentType = component.getComponentType();
820 NodeTypeEnum nodeType = componentType.getNodeType();
821 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
826 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
828 // check artifact existence
829 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
831 if (artifactResult.isRight()) {
832 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
833 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
834 log.debug("addArtifact - artifact {} not found", artifactId);
835 return Either.right(responseFormat);
839 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
842 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
844 return Either.right(responseFormat);
848 // check artifact belong to component
849 boolean found = false;
850 switch (componentType) {
853 found = checkArtifactInComponent(component, artifactId);
855 case RESOURCE_INSTANCE:
856 found = checkArtifactInResourceInstance(component, componentId, artifactId);
862 String componentName = componentType.name().toLowerCase();
863 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
864 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
865 return Either.right(responseFormat);
867 return Either.left(artifactResult.left().value());
870 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
871 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
873 String artifactId = null;
876 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
877 if (payloadEither.isRight()) {
878 return Either.right(payloadEither.right().value());
880 byte[] decodedPayload = payloadEither.left().value();
881 convertParentType(componentType);
884 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
885 if (lockComponent.isRight()) {
886 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
887 .value(), componentType, null);
888 return Either.right(lockComponent.right().value());
891 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
894 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
899 unlockComponent(resultOp, parent, inTransaction);
906 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
907 Component parent, boolean shouldLock, boolean inTransaction) {
910 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
911 if (lockComponent.isRight()) {
912 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
913 .value(), componentType, null);
914 return Either.right(lockComponent.right().value());
917 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
920 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
925 unlockComponent(resultOp, parent, inTransaction);
932 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
933 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
935 convertParentType(componentType);
939 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
941 if (lockComponent.isRight()) {
942 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
943 .value(), componentType, null);
944 return Either.right(lockComponent.right().value());
948 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
950 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
956 unlockComponent(resultOp, parent, inTransaction);
961 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
962 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
964 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
966 if (payloadEither.isRight()) {
967 return Either.right(payloadEither.right().value());
969 byte[] decodedPayload = payloadEither.left().value();
971 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
974 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
975 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
977 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
978 if (validateMd5.isRight()) {
979 ResponseFormat responseFormat = validateMd5.right().value();
980 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
981 return Either.right(responseFormat);
985 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
986 if (validateResult.isRight()) {
987 ResponseFormat responseFormat = validateResult.right().value();
988 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
989 return Either.right(validateResult.right().value());
992 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
993 if (payloadEither.isRight()) {
994 ResponseFormat responseFormat = payloadEither.right().value();
995 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
996 log.debug("Error during handle payload");
997 return Either.right(responseFormat);
1000 // validate heat parameters. this part must be after the parameters are
1001 // extracted in "handlePayload"
1002 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
1003 .getArtifactType());
1004 if (validateAndConvertHeatParamers.isRight()) {
1005 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
1006 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
1007 log.debug("Error during handle payload");
1008 return Either.right(responseFormat);
1010 return payloadEither;
1013 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1014 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1016 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
1022 user.setUserId("UNKNOWN");
1024 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
1027 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1028 switch (componentTypeEnum) {
1030 Resource resource = (Resource) component;
1031 if (resource == null) {
1032 // In that case, component ID should be instead of name
1033 resource = new Resource();
1034 resource.setName(componentId);
1036 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1037 ResourceVersionInfo.newBuilder()
1038 .artifactUuid(prevArtifactUuid)
1039 .build(), currentArtifactUuid, artifactDefinition);
1043 Service service = (Service) component;
1044 if (service == null) {
1045 // In that case, component ID should be instead of name
1046 service = new Service();
1047 service.setName(componentId);
1049 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1050 ResourceVersionInfo.newBuilder()
1051 .artifactUuid(prevArtifactUuid)
1053 ResourceVersionInfo.newBuilder()
1054 .artifactUuid(currentArtifactUuid)
1056 null, artifactDefinition, null);
1059 case RESOURCE_INSTANCE:
1060 if (resourceInstanceName == null) {
1061 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1063 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1064 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1065 ResourceVersionInfo.newBuilder()
1066 .artifactUuid(prevArtifactUuid)
1068 ResourceVersionInfo.newBuilder()
1069 .artifactUuid(currentArtifactUuid)
1071 null, artifactDefinition, null);
1078 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1079 ComponentInstance resourceInstance = component.getComponentInstances()
1081 .filter(p -> p.getUniqueId().equals(componentId))
1084 String resourceInstanceName = null;
1085 if (resourceInstance != null) {
1086 resourceInstanceName = resourceInstance.getName();
1088 return resourceInstanceName;
1091 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1092 StringBuilder sb = new StringBuilder();
1093 if (artifactDefinition != null) {
1094 sb.append(artifactDefinition.getArtifactGroupType().getType())
1097 .append(artifactDefinition.getArtifactLabel())
1100 .append(artifactDefinition.getArtifactType())
1102 .append(artifactDefinition.getArtifactName())
1104 .append(artifactDefinition.getTimeout())
1106 .append(artifactDefinition.getEsId());
1109 if (artifactDefinition.getArtifactVersion() != null) {
1111 sb.append(artifactDefinition.getArtifactVersion());
1117 if (artifactDefinition.getArtifactUUID() != null) {
1118 sb.append(artifactDefinition.getArtifactUUID());
1124 return sb.toString();
1127 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1129 if (origMd5 != null) {
1130 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1131 if (!encodeBase64Str.equals(origMd5)) {
1132 log.debug("The calculated md5 is different then the received one");
1133 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1137 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1138 log.debug("Missing md5 header during artifact create");
1139 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1142 if (payload != null && payload.length != 0) {
1143 log.debug("Cannot have payload while md5 header is missing");
1144 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1147 return Either.left(true);
1150 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1151 ComponentTypeEnum componentType, Component parentComponent) {
1153 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1154 if (artifactById.isRight()) {
1155 return Either.right(artifactById.right().value());
1157 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1159 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1160 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1161 if (validateInformationalArtifactRes.isRight()) {
1162 return Either.right(validateInformationalArtifactRes.right().value());
1164 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1165 if (validateAndSetArtifactname.isRight()) {
1166 return Either.right(validateAndSetArtifactname.right().value());
1168 if (operationName != null && interfaceName != null) {
1169 operationName = operationName.toLowerCase();
1170 interfaceName = interfaceName.toLowerCase();
1172 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1173 if (logicalNameStatus.isRight()) {
1174 return Either.right(logicalNameStatus.right().value());
1176 // This is a patch to block possibility of updating service api fields
1177 // through other artifacts flow
1179 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1180 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1181 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1184 checkCreateFields(user, artifactInfo, artifactGroupType);
1187 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1188 if (currentArtifactInfo != null) {
1189 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1192 // artifactGroupType is not allowed to be updated
1193 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1194 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1195 if (validateGroupType.isRight()) {
1196 return Either.right(validateGroupType.right().value());
1199 NodeTypeEnum parentType = convertParentType(componentType);
1201 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1203 if (isDeploymentArtifact(artifactInfo)) {
1204 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1205 if (deploymentValidationResult.isRight()) {
1206 return Either.right(deploymentValidationResult.right().value());
1210 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1213 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1214 if (descriptionResult.isRight()) {
1215 return Either.right(descriptionResult.right().value());
1218 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1219 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1220 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1221 if (validateServiceApiType.isRight()) {
1222 return Either.right(validateServiceApiType.right().value());
1224 // Change of type is not allowed and should be ignored
1226 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1228 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1229 if (validateUrl.isRight()) {
1230 return Either.right(validateUrl.right().value());
1233 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1234 if (validateUpdate.isRight()) {
1235 log.debug("serviceApi first update cnnot be without payload.");
1236 return Either.right(validateUpdate.right().value());
1240 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1241 if (validateArtifactType.isRight()) {
1242 return Either.right(validateArtifactType.right().value());
1244 if (artifactInfo.getApiUrl() != null) {
1245 artifactInfo.setApiUrl(null);
1246 log.error("Artifact URL cannot be set through this API - ignoring");
1249 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1250 artifactInfo.setServiceApi(false);
1251 log.error("Artifact service API flag cannot be changed - ignoring");
1255 return Either.left(artifactInfo);
1258 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1259 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1260 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1261 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1262 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1266 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1268 Either<ArtifactDefinition, ResponseFormat> result = null;
1269 ArtifactDefinition foundArtifact = null;
1270 if (StringUtils.isNotEmpty(artifactId)) {
1271 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1273 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1274 log.debug("Artifact {} already exist", artifactId);
1275 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1277 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1278 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1279 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1281 if (result == null) {
1282 result = Either.left(foundArtifact);
1287 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1288 ArtifactDefinition foundArtifact;
1289 if (parentComponent.getUniqueId().equals(parentId)) {
1290 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1293 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1294 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1296 return foundArtifact;
1299 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1300 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1301 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1302 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1303 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1304 if (artifactType == null) {
1305 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1306 .getArtifactType()));
1308 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1309 String artifactTypeName = artifactType.getType();
1310 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1311 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1313 .getResourceInformationalArtifacts();
1314 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1315 if (!validArtifactTypes.contains(artifactTypeName)) {
1316 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1319 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1320 .getValidForResourceTypes();
1321 if (!validResourceType.contains(parentResourceType.name())) {
1322 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1326 return validationResult;
1329 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1330 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1331 return NodeTypeEnum.Resource;
1333 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1334 return NodeTypeEnum.ResourceInstance;
1337 return NodeTypeEnum.Service;
1341 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1342 boolean shouldLock, boolean inTransaction) {
1344 NodeTypeEnum parentType = convertParentType(componentType);
1345 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1346 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1347 ArtifactDefinition foundArtifact = null;
1348 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1349 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1350 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1351 boolean isDuplicated = false;
1353 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1356 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1357 if (lockComponent.isRight()) {
1358 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1359 .value(), componentType, null);
1360 resultOp = Either.right(lockComponent.right().value());
1363 if (resultOp == null) {
1364 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1365 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1366 if (getContainerRes.isRight()) {
1367 log.debug("Failed to fetch the container component {}. ", parentId);
1368 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1370 .value()), artifactId);
1371 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1372 resultOp = Either.right(responseFormat);
1375 if (resultOp == null) {
1376 fetchedContainerComponent = getContainerRes.left().value();
1377 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1378 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1379 if (getArtifactRes.isRight()) {
1380 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1382 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1383 .value(), artifactId);
1384 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1385 resultOp = Either.right(responseFormat);
1388 foundArtifact = getArtifactRes.left().value().getLeft();
1389 esId = foundArtifact.getEsId();
1392 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1393 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1394 .getComponentType()));
1395 if (needCloneRes.isRight()) {
1396 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1397 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1399 .value()), foundArtifact.getArtifactDisplayName());
1400 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1401 resultOp = Either.right(responseFormat);
1404 boolean isNeedToDeleteArtifactFromDB = true;
1405 if (resultOp == null) {
1407 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1408 String instanceId = parentId;
1409 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1411 if (isOnlyResourceInstanceArtifact.isRight()) {
1412 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1413 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1414 .value(), foundArtifact
1415 .getArtifactDisplayName());
1416 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1417 return Either.right(responseFormat);
1419 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1422 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1425 if (updatedArtifactRes.isRight()) {
1426 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1427 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1429 .value()), foundArtifact.getArtifactDisplayName());
1430 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1431 resultOp = Either.right(responseFormat);
1434 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1438 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1439 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1440 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1441 if (cassandraStatus != CassandraOperationStatus.OK) {
1442 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1443 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1444 .getArtifactDisplayName());
1445 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1446 resultOp = Either.right(responseFormat);
1449 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1451 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1455 .getGroupInstances());
1456 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1457 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1458 if (status.isRight()) {
1459 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1460 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1462 .value()), foundArtifact.getArtifactDisplayName());
1463 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1464 resultOp = Either.right(responseFormat);
1468 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1469 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1470 if (status != StorageOperationStatus.OK) {
1471 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1472 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1473 .getArtifactDisplayName());
1474 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1475 resultOp = Either.right(responseFormat);
1478 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1479 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1481 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1482 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1483 if (status.isRight()) {
1484 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1485 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1487 .value()), foundArtifact.getArtifactDisplayName());
1488 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1489 resultOp = Either.right(responseFormat);
1493 if (resultOp == null) {
1494 resultOp = Either.left(Either.left(foundArtifact));
1495 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1501 unlockComponent(resultOp, parent, inTransaction);
1506 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1507 Either<Boolean, ActionStatus> result = Either.left(true);
1508 ComponentInstance foundInstance = null;
1509 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1511 .filter(i -> i.getUniqueId().equals(instanceId))
1513 if (!componentInstanceOpt.isPresent()) {
1514 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1517 foundInstance = componentInstanceOpt.get();
1518 String componentUid = foundInstance.getComponentUid();
1519 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1520 if (getContainerRes.isRight()) {
1521 log.debug("Failed to fetch the container component {}. ", componentUid);
1522 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1524 Component origComponent = getContainerRes.left().value();
1525 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1526 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1527 Optional<String> op = deploymentArtifacts.keySet()
1529 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1531 if (op.isPresent()) {
1532 return Either.left(false);
1535 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1536 if (artifacts != null && !artifacts.isEmpty()) {
1537 Optional<String> op = artifacts.keySet()
1539 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1541 if (op.isPresent()) {
1542 return Either.left(false);
1550 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1551 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1552 boolean isUpdated = false;
1553 if (groups != null) {
1554 for (GroupDefinition group : groups) {
1556 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1557 group.getArtifacts().remove(artifactId);
1560 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1561 .contains(foundArtifact.getArtifactUUID())) {
1562 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1566 updatedGroups.add(group);
1570 return updatedGroups;
1573 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1574 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1575 if (CollectionUtils.isNotEmpty(groupInstances)) {
1576 boolean isUpdated = false;
1577 for (GroupInstance groupInstance : groupInstances) {
1579 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1580 .contains(artifactId)) {
1581 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1584 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1585 .contains(foundArtifact
1586 .getArtifactUUID())) {
1587 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1591 updatedGroupInstances.add(groupInstance);
1595 return updatedGroupInstances;
1598 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1600 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1601 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1602 String componentId = component.getUniqueId();
1603 String instanceId = componentId.equals(parentId) ? null : parentId;
1605 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1606 resetMandatoryArtifactFields(foundArtifact);
1607 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1609 else if (cloneIsNeeded) {
1610 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1611 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1614 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1615 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1620 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1622 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1623 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1624 ComponentInstance foundInstance = null;
1625 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1626 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1628 .filter(i -> i.getUniqueId()
1631 if (!componentInstanceOpt.isPresent()) {
1632 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1635 foundInstance = componentInstanceOpt.get();
1636 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1640 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1642 if (result == null) {
1643 if (artifacts.containsKey(artifactId)) {
1644 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1647 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1653 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1654 Map<String, ArtifactDefinition> currArtifacts;
1655 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1656 currArtifacts = component.getDeploymentArtifacts()
1659 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1660 if (MapUtils.isNotEmpty(currArtifacts)) {
1661 artifacts.putAll(currArtifacts);
1664 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1665 currArtifacts = component.getArtifacts()
1668 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1669 if (MapUtils.isNotEmpty(currArtifacts)) {
1670 artifacts.putAll(currArtifacts);
1673 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1674 currArtifacts = component.getToscaArtifacts()
1677 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1678 if (MapUtils.isNotEmpty(currArtifacts)) {
1679 artifacts.putAll(currArtifacts);
1684 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1685 Map<String, ArtifactDefinition> currArtifacts;
1686 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1687 currArtifacts = instance.getDeploymentArtifacts()
1690 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1691 if (MapUtils.isNotEmpty(currArtifacts)) {
1692 artifacts.putAll(currArtifacts);
1695 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1696 currArtifacts = instance.getArtifacts()
1699 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1700 if (MapUtils.isNotEmpty(currArtifacts)) {
1701 artifacts.putAll(currArtifacts);
1706 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1707 if (fetchedArtifact != null) {
1708 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1709 fetchedArtifact.setEsId(null);
1710 fetchedArtifact.setArtifactName(null);
1711 fetchedArtifact.setDescription(null);
1712 fetchedArtifact.setApiUrl(null);
1713 fetchedArtifact.setArtifactChecksum(null);
1714 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1715 fetchedArtifact.setArtifactUUID(null);
1716 long time = System.currentTimeMillis();
1717 fetchedArtifact.setPayloadUpdateDate(time);
1718 fetchedArtifact.setHeatParameters(null);
1719 fetchedArtifact.setHeatParamsUpdateDate(null);
1723 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1724 StorageOperationStatus error = StorageOperationStatus.OK;
1725 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1726 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1727 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1732 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1734 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1736 if (artifactById.isRight()) {
1737 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1738 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1739 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1740 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1741 return Either.right(responseFormat);
1743 ArtifactDefinition artifactDefinition = artifactById.left().value();
1744 if (artifactDefinition == null) {
1745 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1746 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1747 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1748 return Either.right(responseFormat);
1751 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1752 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1753 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1754 return Either.left(insideEither);
1757 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1758 ComponentTypeEnum componentType) {
1760 String artifactLabel = artifactInfo.getArtifactLabel();
1761 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1763 BeEcompErrorManager.getInstance()
1764 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1765 log.debug("missing artifact logical name for component {}", componentId);
1766 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1768 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1770 if (operationName != null) {
1771 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1772 log.debug("artifact label cannot be set {}", artifactLabel);
1773 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1776 artifactLabel = operationName;
1779 String displayName = artifactInfo.getArtifactDisplayName();
1780 if (displayName == null || displayName.isEmpty()) {
1781 displayName = artifactLabel;
1783 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1784 artifactInfo.setArtifactDisplayName(displayName);
1786 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1787 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1788 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1790 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1792 if (artifactLabel.isEmpty()) {
1793 log.debug("missing normalized artifact logical name for component {}", componentId);
1794 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1797 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1798 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1799 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1800 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1802 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1803 log.debug("Non unique Artifact label : {}", artifactLabel);
1804 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1807 artifactInfo.setArtifactLabel(artifactLabel);
1809 return Either.left(ActionStatus.OK);
1812 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1813 boolean isUnique = true;
1814 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1815 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1816 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1819 artifacts = artifactToscaOperation.getArtifacts(componentId);
1822 if (artifacts.isLeft()) {
1823 for (String label : artifacts.left().value().keySet()) {
1824 if (label.equals(artifactLabel)) {
1830 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1831 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1832 .getAllInterfacesOfResource(componentId, true, true);
1833 if (allInterfacesOfResource.isLeft()) {
1834 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1835 for (Operation operation : interace.getOperationsMap().values()) {
1836 if (operation.getImplementation() != null && operation.getImplementation()
1838 .equals(artifactLabel)) {
1849 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1850 ComponentTypeEnum componentType) {
1851 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1852 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1853 String artifactName = artifactInfo.getArtifactName();
1854 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1855 if (artifacts.left().value().values().stream()
1856 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1857 //check whether it is the same artifact we hold (by label)
1858 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1862 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1863 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1868 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1869 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1870 .getAllInterfacesOfResource(componentId, true, true);
1872 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1873 return !allInterfacesOfResource.left().value()
1875 .stream().map(InterfaceDefinition :: getOperationsMap)
1876 .flatMap(map -> map.values().stream())
1877 .map(OperationDataDefinition::getImplementation)
1878 .filter(Objects::nonNull)
1879 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1880 && !artifactLabel.equals(add.getArtifactLabel()));
1885 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1886 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1887 .getAllInterfacesOfResource(componentId, true, true);
1889 if (allInterfacesOfResource.isLeft()){
1890 return !allInterfacesOfResource.left().value()
1892 .stream().map(InterfaceDefinition :: getOperationsMap)
1893 .flatMap(map -> map.values().stream())
1894 .map(OperationDataDefinition::getImplementation)
1895 .filter(Objects::nonNull)
1896 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1901 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1902 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1903 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1904 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1905 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1908 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1910 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1911 log.debug("failed to retrieve artifacts for {} ", componentId);
1912 return Either.right(artifactsResponse.right().value());
1914 return Either.left(artifactsResponse.left().value().entrySet()
1916 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1917 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1920 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1921 return artifacts.entrySet()
1923 .map(x -> x.getValue().getArtifactName())
1924 .collect(Collectors.toList());
1927 // ***************************************************************
1929 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1930 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1931 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1932 Either<ArtifactDefinition, Operation> insideEither = null;
1933 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1934 String instanceId = null;
1935 String instanceName = null;
1936 if (foundInstance != null) {
1937 instanceId = foundInstance.getUniqueId();
1938 instanceName = foundInstance.getName();
1940 boolean isLeft = false;
1941 String artifactUniqueId = null;
1942 StorageOperationStatus error = null;
1943 // information/deployment/api aritfacts
1944 log.trace("Try to create entry on graph");
1945 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1946 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1947 .getUniqueId(), nodeType, true, instanceId);
1949 isLeft = result.isLeft();
1951 artifactUniqueId = result.left().value().getUniqueId();
1952 result.left().value();
1954 insideEither = Either.left(result.left().value());
1955 resultOp = Either.left(insideEither);
1957 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1958 if (error != StorageOperationStatus.OK) {
1964 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1965 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1969 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1970 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1971 .getArtifactDisplayName());
1972 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1973 resultOp = Either.right(responseFormat);
1979 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1980 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1982 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1983 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1984 Either<ArtifactDefinition, Operation> insideEither = null;
1985 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1986 String instanceId = null;
1987 String instanceName = null;
1988 if (foundInstance != null) {
1989 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1990 log.debug("Failed to create artifact, already exists");
1991 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1992 .getArtifactLabel());
1993 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1995 resultOp = Either.right(responseFormat);
1999 instanceId = foundInstance.getUniqueId();
2000 instanceName = foundInstance.getName();
2002 if (artifactData == null) {
2003 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2004 log.debug("Failed to create artifact object for ES.");
2005 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2006 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
2007 resultOp = Either.right(responseFormat);
2011 // set on graph object id of artifact in ES!
2012 artifactInfo.setEsId(artifactData.getId());
2014 boolean isLeft = false;
2015 String artifactUniqueId = null;
2016 StorageOperationStatus error = null;
2017 if (interfaceType != null && operationName != null) {
2018 // lifecycle artifact
2019 Operation operation = convertToOperation(artifactInfo, operationName);
2021 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2023 isLeft = result.isLeft();
2025 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
2026 result.left().value().getImplementation();
2028 insideEither = Either.right(result.left().value());
2029 resultOp = Either.left(insideEither);
2032 error = result.right().value();
2036 // information/deployment/api aritfacts
2037 log.trace("Try to create entry on graph");
2038 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2039 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2040 .getUniqueId(), nodeType, true, instanceId);
2042 isLeft = result.isLeft();
2044 artifactUniqueId = result.left().value().getUniqueId();
2045 artifactData.setId(result.left().value().getEsId());
2046 insideEither = Either.left(result.left().value());
2047 resultOp = Either.left(insideEither);
2049 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2050 if (error != StorageOperationStatus.OK) {
2056 error = result.right().value();
2060 boolean res = saveArtifacts(artifactData, parentId);
2063 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2065 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2066 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2070 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2071 log.debug(FAILED_SAVE_ARTIFACT);
2072 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2073 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2075 resultOp = Either.right(responseFormat);
2080 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2081 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2082 .getArtifactDisplayName());
2083 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2084 resultOp = Either.right(responseFormat);
2090 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2091 ComponentInstance foundInstance = null;
2092 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2093 foundInstance = containerComponent.getComponentInstances()
2095 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2099 return foundInstance;
2102 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2104 Either<Boolean, ResponseFormat> result = Either.left(true);
2105 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2107 validateArtifactTypeExists(responseWrapper, artifactInfo);
2109 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2111 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2113 if (responseWrapper.isEmpty()) {
2114 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2117 // Common code for all types
2118 // not allowed to change artifactType
2119 if (responseWrapper.isEmpty() && !isCreate) {
2120 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2121 if (validateServiceApiType.isRight()) {
2122 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2125 if (responseWrapper.isEmpty()) {
2126 if (parentType.equals(NodeTypeEnum.Resource)) {
2127 Resource resource = (Resource) parentComponent;
2128 ResourceTypeEnum resourceType = resource.getResourceType();
2129 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2130 if (config == null) {
2131 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2132 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2133 .getArtifactType()));
2136 List<String> myList = config.getValidForResourceTypes();
2137 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2138 if (either.isRight()) {
2139 responseWrapper.setInnerElement(either.right().value());
2144 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2147 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2148 String artifactName = artifactInfo.getArtifactName();
2149 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2150 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2154 if (responseWrapper.isEmpty()) {
2155 switch (artifactType) {
2159 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2162 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2163 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2165 case DCAE_INVENTORY_TOSCA:
2166 case DCAE_INVENTORY_JSON:
2167 case DCAE_INVENTORY_POLICY:
2168 // Validation is done in handle payload.
2169 case DCAE_INVENTORY_DOC:
2170 case DCAE_INVENTORY_BLUEPRINT:
2171 case DCAE_INVENTORY_EVENT:
2172 // No specific validation
2174 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2180 if (!responseWrapper.isEmpty()) {
2181 result = Either.right(responseWrapper.getInnerElement());
2186 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2187 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2188 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2189 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2190 .getArtifactType());
2191 responseWrapper.setInnerElement(responseFormat);
2192 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2196 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2197 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2198 if (parentType.equals(NodeTypeEnum.Resource)) {
2199 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2201 .getResourceDeploymentArtifacts();
2203 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2204 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2206 .getResourceInstanceDeploymentArtifacts();
2209 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2211 .getServiceDeploymentArtifacts();
2213 return resourceDeploymentArtifacts;
2216 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2217 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2218 if (artifactType == null) {
2219 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2220 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2221 .getArtifactType());
2222 responseWrapper.setInnerElement(responseFormat);
2223 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2227 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2228 ArtifactTypeConfig retConfig = null;
2229 String fileType = artifactType.getType();
2230 if (parentType.equals(NodeTypeEnum.Resource)) {
2231 retConfig = ConfigurationManager.getConfigurationManager()
2233 .getResourceDeploymentArtifacts()
2236 else if (parentType.equals(NodeTypeEnum.Service)) {
2237 retConfig = ConfigurationManager.getConfigurationManager()
2239 .getServiceDeploymentArtifacts()
2242 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2243 retConfig = ConfigurationManager.getConfigurationManager()
2245 .getResourceInstanceDeploymentArtifacts()
2251 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2252 // extract heat parameters
2253 if (artifactInfo.getPayloadData() != null) {
2254 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2255 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2256 .getArtifactType());
2257 if (heatParameters.isRight() && (!heatParameters.right()
2259 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2260 log.info("failed to parse heat parameters ");
2261 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2262 .getArtifactType());
2263 return Either.right(responseFormat);
2265 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2266 artifactInfo.setListHeatParameters(heatParameters.left().value());
2269 return Either.left(true);
2274 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2275 String fileType = artifactType.getType();
2276 List<String> acceptedTypes = null;
2277 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2278 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2279 log.debug("parent type of artifact can be either resource or service");
2280 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2284 if (deploymentAcceptedTypes == null) {
2285 log.debug("parent type of artifact can be either resource or service");
2286 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2287 .getArtifactType()));
2291 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2294 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2297 String artifactName = artifactInfo.getArtifactName();
2298 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2299 // Pavel - File extension validation is case-insensitive - Ella,
2301 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2302 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2303 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2308 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2310 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2311 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2312 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2314 if (errorWrapper.isEmpty()) {
2315 validateValidYaml(errorWrapper, artifactInfo);
2318 if (errorWrapper.isEmpty()) {
2319 // Validate Heat Exist
2320 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2321 .getComponentType());
2324 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2325 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2328 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2329 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2333 Either<Boolean, ResponseFormat> eitherResponse;
2334 if (errorWrapper.isEmpty()) {
2335 eitherResponse = Either.left(true);
2338 eitherResponse = Either.right(errorWrapper.getInnerElement());
2340 return eitherResponse;
2343 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2344 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2345 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2346 if (fillArtifactPayload.isRight()) {
2347 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2348 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2352 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2356 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2357 Either<Boolean, ResponseFormat> result = Either.left(true);
2358 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2360 if (eitherArtifactData.isLeft()) {
2361 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2362 data = Base64.encodeBase64(data);
2363 payloadWrapper.setInnerElement(data);
2366 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2369 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2370 result = Either.right(responseFormat);
2376 @SuppressWarnings("unchecked")
2377 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2378 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2379 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2380 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2381 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2383 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2384 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2385 if (eitherHeatEnvProperties.isRight()) {
2386 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2387 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2388 errorWrapper.setInnerElement(responseFormat);
2389 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2391 else if (eitherHeatProperties.isRight()) {
2392 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2393 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2394 .getArtifactName(), heatArtifact.getArtifactName());
2395 errorWrapper.setInnerElement(responseFormat);
2396 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2397 .getArtifactName());
2400 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2401 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2402 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2403 if (!heatEnvPropertiesKeys.isEmpty()) {
2404 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2405 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2406 .getArtifactName(), heatArtifact.getArtifactName());
2407 errorWrapper.setInnerElement(responseFormat);
2412 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2413 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2414 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2416 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2417 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2418 .getArtifactType());
2419 errorWrapper.setInnerElement(responseFormat);
2420 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2424 private boolean isValidXml(byte[] xmlToParse) {
2425 boolean isXmlValid = true;
2427 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2428 setFeatures(reader);
2429 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2431 catch (ParserConfigurationException | IOException | SAXException e) {
2432 log.debug("Xml is invalid : {}", e.getMessage(), e);
2438 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2440 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2441 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2443 catch (SAXNotRecognizedException e) {
2444 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2448 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2449 boolean artifactNameFound = false;
2450 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2453 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2454 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2456 if (artifactNameFound) {
2457 String parentName = parentComponent.getName();
2458 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2459 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2460 .name(), parentName, artifactName);
2462 errorWrapper.setInnerElement(responseFormat);
2463 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2468 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2469 ComponentTypeEnum componentType) {
2470 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2471 if (res.isRight()) {
2472 ResponseFormat responseFormat;
2473 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2474 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2477 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2479 errorWrapper.setInnerElement(responseFormat);
2482 ArtifactDefinition heatArtifact = res.left().value();
2483 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2486 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2487 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2488 // timeout > 0 for HEAT artifacts
2489 Integer timeout = artifactInfo.getTimeout();
2490 if (timeout == null) {
2491 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2492 artifactInfo.setTimeout(defaultTimeout);
2493 // HEAT artifact but timeout is invalid
2495 else if (timeout < 1) {
2496 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2499 // US649856 - Allow several HEAT files on Resource
2500 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2501 return Either.left(true);
2504 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2505 String listToString = (typeList != null) ? typeList.toString() : "";
2506 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2507 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2508 .getArtifactName(), listToString, resourceType.getValue());
2509 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2510 String resourceTypeName = resourceType.name();
2511 if (typeList != null && typeList.contains(resourceTypeName)) {
2512 either = Either.left(true);
2517 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2518 if (artifactInfo.getHeatParameters() != null) {
2519 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2520 String parameterType = heatParam.getType();
2521 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2522 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2523 if (heatParameterType == null) {
2524 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2526 return Either.right(responseFormat);
2529 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2530 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2531 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2532 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2533 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2534 .getType(), heatParam.getName());
2535 return Either.right(responseFormat);
2539 return Either.left(artifactInfo);
2542 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2543 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2544 if (parentComponent.getDeploymentArtifacts() != null) {
2545 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2546 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2547 if (getRI.isRight()) {
2548 return deploymentArtifacts;
2550 ComponentInstance ri = getRI.left().value();
2551 if (ri.getDeploymentArtifacts() != null) {
2552 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2555 else if (parentComponent.getDeploymentArtifacts() != null) {
2556 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2559 return deploymentArtifacts;
2562 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2563 // on create if null add informational to current
2564 if (artifactInfo.getArtifactGroupType() == null) {
2565 artifactInfo.setArtifactGroupType(type);
2567 if (artifactInfo.getUniqueId() != null) {
2568 log.error("artifact uniqid cannot be set ignoring");
2570 artifactInfo.setUniqueId(null);
2572 if (artifactInfo.getArtifactRef() != null) {
2573 log.error("artifact ref cannot be set ignoring");
2575 artifactInfo.setArtifactRef(null);
2577 if (artifactInfo.getArtifactRepository() != null) {
2578 log.error("artifact repository cannot be set ignoring");
2580 artifactInfo.setArtifactRepository(null);
2582 if (artifactInfo.getUserIdCreator() != null) {
2583 log.error("creator uuid cannot be set ignoring");
2585 artifactInfo.setArtifactCreator(user.getUserId());
2587 if (artifactInfo.getUserIdLastUpdater() != null) {
2588 log.error("userId of last updater cannot be set ignoring");
2590 artifactInfo.setUserIdLastUpdater(user.getUserId());
2592 if (artifactInfo.getCreatorFullName() != null) {
2593 log.error("creator Full name cannot be set ignoring");
2595 String fullName = user.getFirstName() + " " + user.getLastName();
2596 artifactInfo.setUpdaterFullName(fullName);
2598 if (artifactInfo.getUpdaterFullName() != null) {
2599 log.error("updater Full name cannot be set ignoring");
2601 artifactInfo.setUpdaterFullName(fullName);
2603 if (artifactInfo.getCreationDate() != null) {
2604 log.error("Creation Date cannot be set ignoring");
2606 long time = System.currentTimeMillis();
2607 artifactInfo.setCreationDate(time);
2609 if (artifactInfo.getLastUpdateDate() != null) {
2610 log.error("Last Update Date cannot be set ignoring");
2612 artifactInfo.setLastUpdateDate(time);
2614 if (artifactInfo.getEsId() != null) {
2615 log.error("es id cannot be set ignoring");
2617 artifactInfo.setEsId(null);
2622 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2623 String id = artifactId;
2624 if (artifactId == null || artifactId.isEmpty()) {
2625 String uniqueId = null;
2626 if (interfaceName != null && operationName != null) {
2627 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2628 .getArtifactLabel());
2631 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2633 artifactInfo.setUniqueId(uniqueId);
2634 artifactInfo.setEsId(uniqueId);
2638 artifactInfo.setUniqueId(artifactId);
2639 artifactInfo.setEsId(artifactId);
2644 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2645 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2646 BeEcompErrorManager.getInstance()
2647 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2648 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2649 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2652 boolean artifactTypeExist = false;
2653 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2654 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2656 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2657 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2661 allArtifactTypes = elementOperation.getAllArtifactTypes();
2663 if (allArtifactTypes.isRight()) {
2664 BeEcompErrorManager.getInstance()
2665 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2669 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2671 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2674 for (ArtifactType type : allArtifactTypes.left().value()) {
2675 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2676 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2677 artifactTypeExist = true;
2682 if (!artifactTypeExist) {
2683 BeEcompErrorManager.getInstance()
2684 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2685 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2686 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2687 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2688 .getArtifactType()));
2691 return Either.left(ActionStatus.OK);
2694 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2696 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2697 List<ArtifactType> artifactTypes = new ArrayList<>();
2699 if (parentType.equals(NodeTypeEnum.Service)) {
2700 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2702 .getServiceDeploymentArtifacts();
2704 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2705 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2707 .getResourceInstanceDeploymentArtifacts();
2710 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2712 .getResourceDeploymentArtifacts();
2714 if (deploymentArtifacts != null) {
2715 for (String artifactType : deploymentArtifacts.keySet()) {
2716 ArtifactType artifactT = new ArtifactType();
2717 artifactT.setName(artifactType);
2718 artifactTypes.add(artifactT);
2720 return Either.left(artifactTypes);
2723 return Either.right(ActionStatus.GENERAL_ERROR);
2728 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2729 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2730 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2732 return Either.left(true);
2736 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2737 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2738 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2741 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2742 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2743 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2745 artifactInfo.setArtifactName(normalizeFileName);
2747 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2748 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2751 return Either.left(true);
2754 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2755 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2756 log.info("artifact type is missing operation ignored");
2757 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2760 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2761 log.info("artifact type cannot be changed operation ignored");
2762 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2764 return Either.left(true);
2767 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2768 if (artifactInfo.getArtifactGroupType() == null) {
2769 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2772 else if (!currentArtifact.getArtifactGroupType()
2774 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2775 log.info("artifact group type cannot be changed. operation failed");
2776 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2778 return Either.left(artifactInfo);
2781 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2783 // on update if null add informational to current
2784 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2785 currentArtifact.setArtifactGroupType(type);
2788 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2789 log.error("artifact uniqid cannot be set ignoring");
2791 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2793 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2794 .equals(artifactInfo.getArtifactRef())) {
2795 log.error("artifact ref cannot be set ignoring");
2797 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2799 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2800 .equals(artifactInfo.getArtifactRepository())) {
2801 log.error("artifact repository cannot be set ignoring");
2803 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2805 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2806 .equals(artifactInfo.getUserIdCreator())) {
2807 log.error("creator uuid cannot be set ignoring");
2809 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2811 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2812 .equals(artifactInfo.getArtifactCreator())) {
2813 log.error("artifact creator cannot be set ignoring");
2815 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2817 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2818 .equals(artifactInfo.getUserIdLastUpdater())) {
2819 log.error("userId of last updater cannot be set ignoring");
2821 artifactInfo.setUserIdLastUpdater(user.getUserId());
2823 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2824 .equals(artifactInfo.getCreatorFullName())) {
2825 log.error("creator Full name cannot be set ignoring");
2827 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2829 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2830 .equals(artifactInfo.getUpdaterFullName())) {
2831 log.error("updater Full name cannot be set ignoring");
2833 String fullName = user.getFirstName() + " " + user.getLastName();
2834 artifactInfo.setUpdaterFullName(fullName);
2836 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2837 .equals(artifactInfo.getCreationDate())) {
2838 log.error("Creation Date cannot be set ignoring");
2840 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2842 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2843 .equals(artifactInfo.getLastUpdateDate())) {
2844 log.error("Last Update Date cannot be set ignoring");
2846 long time = System.currentTimeMillis();
2847 artifactInfo.setLastUpdateDate(time);
2849 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2850 log.error("es id cannot be set ignoring");
2852 artifactInfo.setEsId(currentArtifact.getUniqueId());
2854 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2855 .equals(artifactInfo.getArtifactDisplayName())) {
2856 log.error(" Artifact Display Name cannot be set ignoring");
2858 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2860 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2861 .equals(artifactInfo.getServiceApi())) {
2862 log.debug("serviceApi cannot be set. ignoring.");
2864 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2866 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2867 .equals(artifactInfo.getArtifactGroupType())) {
2868 log.debug("artifact group cannot be set. ignoring.");
2870 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2872 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2874 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2875 .isEmpty() && !currentArtifact.getArtifactUUID()
2876 .equals(artifactInfo.getArtifactUUID())) {
2877 log.debug("artifact UUID cannot be set. ignoring.");
2879 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2881 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2882 .getHeatParameters()
2883 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2884 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2888 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2890 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2891 for (HeatParameterDefinition parameter : heatParameters) {
2892 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2894 if (currentParam != null) {
2896 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2897 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2898 parameter.setName(currentParam.getName());
2900 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2901 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2902 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2903 parameter.setDefaultValue(currentParam.getDefaultValue());
2905 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2906 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2907 parameter.setType(currentParam.getType());
2909 if (parameter.getDescription() != null && !parameter.getDescription()
2910 .equalsIgnoreCase(currentParam.getDescription())) {
2911 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2912 parameter.setDescription(currentParam.getDescription());
2915 // check and set current value
2916 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2917 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2918 parameter.setCurrentValue(currentParam.getDefaultValue());
2924 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2926 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2927 for (HeatParameterDefinition param : currentParameters) {
2928 currentParamsMap.put(param.getUniqueId(), param);
2930 return currentParamsMap;
2933 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2934 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2935 log.debug("Artifact url cannot be empty.");
2936 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2938 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2940 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2941 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2943 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2944 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2947 return Either.left(true);
2950 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2951 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2952 log.debug("Artifact description cannot be empty.");
2953 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2955 String description = artifactInfo.getDescription();
2956 description = ValidationUtils.removeNoneUtf8Chars(description);
2957 description = ValidationUtils.normaliseWhitespace(description);
2958 description = ValidationUtils.stripOctets(description);
2959 description = ValidationUtils.removeHtmlTagsOnly(description);
2960 if (!ValidationUtils.validateIsEnglish(description)) {
2961 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2963 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2964 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2965 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2967 artifactInfo.setDescription(description);
2968 return Either.left(true);
2971 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2972 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2973 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2974 String prevArtifactId = null;
2975 String currArtifactId = artifactId;
2977 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2978 Either<ArtifactDefinition, Operation> insideEither = null;
2980 log.trace("Try to update entry on graph");
2981 String artifactUniqueId = null;
2982 ArtifactDefinition artifactDefinition = artifactInfo;
2983 StorageOperationStatus error;
2986 if (interfaceType == null || operationUuid == null) {
2987 log.debug("Entity on graph is updated. Update artifact in ES");
2989 // Changing previous and current artifactId for auditing
2990 prevArtifactId = currArtifactId;
2991 currArtifactId = artifactDefinition.getUniqueId();
2994 if (decodedPayload == null) {
2995 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2996 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2998 if (artifactFromCassandra.isRight()) {
2999 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3000 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3002 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3003 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3004 resultOp = Either.right(responseFormat);
3007 // clone data to new artifact
3008 artifactData.setData(artifactFromCassandra.left().value().getData());
3009 artifactData.setId(artifactFromCassandra.left().value().getId());
3012 if (artifactDefinition.getEsId() == null) {
3013 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3014 artifactData.setId(artifactDefinition.getUniqueId());
3018 NodeTypeEnum convertParentType = convertParentType(componentType);
3019 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
3020 .getUniqueId(), artifactId, convertParentType, parentId);
3021 isLeft = result.isLeft();
3023 artifactUniqueId = result.left().value().getUniqueId();
3024 artifactDefinition = result.left().value();
3025 String artifactType = artifactInfo.getArtifactType();
3026 if (NodeTypeEnum.Resource == convertParentType
3027 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3028 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3029 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3030 && !artifactUniqueId.equals(artifactId)) {
3031 // need to update the generated id in heat env
3032 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3033 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3035 .filter(a -> a.getValue()
3036 .getGeneratedFromId() != null && a
3038 .getGeneratedFromId()
3039 .equals(artifactId))
3041 if (findFirst.isPresent()) {
3042 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3043 artifactEnvInfo.setArtifactChecksum(null);
3044 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3047 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3049 insideEither = Either.left(result.left().value());
3050 resultOp = Either.left(insideEither);
3051 if (error != StorageOperationStatus.OK) {
3056 error = result.right().value();
3060 // create new entry in ES
3062 if (artifactData.getData() != null) {
3063 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3064 artifactData.setId(artifactDefinition.getEsId());
3066 res = saveArtifacts(artifactData, parentId);
3072 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3073 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3074 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3076 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3077 log.debug(FAILED_SAVE_ARTIFACT);
3078 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3079 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3080 resultOp = Either.right(responseFormat);
3083 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3084 decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3085 currArtifactId, artifactDefinition);
3091 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3092 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3093 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3094 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3095 ArtifactDefinition artifactDefinition) {
3096 StorageOperationStatus error;
3097 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3098 if (decodedPayload == null) {
3099 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3100 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3102 if (artifactFromCassandra.isRight()) {
3103 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3104 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3106 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3107 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3108 resultOp = Either.right(responseFormat);
3111 // clone data to new artifact
3112 artifactData.setData(artifactFromCassandra.left().value().getData());
3113 artifactData.setId(artifactFromCassandra.left().value().getId());
3115 // todo if not exist(first time)
3119 if (artifactDefinition.getEsId() == null) {
3120 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3121 artifactData.setId(artifactDefinition.getUniqueId());
3124 NodeTypeEnum convertParentType = convertParentType(componentType);
3125 // Set additional fields for artifact
3126 artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
3127 artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
3129 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
3130 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
3131 if(updateArtifactOnResourceEither.isRight()){
3132 log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
3133 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
3134 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3136 if (artifactData.getData() != null) {
3137 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3138 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3139 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
3140 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3141 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3142 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3146 Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
3147 if(updateOprEither.isRight()){
3148 return Either.right(updateOprEither.right().value());
3151 return Either.left(Either.left(updateOprEither.left().value()));
3154 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3155 log.trace("Starting payload handling");
3156 byte[] payload = artifactInfo.getPayloadData();
3157 byte[] decodedPayload = null;
3159 if (payload != null && payload.length != 0) {
3160 // the generated artifacts were already decoded by the handler
3161 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3162 if (decodedPayload.length == 0) {
3163 log.debug("Failed to decode the payload.");
3164 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3165 return Either.right(responseFormat);
3168 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3169 artifactInfo.setArtifactChecksum(checkSum);
3170 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3172 // Specific payload validations of different types
3173 Either<Boolean, ResponseFormat> result = Either.left(true);
3174 if (isDeploymentArtifact(artifactInfo)) {
3175 log.trace("Starting deployment artifacts payload validation");
3176 String artifactType = artifactInfo.getArtifactType();
3177 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
3178 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
3179 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
3180 if (isPayloadValid.isRight()) {
3181 ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
3182 return Either.right(responseFormat);
3185 if (payloadType.isHeatRelated()) {
3186 log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
3187 result = extractHeatParameters(artifactInfo);
3190 if (result.isRight()) {
3191 return Either.right(result.right().value());
3194 } // null/empty payload is normal if called from metadata update ONLY.
3195 // The validation of whether this is metadata/payload update case is
3196 // currently done separately
3198 if (!isArtifactMetadataUpdate) {
3199 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3200 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3201 return Either.right(responseFormat);
3204 log.trace("Ended payload handling");
3205 return Either.left(decodedPayload);
3208 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3209 boolean inTransaction) {
3210 User user = new User();
3211 user.setUserId(userUserId);
3212 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3213 if (parent.isRight()) {
3214 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3217 return Either.right(responseFormat);
3219 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3222 false, inTransaction);
3223 if (handleDelete.isRight()) {
3224 return Either.right(handleDelete.right().value());
3226 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3227 return Either.left(result.right().value());
3231 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3232 Operation op = new Operation();
3233 long time = System.currentTimeMillis();
3234 op.setCreationDate(time);
3236 String artifactName = artifactInfo.getArtifactName();
3237 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3239 op.setImplementation(artifactInfo);
3240 op.setLastUpdateDate(time);
3244 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3245 String newArtifactName = operationName + "_" + artifactName;
3246 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3247 return newArtifactName;
3251 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3253 // General validation
3254 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3255 log.debug(NULL_PARAMETER);
3256 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3259 // Normalizing artifact name
3260 artifactName = ValidationUtils.normalizeFileName(artifactName);
3262 // Resource validation
3263 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3264 if (validateResourceNameAndVersion.isRight()) {
3265 return Either.right(validateResourceNameAndVersion.right().value());
3268 Resource resource = validateResourceNameAndVersion.left().value();
3269 String resourceId = resource.getUniqueId();
3271 // Service validation
3272 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3273 if (validateServiceNameAndVersion.isRight()) {
3274 return Either.right(validateServiceNameAndVersion.right().value());
3277 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3278 if (artifacts == null || artifacts.isEmpty()) {
3279 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3280 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3283 ArtifactDefinition deploymentArtifact = null;
3285 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3286 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3287 .equals(artifactName)) {
3288 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3289 deploymentArtifact = artifactDefinition;
3294 if (deploymentArtifact == null) {
3295 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3296 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3299 // Downloading the artifact
3300 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3301 if (downloadArtifactEither.isRight()) {
3302 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3303 return Either.right(downloadArtifactEither.right().value());
3305 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3306 return Either.left(downloadArtifactEither.left().value().getRight());
3310 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3312 // General validation
3313 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3314 log.debug(NULL_PARAMETER);
3315 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3318 // Normalizing artifact name
3319 artifactName = ValidationUtils.normalizeFileName(artifactName);
3321 // Service validation
3322 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3323 if (validateServiceNameAndVersion.isRight()) {
3324 return Either.right(validateServiceNameAndVersion.right().value());
3327 Service service = validateServiceNameAndVersion.left().value();
3329 // ResourceInstance validation
3330 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3331 if (validateResourceInstance.isRight()) {
3332 return Either.right(validateResourceInstance.right().value());
3335 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3337 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3339 final String finalArtifactName = artifactName;
3340 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3342 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3344 .anyMatch(filterArtifactByName);
3345 ArtifactDefinition deployableArtifact;
3347 if (!hasDeploymentArtifacts) {
3348 log.debug("Deployment artifact with name {} not found", artifactName);
3349 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3352 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3353 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3354 // Downloading the artifact
3355 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3357 if (downloadArtifactEither.isRight()) {
3358 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3359 return Either.right(downloadArtifactEither.right().value());
3361 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3362 return Either.left(downloadArtifactEither.left().value().getRight());
3365 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3367 List<ComponentInstance> riList = service.getComponentInstances();
3368 for (ComponentInstance ri : riList) {
3369 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3370 return Either.left(ri);
3374 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3377 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3379 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3380 if (serviceListBySystemName.isRight()) {
3381 log.debug("Couldn't fetch any service with name {}", serviceName);
3382 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3384 .value(), ComponentTypeEnum.SERVICE), serviceName));
3386 List<Service> serviceList = serviceListBySystemName.left().value();
3387 if (serviceList == null || serviceList.isEmpty()) {
3388 log.debug("Couldn't fetch any service with name {}", serviceName);
3389 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3392 Service foundService = null;
3393 for (Service service : serviceList) {
3394 if (service.getVersion().equals(serviceVersion)) {
3395 log.trace("Found service with version {}", serviceVersion);
3396 foundService = service;
3401 if (foundService == null) {
3402 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3403 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3404 .getValue(), serviceVersion));
3406 return Either.left(foundService);
3409 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3411 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3412 if (resourceListBySystemName.isRight()) {
3413 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3414 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3416 .value()), resourceName));
3418 return Either.left(resourceListBySystemName.left().value());
3421 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3423 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3424 if (serviceName == null || serviceVersion == null || artifactName == null) {
3425 log.debug(NULL_PARAMETER);
3426 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3429 // Normalizing artifact name
3430 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3432 // Service validation
3433 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3434 if (validateServiceNameAndVersion.isRight()) {
3435 return Either.right(validateServiceNameAndVersion.right().value());
3438 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3440 // Looking for deployment or tosca artifacts
3441 Service service = validateServiceNameAndVersion.left().value();
3443 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3444 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3445 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3448 Optional<ArtifactDefinition> foundArtifactOptl = null;
3450 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3451 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3452 // filters artifact by name
3453 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3455 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3456 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3457 // filters TOSCA artifact by name
3458 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3460 if (!foundArtifactOptl.isPresent()) {
3461 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3462 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3464 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3465 // Downloading the artifact
3466 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3468 if (downloadArtifactEither.isRight()) {
3469 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3470 return Either.right(downloadArtifactEither.right().value());
3472 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3473 return Either.left(downloadArtifactEither.left().value().getRight());
3476 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3477 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3478 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3479 if (artifactById.isRight()) {
3480 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3481 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3482 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3484 ArtifactDefinition artifactDefinition = artifactById.left().value();
3485 if (artifactDefinition == null) {
3486 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3487 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3490 return downloadArtifact(artifactDefinition);
3493 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3494 boolean found = false;
3495 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3496 if (artifactsS != null) {
3497 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3498 if (entry.getValue().getUniqueId().equals(artifactId)) {
3504 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3505 if (!found && deploymentArtifactsS != null) {
3506 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3507 if (entry.getValue().getUniqueId().equals(artifactId)) {
3513 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3514 if (!found && toscaArtifactsS != null) {
3515 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3516 if (entry.getValue().getUniqueId().equals(artifactId)) {
3523 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3524 if (!found && interfaces != null) {
3525 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3526 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3527 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3528 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3529 .getImplementation()
3531 .equals(artifactId)) {
3539 switch (component.getComponentType()) {
3543 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3544 if (!found && apiArtifacts != null) {
3545 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3546 if (entry.getValue().getUniqueId().equals(artifactId)) {
3560 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3562 boolean found = false;
3563 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3564 ComponentInstance resourceInstance = null;
3565 for (ComponentInstance ri : resourceInstances) {
3566 if (ri.getUniqueId().equals(resourceInstanceId)) {
3567 resourceInstance = ri;
3571 if (resourceInstance != null) {
3572 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3573 if (artifacts != null) {
3574 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3575 if (entry.getValue().getUniqueId().equals(artifactId)) {
3582 artifacts = resourceInstance.getArtifacts();
3583 if (artifacts != null) {
3584 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3585 if (entry.getValue().getUniqueId().equals(artifactId)) {
3596 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3597 String containerComponentType) {
3599 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3600 componentForAudit.getNodeType();
3602 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3603 .getToscaFullElement(componentId);
3605 if (componentResult.isRight()) {
3606 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3607 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3608 log.debug("Service not found, serviceId {}", componentId);
3609 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3610 return Either.right(responseFormat);
3612 return Either.left(componentResult.left().value());
3615 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3616 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3617 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3618 if (canWork.isRight()) {
3619 String uniqueId = component.getUniqueId();
3620 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3621 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3623 .getComponentType(), null);
3624 return Either.right(canWork.right().value());
3627 return Either.left(true);
3630 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3632 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3633 String role = user.getRole();
3634 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3635 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3636 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3637 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3638 return Either.right(responseFormat);
3641 return Either.left(true);
3644 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3647 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3648 } catch(ByResponseFormatComponentException e){
3649 ResponseFormat responseFormat = e.getResponseFormat();
3650 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3652 } catch(ByActionStatusComponentException e){
3653 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3654 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3657 return Either.left(user);
3660 private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
3661 ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
3662 User user = new User();
3663 user.setUserId(userId);
3664 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3667 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3668 AuditingActionEnum auditingAction = null;
3669 switch (operation.getArtifactOperationEnum()) {
3671 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3674 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3677 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3680 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3685 return auditingAction;
3688 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3689 String esArtifactId = artifactDefinition.getEsId();
3690 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3691 if (artifactfromES.isRight()) {
3692 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3693 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3694 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3695 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3696 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3697 .getArtifactDisplayName());
3699 return Either.right(responseFormat);
3702 ESArtifactData esArtifactData = artifactfromES.left().value();
3703 byte[] data = esArtifactData.getDataAsArray();
3705 log.debug("Artifact data from ES is null");
3706 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3708 String artifactName = artifactDefinition.getArtifactName();
3709 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3710 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3713 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3714 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3717 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3718 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3720 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3721 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3724 log.info("Failed to save artifact {}.", artifactData.getId());
3730 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3731 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3734 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3735 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3738 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3739 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3740 if (user.isRight()) {
3741 ResponseFormat responseFormat;
3742 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3743 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3744 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3747 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3748 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3750 return Either.right(responseFormat);
3753 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3755 .value(), groupType);
3756 return Either.left(artifactDefinition);
3759 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3760 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3762 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3763 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3764 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3766 artifactInfo.setArtifactDisplayName(artifactName);
3767 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3768 artifactInfo.setArtifactType(artifactType);
3769 artifactInfo.setDescription(artifactDescription);
3770 artifactInfo.setArtifactGroupType(groupType);
3771 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3773 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3775 return artifactInfo;
3778 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3779 String uniqueId = null;
3781 if (resourceId != null) {
3782 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3784 artifactInfo.setUniqueId(uniqueId);
3786 artifactInfo.setUserIdCreator(user.getUserId());
3787 String fullName = user.getFullName();
3788 artifactInfo.setUpdaterFullName(fullName);
3790 long time = System.currentTimeMillis();
3792 artifactInfo.setCreatorFullName(fullName);
3793 artifactInfo.setCreationDate(time);
3795 artifactInfo.setLastUpdateDate(time);
3796 artifactInfo.setUserIdLastUpdater(user.getUserId());
3798 artifactInfo.setMandatory(true);
3801 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3802 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3805 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3806 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3809 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3811 byte[] payload = payloadStr.getBytes();
3813 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3814 return Either.left(artifactData);
3818 * @param artifactDefinition
3821 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3822 String instanceId, boolean shouldLock, boolean inTransaction) {
3823 String payload = generateHeatEnvPayload(artifactDefinition);
3824 String prevUUID = artifactDefinition.getArtifactUUID();
3825 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3826 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3828 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3831 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3832 boolean shouldLock, boolean inTransaction, String instanceId) {
3833 String payload = generateHeatEnvPayload(artifactDefinition);
3834 String prevUUID = artifactDefinition.getArtifactUUID();
3835 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3836 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3838 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3841 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3842 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3843 List<ComponentInstance> componentInstances = component.getComponentInstances();
3844 if (componentInstances != null) {
3845 Optional<ComponentInstance> findFirst = componentInstances.stream()
3846 .filter(ci -> ci.getUniqueId()
3847 .equals(instanceId))
3849 if (findFirst.isPresent()) {
3850 ComponentInstance relevantInst = findFirst.get();
3851 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3852 .getGroupInstances());
3854 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3855 updatedGroupInstances.forEach(gi -> {
3856 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3857 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3859 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3860 if (status.isRight()) {
3861 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3862 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3863 .convertFromStorageResponse(status.right()
3864 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3865 return Either.right(responseFormat);
3871 return Either.left(updatedArtDef);
3874 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3875 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3876 StringBuilder sb = new StringBuilder();
3877 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3878 sb.append("parameters:\n");
3879 if (heatParameters != null) {
3880 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3882 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3884 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3886 String heatValue = heatParameterDefinition.getCurrentValue();
3887 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3888 heatValue = heatParameterDefinition.getDefaultValue();
3889 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3890 empltyHeatValues.add(heatParameterDefinition);
3894 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3899 .append(heatParameterDefinition.getName())
3902 .append(Boolean.parseBoolean(heatValue))
3907 .append(heatParameterDefinition.getName())
3910 .append(new BigDecimal(heatValue).toPlainString())
3913 case COMMA_DELIMITED_LIST:
3916 .append(heatParameterDefinition.getName())
3923 String value = heatValue;
3924 boolean starts = value.startsWith("\"");
3925 boolean ends = value.endsWith("\"");
3926 if (!(starts && ends)) {
3927 starts = value.startsWith("'");
3928 ends = value.endsWith("'");
3929 if (!(starts && ends)) {
3930 value = "\"" + value + "\"";
3934 .append(heatParameterDefinition.getName())
3944 if (!empltyHeatValues.isEmpty()) {
3945 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3946 empltyHeatValues.forEach(hv -> {
3947 sb.append(" ").append(hv.getName()).append(":");
3948 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3949 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3950 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3951 sb.append(" \"\"").append("\n");
3954 sb.append(" ").append("\n");
3959 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3962 return sb.toString().replaceAll("\\\\n", "\n");
3966 * @param artifactDefinition
3970 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3971 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3972 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
3973 .getHeatParamsUpdateDate(),
3974 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3978 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3979 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3980 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3981 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3985 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3986 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3988 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3990 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3991 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3993 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3994 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3995 ESArtifactData artifactData = null;
3997 if (artifactDataRes.isLeft()) {
3998 artifactData = artifactDataRes.left().value();
4001 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4002 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4003 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4004 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4006 return Either.right(artifactDataRes.right().value());
4008 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4010 String esArtifactId = artifactDefinition.getEsId();
4011 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4012 ESArtifactData esArtifactData;
4013 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4014 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4015 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4016 if (artifactfromES.isRight()) {
4017 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4018 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4019 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4020 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4021 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4023 esArtifactData = artifactfromES.left().value();
4024 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4027 oldCheckSum = artifactDefinition.getArtifactChecksum();
4030 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4033 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4034 if (lockComponent.isRight()) {
4035 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4036 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4037 return Either.right(lockComponent.right().value());
4041 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4043 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4044 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4045 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4046 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4047 .getArtifactType(), artifactDefinition.getEsId());
4048 if (updateArifactDefinitionStatus.isRight()) {
4049 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4051 .value()), artifactDefinition.getArtifactDisplayName());
4052 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4053 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4054 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4055 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4057 return Either.right(responseFormat);
4062 oldCheckSum = artifactDefinition.getArtifactChecksum();
4063 artifactDefinition.setArtifactChecksum(newCheckSum);
4064 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4065 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4066 .getArtifactType(), artifactDefinition.getEsId());
4067 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4068 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4070 log.trace("Update Payload ", artifactDefinition.getEsId());
4072 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4074 artifactDefinition = updateArifactDefinitionStatus.left().value();
4075 artifactData.setId(artifactDefinition.getUniqueId());
4076 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4078 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4079 if (!inTransaction) {
4080 janusGraphDao.commit();
4082 log.debug("Artifact Saved In ES {}", artifactData.getId());
4083 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4084 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4085 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4086 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4090 if (!inTransaction) {
4091 janusGraphDao.rollback();
4093 log.info("Failed to save artifact {}.", artifactData.getId());
4094 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4095 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4096 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4097 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4099 return Either.right(responseFormat);
4103 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4105 .value()), artifactDefinition.getArtifactDisplayName());
4106 log.debug("Failed To update artifact {}", artifactData.getId());
4107 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4108 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4109 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4111 return Either.right(responseFormat);
4117 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4123 return Either.left(artifactDefinition);
4127 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4128 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4129 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4130 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4134 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4135 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4137 Map<String, Object> json = new HashMap<>();
4138 if (artifactId != null && !artifactId.isEmpty()) {
4139 json.put(Constants.ARTIFACT_ID, artifactId);
4142 json.put(Constants.ARTIFACT_NAME, artifactName);
4143 json.put(Constants.ARTIFACT_TYPE, artifactType);
4144 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4146 if (artifactContent != null) {
4147 log.debug("payload is encoded. perform decode");
4148 String encodedPayload = Base64.encodeBase64String(artifactContent);
4149 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4151 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4152 json.put(Constants.ARTIFACT_LABEL, label);
4153 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4154 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4155 : updatedRequiredArtifacts.stream()
4156 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4158 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4159 .map(e -> e.getFileName())
4160 .collect(Collectors.toList()));
4161 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4166 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4168 String jsonStr = gson.toJson(json);
4169 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4170 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4171 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4172 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4173 if (uploadArtifactToService.isRight()) {
4174 return Either.right(uploadArtifactToService.right().value());
4177 return Either.left(uploadArtifactToService.left().value());
4180 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4181 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4182 convertParentType(componentType);
4183 String parentId = parent.getUniqueId();
4184 ArtifactDefinition currArtifact = artifactInfo;
4186 if (origMd5 != null) {
4187 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4188 if (validateMd5.isRight()) {
4189 ResponseFormat responseFormat = validateMd5.right().value();
4190 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4191 return Either.right(responseFormat);
4194 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4195 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4196 if (deploymentValidationResult.isRight()) {
4197 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4198 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4199 return Either.right(responseFormat);
4202 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4203 if (payloadEither.isRight()) {
4204 ResponseFormat responseFormat = payloadEither.right().value();
4205 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4206 return Either.right(responseFormat);
4210 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4211 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4212 return Either.right(responseFormat);
4218 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4219 if (lockComponent.isRight()) {
4220 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4221 .value(), componentType, null);
4222 return Either.right(lockComponent.right().value());
4225 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4227 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4233 if (resultOp == null || resultOp.isRight()) {
4234 log.debug(ROLLBACK);
4235 if (!inTransaction) {
4236 janusGraphDao.rollback();
4241 if (!inTransaction) {
4242 janusGraphDao.commit();
4246 componentType = parent.getComponentType();
4248 NodeTypeEnum nodeType = componentType.getNodeType();
4249 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4253 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4254 ComponentTypeEnum componentType, String origMd5) {
4256 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4257 Either<ArtifactDefinition, Operation> insideEither = null;
4258 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4259 if (getRI.isRight()) {
4260 return Either.right(getRI.right().value());
4262 ComponentInstance ri = getRI.left().value();
4263 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4264 if (getArtifactRes.isRight()) {
4265 return Either.right(getArtifactRes.right().value());
4267 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4269 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4270 .equals(ArtifactTypeEnum.HEAT_VOL
4271 .getType()) || currArtifact
4273 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4274 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4275 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4277 return Either.right(responseFormat);
4279 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4280 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4281 new ArrayList<HeatParameterDefinition>();
4284 if (origMd5 != null) {
4285 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4286 .getName(), currentHeatEnvParams,
4287 updatedHeatEnvParams, currArtifact.getArtifactName());
4288 if (uploadParamsValidationResult.isRight()) {
4289 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4290 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4292 return Either.right(responseFormat);
4294 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4297 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4299 if (validateAndConvertHeatParamers.isRight()) {
4300 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4301 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4303 return Either.right(responseFormat);
4306 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4307 // fill reduced heat env parameters List for updating
4308 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4309 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4310 currArtifact.setListHeatParameters(currentHeatEnvParams);
4312 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4313 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4314 if (updateArifactRes.isRight()) {
4315 log.debug("Failed to update artifact on graph - {}", artifactId);
4316 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4319 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4321 return Either.right(responseFormat);
4323 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4324 if (error != StorageOperationStatus.OK) {
4325 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4326 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4328 return Either.right(responseFormat);
4331 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4333 .getUniqueId(), parent.getUniqueId());
4334 if (error != StorageOperationStatus.OK) {
4335 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4336 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4338 return Either.right(responseFormat);
4342 insideEither = Either.left(currArtifact);
4343 resultOp = Either.left(insideEither);
4344 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4345 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4350 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4351 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4352 String paramName = heatEnvParam.getName();
4353 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4354 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4355 String updatedParamValue = heatEnvParam.getCurrentValue();
4356 currHeatParam.setCurrentValue(updatedParamValue);
4362 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4363 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4365 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4366 Either<ArtifactDefinition, Operation> insideEither = null;
4367 String currentHeatId = currHeatArtifact.getUniqueId();
4369 String esArtifactId = currHeatArtifact.getEsId();
4370 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4371 if (artifactFromES.isRight()) {
4372 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4373 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4374 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4375 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4376 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4379 ESArtifactData esArtifactData = artifactFromES.left().value();
4381 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4383 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4384 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4385 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4387 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4391 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4393 paramName = heatEnvParam.getName();
4394 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4395 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4397 String updatedParamValue = heatEnvParam.getCurrentValue();
4398 if (updatedParamValue == null) {
4399 updatedParamValue = heatEnvParam.getDefaultValue();
4401 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4402 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4403 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4404 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4405 .getType(), paramType.getType(), paramName);
4406 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4407 return Either.right(responseFormat);
4410 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4411 newHeatEnvParams.add(currHeatParam);
4416 if (!newHeatEnvParams.isEmpty()) {
4417 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4418 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4419 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4421 if (operationStatus.isRight()) {
4422 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4424 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4427 return Either.right(responseFormat);
4430 updatedHeatArt = operationStatus.left().value();
4432 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4433 esArtifactData.setId(updatedHeatArt.getEsId());
4435 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4438 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4439 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4440 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4441 .getUniqueId(), responseFormat, componentType, null);
4444 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4445 log.debug(FAILED_SAVE_ARTIFACT);
4446 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4447 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4448 .getUniqueId(), responseFormat, componentType, null);
4449 resultOp = Either.right(responseFormat);
4452 insideEither = Either.left(updatedHeatArt);
4455 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4456 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4457 artifactEnvInfo.setArtifactChecksum(null);
4458 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4459 .getUniqueId(), componentType.getNodeType(), componentId);
4462 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4466 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4467 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4469 .value(), parent, componentType);
4470 if (result != ActionStatus.OK) {
4471 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4472 return Either.right(responseFormat);
4476 if (updatedHeatEnvParams.isEmpty()) {
4477 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4479 resultOp = Either.left(insideEither);
4480 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4481 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4486 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4487 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4488 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4489 return Either.right(responseFormat);
4493 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4494 StorageOperationStatus error = StorageOperationStatus.OK;
4495 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4496 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4497 List<String> groupInstancesId = null;
4498 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4499 groupInstancesId = groupsInstances.stream()
4500 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4501 .contains(artifactId))
4502 .map(GroupInstanceDataDefinition::getUniqueId)
4503 .collect(Collectors.toList());
4505 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4506 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4512 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4513 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4515 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4516 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4517 .getArtifactName(), currArtifactName);
4518 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4519 return Either.right(responseFormat);
4522 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4523 String paramName = uploadedHeatParam.getName();
4524 boolean isExistsInHeat = false;
4525 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4526 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4528 isExistsInHeat = true;
4529 uploadedHeatParam.setType(currHeatParam.getType());
4530 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4531 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4532 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4536 if (!isExistsInHeat) {
4537 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4538 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4539 return Either.right(responseFormat);
4542 return Either.left(updatedHeatEnvParams);
4545 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4546 ResponseFormat responseFormat = null;
4547 List<ComponentInstance> ris = component.getComponentInstances();
4548 for (ComponentInstance ri : ris) {
4549 if (riID.equals(ri.getUniqueId())) {
4550 return Either.left(ri);
4553 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4554 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4555 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4556 return Either.right(responseFormat);
4559 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4560 ResponseFormat responseFormat = null;
4561 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4562 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4563 if (artifactId.equals(artifact.getUniqueId())) {
4564 return Either.left(artifact);
4567 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4568 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4570 return Either.right(responseFormat);
4573 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4574 ArtifactDefinition ret;
4575 if (eitherArtifact.isLeft()) {
4576 ret = eitherArtifact.left().value();
4579 ret = eitherArtifact.right().value().getImplementationArtifact();
4585 * downloads artifact of component by UUIDs
4587 * @param componentType
4588 * @param componentUuid
4589 * @param artifactUUID
4590 * @param resourceCommonInfo
4593 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4594 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4595 Either<byte[], ResponseFormat> result;
4596 byte[] downloadedArtifact = null;
4597 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4598 if (errorWrapper.isEmpty() && component != null) {
4599 resourceCommonInfo.setResourceName(component.getName());
4600 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4602 if (errorWrapper.isEmpty()) {
4603 result = Either.left(downloadedArtifact);
4606 result = Either.right(errorWrapper.getInnerElement());
4612 * downloads an artifact of resource instance of component by UUIDs
4614 * @param componentType
4615 * @param componentUuid
4616 * @param resourceInstanceName
4617 * @param artifactUUID
4620 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4621 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4622 Either<byte[], ResponseFormat> result;
4623 byte[] downloadedArtifact = null;
4624 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4625 if (errorWrapper.isEmpty()) {
4626 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4629 if (errorWrapper.isEmpty()) {
4630 result = Either.left(downloadedArtifact);
4633 result = Either.right(errorWrapper.getInnerElement());
4639 * uploads an artifact to a component by UUID
4643 * @param componentType
4644 * @param componentUuid
4645 * @param resourceCommonInfo
4649 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4650 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4651 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4652 Component component = null;
4653 String componentId = null;
4654 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4655 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4656 String userId = request.getHeader(Constants.USER_ID_HEADER);
4658 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4659 if (getComponentRes.isRight()) {
4660 StorageOperationStatus status = getComponentRes.right().value();
4661 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4662 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4664 if (errorWrapper.isEmpty()) {
4665 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4666 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4668 if (!getComponentRes.left()
4670 .getMetadataDataDefinition()
4672 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4673 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4674 if (component != null) {
4675 componentId = component.getUniqueId();
4676 componentName = component.getName();
4679 resourceCommonInfo.setResourceName(componentName);
4681 if (errorWrapper.isEmpty()) {
4682 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4683 if (actionResult.isRight()) {
4684 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4687 return Either.right(actionResult.right().value());
4689 return Either.left(actionResult.left().value().left().value());
4691 return Either.right(errorWrapper.getInnerElement());
4694 * upload an artifact to a resource instance by UUID
4698 * @param componentType
4699 * @param componentUuid
4700 * @param resourceInstanceName
4704 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4705 ArtifactOperationInfo operation) {
4706 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4707 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4708 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4709 ArtifactDefinition uploadArtifact = null;
4710 Component component = null;
4711 String componentInstanceId;
4713 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4714 String userId = request.getHeader(Constants.USER_ID_HEADER);
4716 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4717 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4718 if (getComponentRes.isRight()) {
4719 StorageOperationStatus status = getComponentRes.right().value();
4720 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4721 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4723 if (errorWrapper.isEmpty() && !getComponentRes.left()
4725 .getMetadataDataDefinition()
4727 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4728 component = checkoutParentComponent(componentType, getComponentRes.left()
4730 .getMetadataDataDefinition()
4731 .getUniqueId(), userId, errorWrapper);
4733 if (errorWrapper.isEmpty()) {
4734 if (component == null) {
4735 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4738 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4741 if (errorWrapper.isEmpty()) {
4742 componentInstanceId = componentRiPair.getRight().getUniqueId();
4743 componentId = componentRiPair.getLeft().getUniqueId();
4744 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4746 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4747 .findParamByType(componentType));
4748 if (actionResult.isRight()) {
4749 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4752 errorWrapper.setInnerElement(actionResult.right().value());
4755 if (errorWrapper.isEmpty()) {
4756 uploadArtifact = actionResult.left().value().left().value();
4757 uploadArtifactResult = Either.left(uploadArtifact);
4760 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4762 return uploadArtifactResult;
4766 * updates an artifact on a component by UUID
4770 * @param componentType
4771 * @param componentUuid
4772 * @param artifactUUID
4776 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4777 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4778 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4779 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4780 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4781 ArtifactDefinition updateArtifact = null;
4782 Component component = null;
4783 String componentId = null;
4784 String artifactId = null;
4785 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4786 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4787 String userId = request.getHeader(Constants.USER_ID_HEADER);
4789 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4790 if (getComponentRes.isRight()) {
4791 StorageOperationStatus status = getComponentRes.right().value();
4792 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4793 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4795 if (errorWrapper.isEmpty()) {
4796 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4797 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4799 if (!getComponentRes.left()
4801 .getMetadataDataDefinition()
4803 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4804 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4805 if (component != null) {
4806 componentId = component.getUniqueId();
4807 componentName = component.getName();
4810 resourceCommonInfo.setResourceName(componentName);
4812 if (errorWrapper.isEmpty()) {
4813 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4815 if (errorWrapper.isEmpty()) {
4816 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4817 if (actionResult.isRight()) {
4818 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4821 errorWrapper.setInnerElement(actionResult.right().value());
4824 if (errorWrapper.isEmpty()) {
4825 updateArtifact = actionResult.left().value().left().value();
4826 updateArtifactResult = Either.left(updateArtifact);
4830 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4832 return updateArtifactResult;
4836 * updates an artifact on a resource instance by UUID
4840 * @param componentType
4841 * @param componentUuid
4842 * @param resourceInstanceName
4843 * @param artifactUUID
4844 * @param operation TODO
4847 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4848 ArtifactOperationInfo operation) {
4850 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4851 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4852 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4853 ArtifactDefinition updateArtifact = null;
4854 Component component = null;
4855 String componentInstanceId = null;
4856 String componentId = null;
4857 String artifactId = null;
4858 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4859 String userId = request.getHeader(Constants.USER_ID_HEADER);
4861 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4862 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4863 if (getComponentRes.isRight()) {
4864 StorageOperationStatus status = getComponentRes.right().value();
4865 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4866 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4868 if (errorWrapper.isEmpty() && !getComponentRes.left()
4870 .getMetadataDataDefinition()
4872 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4873 component = checkoutParentComponent(componentType, getComponentRes.left()
4875 .getMetadataDataDefinition()
4876 .getUniqueId(), userId, errorWrapper);
4878 if (errorWrapper.isEmpty()) {
4879 if (component == null) {
4880 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4883 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4886 if (errorWrapper.isEmpty()) {
4887 componentInstanceId = componentRiPair.getRight().getUniqueId();
4888 componentId = componentRiPair.getLeft().getUniqueId();
4889 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4891 if (errorWrapper.isEmpty()) {
4892 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4894 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4895 .findParamByType(componentType));
4896 if (actionResult.isRight()) {
4897 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4900 errorWrapper.setInnerElement(actionResult.right().value());
4903 if (errorWrapper.isEmpty()) {
4904 updateArtifact = actionResult.left().value().left().value();
4905 updateArtifactResult = Either.left(updateArtifact);
4908 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4910 return updateArtifactResult;
4913 private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4914 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4915 if (componentStorageOperationStatusEither.isRight()) {
4916 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4917 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4918 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4920 Component storedComponent = componentStorageOperationStatusEither.left().value();
4922 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4923 if(!optionalInterface.isPresent()) {
4924 log.debug("Failed to get resource interface for resource Id {}", componentId);
4925 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4928 //fetch the operation from storage
4929 InterfaceDefinition gotInterface = optionalInterface.get();
4930 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4931 Optional<Operation> optionalOperation = operationsMap.values()
4933 .filter(o -> o.getUniqueId().equals(operationUuid))
4935 if (!optionalOperation.isPresent()) {
4936 log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4937 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4938 return Either.right(responseFormat);
4941 Operation operation = optionalOperation.get();
4942 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
4943 implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
4944 implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
4945 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
4946 implementationArtifact.setDescription(artifactInfo.getDescription());
4947 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
4948 implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
4949 implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
4950 implementationArtifact.setEsId(artifactInfo.getEsId());
4951 operation.setImplementation(implementationArtifact);
4952 gotInterface.setOperationsMap(operationsMap);
4953 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
4954 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
4955 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
4956 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
4957 ActionStatus actionStatus =
4958 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
4959 return Either.right(componentsUtils.getResponseFormat(actionStatus));
4962 return Either.left(artifactInfo);
4966 * updates an artifact on a component by UUID
4970 * @param componentType
4971 * @param componentUuid
4972 * @param artifactUUID
4976 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4977 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4978 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
4979 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4980 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4981 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4982 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4983 ArtifactDefinition updateArtifact = null;
4984 String componentId = null;
4985 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4986 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4987 String userId = request.getHeader(Constants.USER_ID_HEADER);
4988 ArtifactDefinition existingArtifactInfo = null;
4989 String interfaceName = null;
4991 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4992 if (getComponentRes.isRight()) {
4993 StorageOperationStatus status = getComponentRes.right().value();
4994 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4995 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4998 if (errorWrapper.isEmpty()) {
4999 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5000 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5001 if (!getComponentRes.left()
5003 .getMetadataDataDefinition()
5005 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5006 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5007 if (component != null) {
5008 componentId = component.getUniqueId();
5009 componentName = component.getName();
5013 resourceCommonInfo.setResourceName(componentName);
5016 if(errorWrapper.isEmpty()){
5017 Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
5018 if (interfaceNameEither.isRight()) {
5019 errorWrapper.setInnerElement(interfaceNameEither.right().value());
5022 interfaceName = interfaceNameEither.left().value();
5025 if(errorWrapper.isEmpty()){
5026 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
5027 if (toscaComponentEither.isRight()) {
5028 StorageOperationStatus status = toscaComponentEither.right().value();
5029 log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
5030 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5033 if (errorWrapper.isEmpty()) {
5034 NodeTypeEnum parentType = convertParentType(componentType);
5035 List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
5036 for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
5037 if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
5038 existingArtifactInfo = artifactDefinition;
5042 if(existingArtifactInfo != null){
5043 return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
5049 if (errorWrapper.isEmpty()) {
5050 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5051 artifactUUID, artifactInfo, origMd5, data, interfaceName,
5052 operationUUID, null, null);
5053 if (actionResult.isRight()) {
5054 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5057 errorWrapper.setInnerElement(actionResult.right().value());
5061 if (errorWrapper.isEmpty()) {
5062 updateArtifact = actionResult.left().value().left().value();
5063 updateArtifactResult = Either.left(updateArtifact);
5067 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5069 return updateArtifactResult;
5072 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5073 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5074 if (componentStorageOperationStatusEither.isRight()) {
5075 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5076 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5077 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5079 Component storedComponent = componentStorageOperationStatusEither.left().value();
5081 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5082 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5083 if(!optionalInterface.isPresent()) {
5084 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5086 return Either.left(optionalInterface.get().getType());
5091 * deletes an artifact on a component by UUID
5094 * @param componentType
5095 * @param componentUuid
5096 * @param artifactUUID
5097 * @param resourceCommonInfo
5098 * @param operation TODO
5101 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5102 ArtifactOperationInfo operation) {
5104 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5105 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5106 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5107 ArtifactDefinition deleteArtifact = null;
5108 Component component = null;
5109 String componentId = null;
5110 String artifactId = null;
5111 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5112 String userId = request.getHeader(Constants.USER_ID_HEADER);
5114 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5115 if (getComponentRes.isRight()) {
5116 StorageOperationStatus status = getComponentRes.right().value();
5117 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5118 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5120 if (errorWrapper.isEmpty()) {
5121 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5122 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5123 if (!getComponentRes.left()
5125 .getMetadataDataDefinition()
5127 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5128 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5129 if (component != null) {
5130 componentId = component.getUniqueId();
5131 componentName = component.getName();
5134 resourceCommonInfo.setResourceName(componentName);
5136 if (errorWrapper.isEmpty()) {
5137 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5139 if (errorWrapper.isEmpty()) {
5140 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5141 if (actionResult.isRight()) {
5142 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5145 errorWrapper.setInnerElement(actionResult.right().value());
5148 if (errorWrapper.isEmpty()) {
5149 deleteArtifact = actionResult.left().value().left().value();
5150 deleteArtifactResult = Either.left(deleteArtifact);
5153 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5155 return deleteArtifactResult;
5159 * deletes an artifact from a resource instance by UUID
5162 * @param componentType
5163 * @param componentUuid
5164 * @param resourceInstanceName
5165 * @param artifactUUID
5166 * @param operation TODO
5169 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5170 ArtifactOperationInfo operation) {
5172 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5173 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5174 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5175 ArtifactDefinition deleteArtifact = null;
5176 Component component = null;
5177 String componentInstanceId = null;
5178 String componentId = null;
5179 String artifactId = null;
5180 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5181 String userId = request.getHeader(Constants.USER_ID_HEADER);
5182 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5183 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5184 if (getComponentRes.isRight()) {
5185 StorageOperationStatus status = getComponentRes.right().value();
5186 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5187 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5189 if (errorWrapper.isEmpty() && !getComponentRes.left()
5191 .getMetadataDataDefinition()
5193 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5194 component = checkoutParentComponent(componentType, getComponentRes.left()
5196 .getMetadataDataDefinition()
5197 .getUniqueId(), userId, errorWrapper);
5199 if (errorWrapper.isEmpty()) {
5200 if (component == null) {
5201 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5204 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5207 if (errorWrapper.isEmpty()) {
5208 componentInstanceId = componentRiPair.getRight().getUniqueId();
5209 componentId = componentRiPair.getLeft().getUniqueId();
5210 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5212 if (errorWrapper.isEmpty()) {
5214 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5215 .findParamByType(componentType));
5217 if (actionResult.isRight()) {
5218 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5221 errorWrapper.setInnerElement(actionResult.right().value());
5224 if (errorWrapper.isEmpty()) {
5225 deleteArtifact = actionResult.left().value().left().value();
5226 deleteArtifactResult = Either.left(deleteArtifact);
5229 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5231 return deleteArtifactResult;
5234 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5235 String artifactId = null;
5236 ArtifactDefinition foundArtifact = null;
5237 if (instance.getDeploymentArtifacts() != null) {
5238 foundArtifact = instance.getDeploymentArtifacts()
5241 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5242 .equals(artifactUUID))
5246 if (foundArtifact == null && instance.getArtifacts() != null) {
5247 foundArtifact = instance.getArtifacts()
5250 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5251 .equals(artifactUUID))
5255 if (foundArtifact == null) {
5256 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5257 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5260 artifactId = foundArtifact.getUniqueId();
5265 @SuppressWarnings("unchecked")
5266 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5267 Map<String, String> existingEnvVersions) {
5268 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5270 .getDeploymentResourceInstanceArtifacts();
5271 if (deploymentResourceArtifacts == null) {
5272 log.debug("no deployment artifacts are configured for generated artifacts");
5273 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5275 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5276 if (placeHolderData == null) {
5277 log.debug("no env type {} are configured for generated artifacts", envType);
5278 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5281 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5282 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5283 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5284 if (createArtifactPlaceHolder.isRight()) {
5285 return Either.right(createArtifactPlaceHolder.right().value());
5287 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5288 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5289 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5290 artifactHeatEnv.setTimeout(0);
5291 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5292 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5293 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5294 ArtifactDefinition heatEnvPlaceholder;
5295 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5296 if (parentType != NodeTypeEnum.ResourceInstance) {
5297 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5298 .getUniqueId(), parentType, parentId);
5299 if (addHeatEnvArtifact.isRight()) {
5300 log.debug("failed to create heat env artifact on resource instance");
5301 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5303 .value(), false), "", null));
5305 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5308 heatEnvPlaceholder = artifactHeatEnv;
5309 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5310 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5313 ComponentTypeEnum componentType = component.getComponentType();
5314 if (parentType == NodeTypeEnum.ResourceInstance) {
5315 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5317 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5318 new ResourceCommonInfo(parentName, componentType.getValue()),
5319 ResourceVersionInfo.newBuilder().build(),
5320 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5321 null, heatEnvPlaceholder, null);
5322 return Either.left(heatEnvPlaceholder);
5325 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5326 if (artifact.getListHeatParameters() == null) {
5329 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5330 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5331 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5332 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5333 heatEnvParameter.setCurrentValue(null);
5334 heatEnvParameters.add(heatEnvParameter);
5336 artifactDefinition.setListHeatParameters(heatEnvParameters);
5339 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5340 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5341 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5342 String name = heatArtifact.getArtifactName();
5345 name = heatArtifact.getArtifactLabel();
5346 fileName = name + "." + envExtension;
5349 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5351 heatEnvArtifact.setArtifactName(fileName);
5354 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5355 if (null != existingEnvVersions) {
5356 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5357 if (null != prevVersion) {
5358 heatEnvArtifact.setArtifactVersion(prevVersion);
5364 * Handles Artifacts Request For Inner Component
5366 * @param artifactsToHandle
5369 * @param vfcsNewCreatedArtifacts
5372 * @param inTransaction
5375 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5376 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5378 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5379 ComponentTypeEnum componentType = component.getComponentType();
5380 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5381 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5382 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5386 for (ArtifactDefinition artifact : artifactsToHandle) {
5387 originData = buildJsonStringForCsarVfcArtifact(artifact);
5388 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5389 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5390 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5391 if (actionResult.isRight()) {
5392 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5393 .getName(), actionResult.right().value());
5394 errorWrapper.setInnerElement(actionResult.right().value());
5395 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5396 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5400 uploadedArtifacts.add(actionResult.left().value().left().value());
5402 if (errorWrapper.isEmpty()) {
5403 handleArtifactsResult = Either.left(uploadedArtifacts);
5406 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5409 catch (Exception e) {
5410 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5411 handleArtifactsResult = Either.right(responseFormat);
5412 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5414 return handleArtifactsResult;
5417 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5418 ComponentInstance componentInstance = null;
5419 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5420 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5421 if (errorWrapper.isEmpty()) {
5422 componentInstance = component.getComponentInstances()
5424 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5425 .equals(normalizedName))
5428 if (componentInstance == null) {
5429 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5431 .getValue(), component.getName()));
5432 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5435 return componentInstance;
5438 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5440 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5441 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5442 ComponentInstance componentInstance = component.getComponentInstances()
5444 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5445 .equals(normalizedName))
5448 if (componentInstance == null) {
5449 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5451 .getValue(), component.getName()));
5452 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5455 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5457 return relatedComponentComponentInstancePair;
5460 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5461 ComponentInstance componentInstance;
5462 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5463 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5464 if (errorWrapper.isEmpty()) {
5465 componentInstance = component.getComponentInstances()
5467 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5470 if (componentInstance == null) {
5471 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5473 .getValue(), component.getName()));
5474 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5477 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5480 return relatedComponentComponentInstancePair;
5483 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5485 byte[] downloadedArtifact = null;
5486 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5487 List<ArtifactDefinition> artifactsList = null;
5488 ArtifactDefinition deploymentArtifact = null;
5489 if (artifacts != null && !artifacts.isEmpty()) {
5490 artifactsList = artifacts.values()
5492 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5493 .equals(artifactUUID))
5494 .collect(Collectors.toList());
5496 if (artifactsList == null || artifactsList.isEmpty()) {
5497 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5498 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5500 if (errorWrapper.isEmpty()) {
5501 deploymentArtifact = artifactsList.get(0);
5502 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5503 if (downloadArtifactEither.isRight()) {
5504 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5505 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5508 if (errorWrapper.isEmpty()) {
5509 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5510 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5512 return downloadedArtifact;
5515 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5516 Component component = null;
5517 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5518 if (getComponentRes.isRight()) {
5519 StorageOperationStatus status = getComponentRes.right().value();
5520 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5521 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5524 component = getComponentRes.left().value();
5529 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5530 Component component = null;
5531 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5532 if (getComponentRes.isRight()) {
5533 StorageOperationStatus status = getComponentRes.right().value();
5534 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5535 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5538 List<Component> value = getComponentRes.left().value();
5539 if (value.isEmpty()) {
5540 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5541 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5542 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5545 component = value.get(0);
5551 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5552 String artifactId = null;
5553 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5554 StorageOperationStatus storageStatus;
5555 ArtifactDefinition latestArtifact = null;
5556 List<ArtifactDefinition> artifacts = null;
5557 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5558 if (getArtifactsRes.isRight()) {
5559 storageStatus = getArtifactsRes.right().value();
5560 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5561 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5562 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5564 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5566 if (errorWrapper.isEmpty()) {
5567 artifacts = getArtifactsRes.left()
5571 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5572 .equals(artifactUUID))
5573 .collect(Collectors.toList());
5574 if (artifacts == null || artifacts.isEmpty()) {
5575 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5576 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5579 if (errorWrapper.isEmpty()) {
5580 latestArtifact = artifacts.stream().max((a1, a2) -> {
5581 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5582 if (compareRes == 0) {
5583 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5584 .getLastUpdateDate());
5588 if (latestArtifact == null) {
5589 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5590 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5593 if (errorWrapper.isEmpty()) {
5594 artifactId = latestArtifact.getUniqueId();
5599 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5601 Component component = null;
5602 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5603 if (getUserRes.isRight()) {
5604 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5607 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5609 if (errorWrapper.isEmpty()) {
5610 User modifier = getUserRes.left().value();
5611 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5612 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5613 if (checkoutRes.isRight()) {
5614 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5615 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5616 errorWrapper.setInnerElement(checkoutRes.right().value());
5619 component = checkoutRes.left().value();
5625 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5626 Map<String, Object> json = new HashMap<>();
5627 String artifactName = artifact.getArtifactName();
5628 json.put(Constants.ARTIFACT_NAME, artifactName);
5629 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5630 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5631 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5632 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5633 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5634 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5635 return gson.toJson(json);
5639 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5640 this.nodeTemplateOperation = nodeTemplateOperation;