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.common.annotations.VisibleForTesting;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import fj.data.Either;
29 import org.apache.commons.codec.binary.Base64;
30 import org.apache.commons.collections.CollectionUtils;
31 import org.apache.commons.collections.MapUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.commons.lang3.tuple.ImmutablePair;
34 import org.elasticsearch.common.Strings;
35 import org.openecomp.sdc.be.components.ArtifactsResolver;
36 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
37 import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector;
38 import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
41 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
43 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
44 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
45 import org.openecomp.sdc.be.config.BeEcompErrorManager;
46 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
47 import org.openecomp.sdc.be.config.ConfigurationManager;
48 import org.openecomp.sdc.be.dao.api.ActionStatus;
49 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
50 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
51 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
52 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
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.NodeTemplateOperation;
77 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
78 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
79 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
80 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
81 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
82 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
83 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
84 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
85 import org.openecomp.sdc.be.resources.data.ESArtifactData;
86 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
87 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
88 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
89 import org.openecomp.sdc.be.servlets.RepresentationUtils;
90 import org.openecomp.sdc.be.tosca.CsarUtils;
91 import org.openecomp.sdc.be.tosca.ToscaError;
92 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
93 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
94 import org.openecomp.sdc.be.user.IUserBusinessLogic;
95 import org.openecomp.sdc.be.user.Role;
96 import org.openecomp.sdc.be.user.UserBusinessLogic;
97 import org.openecomp.sdc.be.utils.TypeUtils;
98 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
99 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
100 import org.openecomp.sdc.common.api.Constants;
101 import org.openecomp.sdc.common.datastructure.Wrapper;
102 import org.openecomp.sdc.common.log.wrappers.Logger;
103 import org.openecomp.sdc.common.util.GeneralUtility;
104 import org.openecomp.sdc.common.util.ValidationUtils;
105 import org.openecomp.sdc.common.util.YamlToObjectConverter;
106 import org.openecomp.sdc.exception.ResponseFormat;
107 import org.springframework.beans.factory.annotation.Autowired;
108 import org.xml.sax.InputSource;
109 import org.xml.sax.SAXException;
110 import org.xml.sax.SAXNotRecognizedException;
111 import org.xml.sax.SAXNotSupportedException;
112 import org.xml.sax.XMLReader;
113 import org.yaml.snakeyaml.Yaml;
115 import javax.servlet.http.HttpServletRequest;
116 import javax.xml.XMLConstants;
117 import javax.xml.parsers.ParserConfigurationException;
118 import javax.xml.parsers.SAXParserFactory;
119 import java.io.ByteArrayInputStream;
120 import java.io.IOException;
121 import java.math.BigDecimal;
122 import java.util.ArrayList;
123 import java.util.Collections;
124 import java.util.Comparator;
125 import java.util.HashMap;
126 import java.util.Iterator;
127 import java.util.List;
128 import java.util.Map;
129 import java.util.Map.Entry;
130 import java.util.Objects;
131 import java.util.Optional;
132 import java.util.Set;
133 import java.util.function.Predicate;
134 import java.util.function.Supplier;
135 import java.util.stream.Collectors;
137 @org.springframework.stereotype.Component("artifactBusinessLogic")
138 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
139 private static final String RESOURCE_INSTANCE = "resource instance";
140 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
141 private static final String ARTIFACT_DESCRIPTION = "artifact description";
142 private static final String ARTIFACT_LABEL = "artifact label";
143 private static final String ARTIFACT_URL = "artifact url";
144 private static final String ARTIFACT_NAME = "artifact name";
145 private static final String ARTIFACT_PAYLOAD = "artifact payload";
147 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
148 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
149 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
151 public static final String HEAT_ENV_NAME = "heatEnv";
152 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
153 public static final String HEAT_ENV_SUFFIX = "env";
154 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
156 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
157 public static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
158 public static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
159 public static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
160 public static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
161 public static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
162 public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
163 public static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
164 public static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
165 public static final String NULL_PARAMETER = "One of the function parameteres is null";
166 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
167 public static final String ROLLBACK = "all changes rollback";
168 public static final String COMMIT = "all changes committed";
169 public static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
170 public static final String UPDATE_ARTIFACT = "Update Artifact";
171 public static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
172 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
174 @javax.annotation.Resource
175 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
176 @javax.annotation.Resource
177 private IUserAdminOperation userOperaton;
179 @javax.annotation.Resource
180 private IElementOperation elementOperation;
182 @javax.annotation.Resource
183 private ResourceBusinessLogic resourceBusinessLogic;
185 @javax.annotation.Resource
186 private ServiceBusinessLogic serviceBusinessLogic;
188 @javax.annotation.Resource
189 private UserBusinessLogic userAdminManager;
191 @javax.annotation.Resource
192 private IHeatParametersOperation heatParametersOperation;
195 private ArtifactCassandraDao artifactCassandraDao;
198 private ToscaExportHandler toscaExportUtils;
201 private CsarUtils csarUtils;
204 private LifecycleBusinessLogic lifecycleBusinessLogic;
207 private IUserBusinessLogic userBusinessLogic;
210 private NodeTemplateOperation nodeTemplateOperation;
213 private ArtifactsResolver artifactsResolver;
215 public enum ArtifactOperationEnum {
216 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
218 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
219 return operation == CREATE || operation == LINK;
223 public class ArtifactOperationInfo {
225 private ArtifactOperationEnum artifactOperationEnum;
226 private boolean isExternalApi;
227 private boolean ignoreLifecycleState;
229 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
230 this.artifactOperationEnum = artifactOperationEnum;
231 this.isExternalApi = isExternalApi;
232 this.ignoreLifecycleState = ignoreLifecycleState;
235 public boolean isExternalApi() {
236 return isExternalApi;
239 public boolean ignoreLifecycleState() {
240 return ignoreLifecycleState;
243 public ArtifactOperationEnum getArtifactOperationEnum() {
244 return artifactOperationEnum;
250 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
251 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
252 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
255 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
256 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
258 // step 1 - detect auditing type
259 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
260 // step 2 - check header
261 if (userId == null) {
262 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
263 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
264 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
265 return Either.right(responseFormat);
267 // step 3 - check user existence
268 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
269 if (userResult.isRight()) {
270 return Either.right(userResult.right().value());
273 // step 4 - check user's role
274 User user = userResult.left().value();
275 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
276 if (validateUserRole.isRight()) {
277 return Either.right(validateUserRole.right().value());
281 // 5. check service/resource existence
282 // 6. check service/resource check out
283 // 7. user is owner of checkout state
284 org.openecomp.sdc.be.model.Component component = null;
285 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
286 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
287 if (validateComponent.isRight()) {
288 return Either.right(validateComponent.right().value());
290 component = validateComponent.left().value();
291 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
292 if (validateWorkOnResource.isRight()) {
293 return Either.right(validateWorkOnResource.right().value());
297 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
298 shouldLock, inTransaction, true);
302 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
303 * For regular usage use <br>
304 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
308 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
309 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
310 Component parent = component;
311 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
313 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
314 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
316 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
317 if (errorWrapper.isEmpty()) {
319 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
322 result = Either.right(errorWrapper.getInnerElement());
327 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
328 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
329 ArtifactDefinition validatedArtifactInfo = artifactInfo;
330 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
331 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
332 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
333 if (validateArtifact.isRight()) {
334 ResponseFormat responseFormat = validateArtifact.right().value();
335 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
336 errorWrapper.setInnerElement(validateArtifact.right().value());
338 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
339 validatedArtifactInfo = validateArtifact.left().value();
340 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
343 return validatedArtifactInfo;
346 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
347 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
348 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
350 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
351 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
352 ComponentInstance componentInstance = component.getComponentInstances()
354 .filter(p -> p.getUniqueId().equals(componentId))
357 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
359 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
361 .filter(p -> p.getUniqueId()
362 .equals(validatedArtifact.getUniqueId()))
365 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
366 .getName(), user, componentId, shouldLock, inTransaction);
367 if (eitherGenerated.isRight()) {
368 errorWrapper.setInnerElement(eitherGenerated.right().value());
373 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
374 boolean needGenerate;
375 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
376 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
377 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
378 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
379 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
383 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
384 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
386 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
389 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
390 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
392 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
393 if (generated.isRight()) {
396 byte[] decodedPayload = artifactDefinition.getPayloadData();
397 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
398 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
399 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
400 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
401 shouldLock, inTransaction);
405 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
406 log.debug("tosca artifact generation");
407 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
408 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
410 if (generated.isRight()) {
411 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
414 return Either.right(generated.right().value());
416 byte[] value = generated.left().value();
417 artifactInfo.setPayload(value);
421 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
422 if (exportComponent.isRight()) {
423 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
425 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
426 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
427 return Either.right(responseFormat);
429 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
430 String payload = exportComponent.left().value().getMainYaml();
431 artifactInfo.setPayloadData(payload);
433 return Either.left(Either.left(artifactInfo));
436 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
437 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
438 switch (operation.getArtifactOperationEnum()) {
440 if (artifactGenerationRequired(parent, artifactInfo)) {
441 return generateNotSavedArtifact(parent, artifactInfo);
443 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
445 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
447 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
448 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
449 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
450 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
451 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
452 if (needUpdateGroup && result.isLeft()) {
453 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
454 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
455 .value(), parent, componentType, componentId);
456 if (error != ActionStatus.OK) {
457 result = Either.right(componentsUtils.getResponseFormat(error));
462 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
463 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
466 if (result == null) {
467 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
468 if (needUpdateGroup && result.isLeft()) {
469 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
471 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
472 .value(), parent, componentType);
473 if (error != ActionStatus.OK) {
474 result = Either.right(componentsUtils.getResponseFormat(error));
480 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
482 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
487 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
488 List<GroupDefinition> groups = parent.getGroups();
489 if (groups != null && !groups.isEmpty()) {
490 List<GroupDataDefinition> groupToUpdate = groups.stream()
491 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
492 .contains(artifactInfo
494 .collect(Collectors.toList());
495 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
496 groupToUpdate.forEach(g -> {
497 g.getArtifacts().remove(artifactInfo.getUniqueId());
498 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
499 g.getArtifacts().add(artAfterUpdate.getUniqueId());
500 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
502 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
503 if (status.isRight()) {
504 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
505 return componentsUtils.convertFromStorageResponse(status.right().value());
509 return ActionStatus.OK;
512 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
513 List<GroupDefinition> groups = parent.getGroups();
514 if (groups != null && !groups.isEmpty()) {
515 List<GroupDataDefinition> groupToUpdate = groups.stream()
516 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
517 .contains(artifactInfoHeat
519 .collect(Collectors.toList());
520 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
521 groupToUpdate.forEach(g -> {
522 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
523 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
524 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
525 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
526 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
527 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
529 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
530 if (status.isRight()) {
531 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
532 return componentsUtils.convertFromStorageResponse(status.right().value());
536 return ActionStatus.OK;
539 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
540 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
541 List<GroupInstance> groupInstances = null;
542 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
544 .filter(ci -> ci.getUniqueId().equals(parentId))
546 if (componentInstOp.isPresent()) {
547 groupInstances = componentInstOp.get().getGroupInstances();
549 if (CollectionUtils.isNotEmpty(groupInstances)) {
550 boolean isUpdated = false;
551 for (GroupInstance groupInstance : groupInstances) {
553 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
554 .contains(artifactInfo
556 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
557 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
560 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
561 .contains(artifactInfo
562 .getArtifactUUID())) {
563 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
564 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
568 updatedGroupInstances.add(groupInstance);
572 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
573 if (status.isRight()) {
574 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
575 return componentsUtils.convertFromStorageResponse(status.right().value());
577 return ActionStatus.OK;
580 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
581 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
582 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
583 result = generateToscaArtifact(parent, artifactInfo, false, false);
586 String heatArtifactId = artifactInfo.getGeneratedFromId();
587 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
588 if (heatRes.isRight()) {
589 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
591 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
594 return Either.right(responseFormat);
596 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
597 artifactInfo.setPayloadData(generatedPayload);
598 result = Either.left(Either.left(artifactInfo));
603 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
604 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
605 convertParentType(componentType);
606 String parentId = parent.getUniqueId();
607 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
608 .getGeneratedFromId());
609 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
611 if (origMd5 != null) {
612 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
613 if (validateMd5.isRight()) {
614 ResponseFormat responseFormat = validateMd5.right().value();
615 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
616 return Either.right(responseFormat);
619 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
621 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
622 if (payloadEither.isRight()) {
623 ResponseFormat responseFormat = payloadEither.right().value();
624 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
625 return Either.right(responseFormat);
629 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
630 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
631 return Either.right(responseFormat);
637 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
638 if (lockComponent.isRight()) {
639 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
640 .value(), componentType, null);
641 return Either.right(lockComponent.right().value());
644 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
646 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
652 if (resultOp == null || resultOp.isRight()) {
654 if (!inTransaction) {
655 janusGraphDao.rollback();
660 if (!inTransaction) {
661 janusGraphDao.commit();
665 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
670 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
671 if (artifactGenerationRequired(component, csarArtifact)) {
672 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
674 if (generated.isRight()) {
675 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
678 return Either.right(generated.right().value());
680 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
683 return downloadArtifact(csarArtifact);
686 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
687 // perform all validation in common flow
688 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
689 null, parentId, containerComponentType);
690 if (result.isRight()) {
691 return Either.right(result.right().value());
693 ArtifactDefinition artifactDefinition;
694 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
695 if (insideValue.isLeft()) {
696 artifactDefinition = insideValue.left().value();
699 artifactDefinition = insideValue.right().value().getImplementationArtifact();
701 // for tosca artifacts and heat env on VF level generated on download without saving
702 if (artifactDefinition.getPayloadData() != null) {
703 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
706 return downloadArtifact(artifactDefinition);
709 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
711 // detect auditing type
712 Map<String, ArtifactDefinition> resMap = null;
713 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
718 if (userId == null) {
719 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
720 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
722 resultOp = Either.right(responseFormat);
726 // check user existence
730 validateUserExists(userId, "get artifacts", false);
732 // 5. check service/resource existence
733 // 6. check service/resource check out
734 // 7. user is owner of checkout state
735 org.openecomp.sdc.be.model.Component component = null;
736 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
737 ComponentParametersView componentFilter = new ComponentParametersView();
738 componentFilter.disableAll();
739 componentFilter.setIgnoreArtifacts(false);
740 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
741 componentFilter.setIgnoreComponentInstances(false);
744 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
745 .findByParamName(containerComponentType), componentFilter);
747 if (validateComponent.isRight()) {
748 resultOp = Either.right(validateComponent.right().value());
751 component = validateComponent.left().value();
752 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
753 if (lockComponent.isRight()) {
755 resultOp = Either.right(lockComponent.right().value());
760 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
762 if (groupType == null) {
763 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
764 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
766 resultOp = Either.right(responseFormat);
770 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
771 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
772 if (list != null && !list.isEmpty()) {
773 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
776 resMap = new HashMap<>();
778 resultOp = Either.left(resMap);
783 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
784 .getNodeType(), groupType, componentId);
785 if (artifactsMapStatus.isRight()) {
786 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
787 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
788 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
789 resultOp = Either.right(responseFormat);
792 resMap = new HashMap<>();
793 resultOp = Either.left(resMap);
797 resMap = artifactsMapStatus.left().value();
798 resultOp = Either.left(resMap);
805 if (resultOp == null || resultOp.isRight()) {
807 janusGraphDao.rollback();
811 janusGraphDao.commit();
814 componentType = component.getComponentType();
815 NodeTypeEnum nodeType = componentType.getNodeType();
816 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
821 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
823 // check artifact existence
824 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
826 if (artifactResult.isRight()) {
827 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
829 log.debug("addArtifact - artifact {} not found", artifactId);
830 return Either.right(responseFormat);
834 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
837 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
839 return Either.right(responseFormat);
843 // check artifact belong to component
844 boolean found = false;
845 switch (componentType) {
848 found = checkArtifactInComponent(component, artifactId);
850 case RESOURCE_INSTANCE:
851 found = checkArtifactInResourceInstance(component, componentId, artifactId);
857 String componentName = componentType.name().toLowerCase();
858 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
859 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
860 return Either.right(responseFormat);
862 return Either.left(artifactResult.left().value());
865 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
866 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
868 String artifactId = null;
871 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
872 if (payloadEither.isRight()) {
873 return Either.right(payloadEither.right().value());
875 byte[] decodedPayload = payloadEither.left().value();
876 convertParentType(componentType);
879 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
880 if (lockComponent.isRight()) {
881 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
882 .value(), componentType, null);
883 return Either.right(lockComponent.right().value());
886 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
889 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
894 unlockComponent(resultOp, parent, inTransaction);
901 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
902 Component parent, boolean shouldLock, boolean inTransaction) {
905 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
906 if (lockComponent.isRight()) {
907 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
908 .value(), componentType, null);
909 return Either.right(lockComponent.right().value());
912 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
915 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
920 unlockComponent(resultOp, parent, inTransaction);
927 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
928 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
930 convertParentType(componentType);
934 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
936 if (lockComponent.isRight()) {
937 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
938 .value(), componentType, null);
939 return Either.right(lockComponent.right().value());
943 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
945 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
951 unlockComponent(resultOp, parent, inTransaction);
956 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
957 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
959 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
961 if (payloadEither.isRight()) {
962 return Either.right(payloadEither.right().value());
964 byte[] decodedPayload = payloadEither.left().value();
966 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
969 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
970 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
972 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
973 if (validateMd5.isRight()) {
974 ResponseFormat responseFormat = validateMd5.right().value();
975 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
976 return Either.right(responseFormat);
980 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
981 if (validateResult.isRight()) {
982 ResponseFormat responseFormat = validateResult.right().value();
983 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
984 return Either.right(validateResult.right().value());
987 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
988 if (payloadEither.isRight()) {
989 ResponseFormat responseFormat = payloadEither.right().value();
990 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
991 log.debug("Error during handle payload");
992 return Either.right(responseFormat);
995 // validate heat parameters. this part must be after the parameters are
996 // extracted in "handlePayload"
997 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
999 if (validateAndConvertHeatParamers.isRight()) {
1000 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
1001 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
1002 log.debug("Error during handle payload");
1003 return Either.right(responseFormat);
1005 return payloadEither;
1008 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1009 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1011 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
1017 user.setUserId("UNKNOWN");
1019 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
1022 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1023 switch (componentTypeEnum) {
1025 Resource resource = (Resource) component;
1026 if (resource == null) {
1027 // In that case, component ID should be instead of name
1028 resource = new Resource();
1029 resource.setName(componentId);
1031 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1032 ResourceVersionInfo.newBuilder()
1033 .artifactUuid(prevArtifactUuid)
1034 .build(), currentArtifactUuid, artifactDefinition);
1038 Service service = (Service) component;
1039 if (service == null) {
1040 // In that case, component ID should be instead of name
1041 service = new Service();
1042 service.setName(componentId);
1044 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1045 ResourceVersionInfo.newBuilder()
1046 .artifactUuid(prevArtifactUuid)
1048 ResourceVersionInfo.newBuilder()
1049 .artifactUuid(currentArtifactUuid)
1051 null, artifactDefinition, null);
1054 case RESOURCE_INSTANCE:
1055 if (resourceInstanceName == null) {
1056 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1058 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1059 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1060 ResourceVersionInfo.newBuilder()
1061 .artifactUuid(prevArtifactUuid)
1063 ResourceVersionInfo.newBuilder()
1064 .artifactUuid(currentArtifactUuid)
1066 null, artifactDefinition, null);
1073 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1074 ComponentInstance resourceInstance = component.getComponentInstances()
1076 .filter(p -> p.getUniqueId().equals(componentId))
1079 String resourceInstanceName = null;
1080 if (resourceInstance != null) {
1081 resourceInstanceName = resourceInstance.getName();
1083 return resourceInstanceName;
1086 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1087 StringBuilder sb = new StringBuilder();
1088 if (artifactDefinition != null) {
1089 sb.append(artifactDefinition.getArtifactGroupType().getType())
1092 .append(artifactDefinition.getArtifactLabel())
1095 .append(artifactDefinition.getArtifactType())
1097 .append(artifactDefinition.getArtifactName())
1099 .append(artifactDefinition.getTimeout())
1101 .append(artifactDefinition.getEsId());
1104 if (artifactDefinition.getArtifactVersion() != null) {
1106 sb.append(artifactDefinition.getArtifactVersion());
1112 if (artifactDefinition.getArtifactUUID() != null) {
1113 sb.append(artifactDefinition.getArtifactUUID());
1119 return sb.toString();
1122 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1124 if (origMd5 != null) {
1125 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1126 if (!encodeBase64Str.equals(origMd5)) {
1127 log.debug("The calculated md5 is different then the received one");
1128 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1132 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1133 log.debug("Missing md5 header during artifact create");
1134 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1137 if (payload != null && payload.length != 0) {
1138 log.debug("Cannot have payload while md5 header is missing");
1139 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1142 return Either.left(true);
1145 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1146 ComponentTypeEnum componentType, Component parentComponent) {
1148 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1149 if (artifactById.isRight()) {
1150 return Either.right(artifactById.right().value());
1152 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1154 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1155 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1156 if (validateInformationalArtifactRes.isRight()) {
1157 return Either.right(validateInformationalArtifactRes.right().value());
1159 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1160 if (validateAndSetArtifactname.isRight()) {
1161 return Either.right(validateAndSetArtifactname.right().value());
1163 if (operationName != null && interfaceName != null) {
1164 operationName = operationName.toLowerCase();
1165 interfaceName = interfaceName.toLowerCase();
1167 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1168 if (logicalNameStatus.isRight()) {
1169 return Either.right(logicalNameStatus.right().value());
1171 // This is a patch to block possibility of updating service api fields
1172 // through other artifacts flow
1174 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1175 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1176 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1179 checkCreateFields(user, artifactInfo, artifactGroupType);
1182 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1183 if (currentArtifactInfo != null) {
1184 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1187 // artifactGroupType is not allowed to be updated
1188 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1189 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1190 if (validateGroupType.isRight()) {
1191 return Either.right(validateGroupType.right().value());
1194 NodeTypeEnum parentType = convertParentType(componentType);
1196 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1198 if (isDeploymentArtifact(artifactInfo)) {
1199 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1200 if (deploymentValidationResult.isRight()) {
1201 return Either.right(deploymentValidationResult.right().value());
1205 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1208 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1209 if (descriptionResult.isRight()) {
1210 return Either.right(descriptionResult.right().value());
1213 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1214 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1215 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1216 if (validateServiceApiType.isRight()) {
1217 return Either.right(validateServiceApiType.right().value());
1219 // Change of type is not allowed and should be ignored
1221 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1223 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1224 if (validateUrl.isRight()) {
1225 return Either.right(validateUrl.right().value());
1228 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1229 if (validateUpdate.isRight()) {
1230 log.debug("serviceApi first update cnnot be without payload.");
1231 return Either.right(validateUpdate.right().value());
1235 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1236 if (validateArtifactType.isRight()) {
1237 return Either.right(validateArtifactType.right().value());
1239 if (artifactInfo.getApiUrl() != null) {
1240 artifactInfo.setApiUrl(null);
1241 log.error("Artifact URL cannot be set through this API - ignoring");
1244 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1245 artifactInfo.setServiceApi(false);
1246 log.error("Artifact service API flag cannot be changed - ignoring");
1250 return Either.left(artifactInfo);
1253 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1254 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1255 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1256 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1257 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1261 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1263 Either<ArtifactDefinition, ResponseFormat> result = null;
1264 ArtifactDefinition foundArtifact = null;
1265 if (StringUtils.isNotEmpty(artifactId)) {
1266 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1268 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1269 log.debug("Artifact {} already exist", artifactId);
1270 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1272 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1273 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1274 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1276 if (result == null) {
1277 result = Either.left(foundArtifact);
1282 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1283 ArtifactDefinition foundArtifact;
1284 if (parentComponent.getUniqueId().equals(parentId)) {
1285 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1288 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1289 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1291 return foundArtifact;
1294 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1295 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1296 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1297 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1298 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1299 if (artifactType == null) {
1300 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1301 .getArtifactType()));
1303 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1304 String artifactTypeName = artifactType.getType();
1305 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1306 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1308 .getResourceInformationalArtifacts();
1309 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1310 if (!validArtifactTypes.contains(artifactTypeName)) {
1311 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1314 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1315 .getValidForResourceTypes();
1316 if (!validResourceType.contains(parentResourceType.name())) {
1317 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1321 return validationResult;
1324 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1325 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1326 return NodeTypeEnum.Resource;
1328 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1329 return NodeTypeEnum.ResourceInstance;
1332 return NodeTypeEnum.Service;
1336 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1337 boolean shouldLock, boolean inTransaction) {
1339 NodeTypeEnum parentType = convertParentType(componentType);
1340 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1341 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1342 ArtifactDefinition foundArtifact = null;
1343 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1344 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1345 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1346 boolean isDuplicated = false;
1348 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1351 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1352 if (lockComponent.isRight()) {
1353 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1354 .value(), componentType, null);
1355 resultOp = Either.right(lockComponent.right().value());
1358 if (resultOp == null) {
1359 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1360 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1361 if (getContainerRes.isRight()) {
1362 log.debug("Failed to fetch the container component {}. ", parentId);
1363 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1365 .value()), artifactId);
1366 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1367 resultOp = Either.right(responseFormat);
1370 if (resultOp == null) {
1371 fetchedContainerComponent = getContainerRes.left().value();
1372 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1373 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1374 if (getArtifactRes.isRight()) {
1375 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1377 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1378 .value(), artifactId);
1379 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1380 resultOp = Either.right(responseFormat);
1383 foundArtifact = getArtifactRes.left().value().getLeft();
1384 esId = foundArtifact.getEsId();
1387 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1388 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1389 .getComponentType()));
1390 if (needCloneRes.isRight()) {
1391 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1392 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1394 .value()), foundArtifact.getArtifactDisplayName());
1395 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1396 resultOp = Either.right(responseFormat);
1399 boolean isNeedToDeleteArtifactFromDB = true;
1400 if (resultOp == null) {
1402 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1403 String instanceId = parentId;
1404 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1406 if (isOnlyResourceInstanceArtifact.isRight()) {
1407 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1408 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1409 .value(), foundArtifact
1410 .getArtifactDisplayName());
1411 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1412 return Either.right(responseFormat);
1414 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1417 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1420 if (updatedArtifactRes.isRight()) {
1421 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1422 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1424 .value()), foundArtifact.getArtifactDisplayName());
1425 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1426 resultOp = Either.right(responseFormat);
1429 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1433 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1434 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1435 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1436 if (cassandraStatus != CassandraOperationStatus.OK) {
1437 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1438 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1439 .getArtifactDisplayName());
1440 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1441 resultOp = Either.right(responseFormat);
1444 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1446 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1450 .getGroupInstances());
1451 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1452 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1453 if (status.isRight()) {
1454 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1455 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1457 .value()), foundArtifact.getArtifactDisplayName());
1458 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1459 resultOp = Either.right(responseFormat);
1463 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1464 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1465 if (status != StorageOperationStatus.OK) {
1466 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1467 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1468 .getArtifactDisplayName());
1469 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1470 resultOp = Either.right(responseFormat);
1473 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1474 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1476 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1477 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1478 if (status.isRight()) {
1479 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1480 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1482 .value()), foundArtifact.getArtifactDisplayName());
1483 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1484 resultOp = Either.right(responseFormat);
1488 if (resultOp == null) {
1489 resultOp = Either.left(Either.left(foundArtifact));
1490 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1496 unlockComponent(resultOp, parent, inTransaction);
1501 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1502 Either<Boolean, ActionStatus> result = Either.left(true);
1503 ComponentInstance foundInstance = null;
1504 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1506 .filter(i -> i.getUniqueId().equals(instanceId))
1508 if (!componentInstanceOpt.isPresent()) {
1509 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1512 foundInstance = componentInstanceOpt.get();
1513 String componentUid = foundInstance.getComponentUid();
1514 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1515 if (getContainerRes.isRight()) {
1516 log.debug("Failed to fetch the container component {}. ", componentUid);
1517 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1519 Component origComponent = getContainerRes.left().value();
1520 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1521 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1522 Optional<String> op = deploymentArtifacts.keySet()
1524 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1526 if (op.isPresent()) {
1527 return Either.left(false);
1530 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1531 if (artifacts != null && !artifacts.isEmpty()) {
1532 Optional<String> op = artifacts.keySet()
1534 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1536 if (op.isPresent()) {
1537 return Either.left(false);
1545 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1546 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1547 boolean isUpdated = false;
1548 if (groups != null) {
1549 for (GroupDefinition group : groups) {
1551 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1552 group.getArtifacts().remove(artifactId);
1555 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1556 .contains(foundArtifact.getArtifactUUID())) {
1557 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1561 updatedGroups.add(group);
1565 return updatedGroups;
1568 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1569 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1570 if (CollectionUtils.isNotEmpty(groupInstances)) {
1571 boolean isUpdated = false;
1572 for (GroupInstance groupInstance : groupInstances) {
1574 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1575 .contains(artifactId)) {
1576 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1579 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1580 .contains(foundArtifact
1581 .getArtifactUUID())) {
1582 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1586 updatedGroupInstances.add(groupInstance);
1590 return updatedGroupInstances;
1593 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1595 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1596 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1597 String componentId = component.getUniqueId();
1598 String instanceId = componentId.equals(parentId) ? null : parentId;
1600 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1601 resetMandatoryArtifactFields(foundArtifact);
1602 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1604 else if (cloneIsNeeded) {
1605 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1606 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1609 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1610 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1615 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1617 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1618 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1619 ComponentInstance foundInstance = null;
1620 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1621 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1623 .filter(i -> i.getUniqueId()
1626 if (!componentInstanceOpt.isPresent()) {
1627 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1630 foundInstance = componentInstanceOpt.get();
1631 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1635 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1637 if (result == null) {
1638 if (artifacts.containsKey(artifactId)) {
1639 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1642 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1648 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1649 Map<String, ArtifactDefinition> currArtifacts;
1650 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1651 currArtifacts = component.getDeploymentArtifacts()
1654 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1655 if (MapUtils.isNotEmpty(currArtifacts)) {
1656 artifacts.putAll(currArtifacts);
1659 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1660 currArtifacts = component.getArtifacts()
1663 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1664 if (MapUtils.isNotEmpty(currArtifacts)) {
1665 artifacts.putAll(currArtifacts);
1668 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1669 currArtifacts = component.getToscaArtifacts()
1672 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1673 if (MapUtils.isNotEmpty(currArtifacts)) {
1674 artifacts.putAll(currArtifacts);
1679 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1680 Map<String, ArtifactDefinition> currArtifacts;
1681 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1682 currArtifacts = instance.getDeploymentArtifacts()
1685 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1686 if (MapUtils.isNotEmpty(currArtifacts)) {
1687 artifacts.putAll(currArtifacts);
1690 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1691 currArtifacts = instance.getArtifacts()
1694 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1695 if (MapUtils.isNotEmpty(currArtifacts)) {
1696 artifacts.putAll(currArtifacts);
1701 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1702 if (fetchedArtifact != null) {
1703 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1704 fetchedArtifact.setEsId(null);
1705 fetchedArtifact.setArtifactName(null);
1706 fetchedArtifact.setDescription(null);
1707 fetchedArtifact.setApiUrl(null);
1708 fetchedArtifact.setArtifactChecksum(null);
1709 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1710 fetchedArtifact.setArtifactUUID(null);
1711 long time = System.currentTimeMillis();
1712 fetchedArtifact.setPayloadUpdateDate(time);
1713 fetchedArtifact.setHeatParameters(null);
1714 fetchedArtifact.setHeatParamsUpdateDate(null);
1718 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1719 StorageOperationStatus error = StorageOperationStatus.OK;
1720 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1721 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1722 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1727 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1729 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1731 if (artifactById.isRight()) {
1732 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1733 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1734 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1735 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1736 return Either.right(responseFormat);
1738 ArtifactDefinition artifactDefinition = artifactById.left().value();
1739 if (artifactDefinition == null) {
1740 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1741 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1742 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1743 return Either.right(responseFormat);
1746 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1747 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1748 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1749 return Either.left(insideEither);
1752 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1753 ComponentTypeEnum componentType) {
1755 String artifactLabel = artifactInfo.getArtifactLabel();
1756 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1758 BeEcompErrorManager.getInstance()
1759 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1760 log.debug("missing artifact logical name for component {}", componentId);
1761 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1763 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1765 if (operationName != null) {
1766 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1767 log.debug("artifact label cannot be set {}", artifactLabel);
1768 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1771 artifactLabel = operationName;
1774 String displayName = artifactInfo.getArtifactDisplayName();
1775 if (displayName == null || displayName.isEmpty()) {
1776 displayName = artifactLabel;
1778 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1779 artifactInfo.setArtifactDisplayName(displayName);
1781 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1782 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1783 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1785 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1787 if (artifactLabel.isEmpty()) {
1788 log.debug("missing normalized artifact logical name for component {}", componentId);
1789 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1792 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1793 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1794 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1795 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1797 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1798 log.debug("Non unique Artifact label : {}", artifactLabel);
1799 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1802 artifactInfo.setArtifactLabel(artifactLabel);
1804 return Either.left(ActionStatus.OK);
1807 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1808 boolean isUnique = true;
1809 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1810 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1811 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1814 artifacts = artifactToscaOperation.getArtifacts(componentId);
1817 if (artifacts.isLeft()) {
1818 for (String label : artifacts.left().value().keySet()) {
1819 if (label.equals(artifactLabel)) {
1825 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1826 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1827 .getAllInterfacesOfResource(componentId, true, true);
1828 if (allInterfacesOfResource.isLeft()) {
1829 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1830 for (Operation operation : interace.getOperationsMap().values()) {
1831 if (operation.getImplementation() != null && operation.getImplementation()
1833 .equals(artifactLabel)) {
1844 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1845 ComponentTypeEnum componentType) {
1846 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1847 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1848 String artifactName = artifactInfo.getArtifactName();
1849 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1850 if (artifacts.left().value().values().stream()
1851 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1852 //check whether it is the same artifact we hold (by label)
1853 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1857 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1858 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1863 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1864 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1865 .getAllInterfacesOfResource(componentId, true, true);
1867 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1868 return !allInterfacesOfResource.left().value()
1870 .stream().map(InterfaceDefinition :: getOperationsMap)
1871 .flatMap(map -> map.values().stream())
1872 .map(OperationDataDefinition::getImplementation)
1873 .filter(Objects::nonNull)
1874 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1875 && !artifactLabel.equals(add.getArtifactLabel()));
1880 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1881 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1882 .getAllInterfacesOfResource(componentId, true, true);
1884 if (allInterfacesOfResource.isLeft()){
1885 return !allInterfacesOfResource.left().value()
1887 .stream().map(InterfaceDefinition :: getOperationsMap)
1888 .flatMap(map -> map.values().stream())
1889 .map(OperationDataDefinition::getImplementation)
1890 .filter(Objects::nonNull)
1891 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1896 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1897 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1898 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1899 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1900 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1903 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1905 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1906 log.debug("failed to retrieve artifacts for {} ", componentId);
1907 return Either.right(artifactsResponse.right().value());
1909 return Either.left(artifactsResponse.left().value().entrySet()
1911 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1912 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1915 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1916 return artifacts.entrySet()
1918 .map(x -> x.getValue().getArtifactName())
1919 .collect(Collectors.toList());
1922 // ***************************************************************
1924 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1925 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1926 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1927 Either<ArtifactDefinition, Operation> insideEither = null;
1928 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1929 String instanceId = null;
1930 String instanceName = null;
1931 if (foundInstance != null) {
1932 instanceId = foundInstance.getUniqueId();
1933 instanceName = foundInstance.getName();
1935 boolean isLeft = false;
1936 String artifactUniqueId = null;
1937 StorageOperationStatus error = null;
1938 // information/deployment/api aritfacts
1939 log.trace("Try to create entry on graph");
1940 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1941 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1942 .getUniqueId(), nodeType, true, instanceId);
1944 isLeft = result.isLeft();
1946 artifactUniqueId = result.left().value().getUniqueId();
1947 result.left().value();
1949 insideEither = Either.left(result.left().value());
1950 resultOp = Either.left(insideEither);
1952 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1953 if (error != StorageOperationStatus.OK) {
1959 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1960 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1964 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1965 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1966 .getArtifactDisplayName());
1967 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1968 resultOp = Either.right(responseFormat);
1974 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1975 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1977 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1978 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1979 Either<ArtifactDefinition, Operation> insideEither = null;
1980 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1981 String instanceId = null;
1982 String instanceName = null;
1983 if (foundInstance != null) {
1984 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1985 log.debug("Failed to create artifact, already exists");
1986 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1987 .getArtifactLabel());
1988 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1990 resultOp = Either.right(responseFormat);
1994 instanceId = foundInstance.getUniqueId();
1995 instanceName = foundInstance.getName();
1997 if (artifactData == null) {
1998 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1999 log.debug("Failed to create artifact object for ES.");
2000 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2001 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
2002 resultOp = Either.right(responseFormat);
2006 // set on graph object id of artifact in ES!
2007 artifactInfo.setEsId(artifactData.getId());
2009 boolean isLeft = false;
2010 String artifactUniqueId = null;
2011 StorageOperationStatus error = null;
2012 if (interfaceType != null && operationName != null) {
2013 // lifecycle artifact
2014 Operation operation = convertToOperation(artifactInfo, operationName);
2016 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2018 isLeft = result.isLeft();
2020 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
2021 result.left().value().getImplementation();
2023 insideEither = Either.right(result.left().value());
2024 resultOp = Either.left(insideEither);
2027 error = result.right().value();
2031 // information/deployment/api aritfacts
2032 log.trace("Try to create entry on graph");
2033 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2034 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2035 .getUniqueId(), nodeType, true, instanceId);
2037 isLeft = result.isLeft();
2039 artifactUniqueId = result.left().value().getUniqueId();
2040 artifactData.setId(result.left().value().getEsId());
2041 insideEither = Either.left(result.left().value());
2042 resultOp = Either.left(insideEither);
2044 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2045 if (error != StorageOperationStatus.OK) {
2051 error = result.right().value();
2055 boolean res = saveArtifacts(artifactData, parentId);
2058 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2060 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2061 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2065 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2066 log.debug(FAILED_SAVE_ARTIFACT);
2067 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2068 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2070 resultOp = Either.right(responseFormat);
2075 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2076 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2077 .getArtifactDisplayName());
2078 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2079 resultOp = Either.right(responseFormat);
2085 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2086 ComponentInstance foundInstance = null;
2087 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2088 foundInstance = containerComponent.getComponentInstances()
2090 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2094 return foundInstance;
2097 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2099 Either<Boolean, ResponseFormat> result = Either.left(true);
2100 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2102 validateArtifactTypeExists(responseWrapper, artifactInfo);
2104 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2106 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2108 if (responseWrapper.isEmpty()) {
2109 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2112 // Common code for all types
2113 // not allowed to change artifactType
2114 if (responseWrapper.isEmpty() && !isCreate) {
2115 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2116 if (validateServiceApiType.isRight()) {
2117 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2120 if (responseWrapper.isEmpty()) {
2121 if (parentType.equals(NodeTypeEnum.Resource)) {
2122 Resource resource = (Resource) parentComponent;
2123 ResourceTypeEnum resourceType = resource.getResourceType();
2124 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2125 if (config == null) {
2126 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2127 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2128 .getArtifactType()));
2131 List<String> myList = config.getValidForResourceTypes();
2132 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2133 if (either.isRight()) {
2134 responseWrapper.setInnerElement(either.right().value());
2139 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2142 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2143 String artifactName = artifactInfo.getArtifactName();
2144 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2145 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2149 if (responseWrapper.isEmpty()) {
2150 switch (artifactType) {
2154 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2157 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2158 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2160 case DCAE_INVENTORY_TOSCA:
2161 case DCAE_INVENTORY_JSON:
2162 case DCAE_INVENTORY_POLICY:
2163 // Validation is done in handle payload.
2164 case DCAE_INVENTORY_DOC:
2165 case DCAE_INVENTORY_BLUEPRINT:
2166 case DCAE_INVENTORY_EVENT:
2167 // No specific validation
2169 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2175 if (!responseWrapper.isEmpty()) {
2176 result = Either.right(responseWrapper.getInnerElement());
2181 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2182 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2183 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2184 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2185 .getArtifactType());
2186 responseWrapper.setInnerElement(responseFormat);
2187 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2191 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2192 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2193 if (parentType.equals(NodeTypeEnum.Resource)) {
2194 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2196 .getResourceDeploymentArtifacts();
2198 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2199 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2201 .getResourceInstanceDeploymentArtifacts();
2204 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2206 .getServiceDeploymentArtifacts();
2208 return resourceDeploymentArtifacts;
2211 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2212 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2213 if (artifactType == null) {
2214 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2215 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2216 .getArtifactType());
2217 responseWrapper.setInnerElement(responseFormat);
2218 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2222 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2223 ArtifactTypeConfig retConfig = null;
2224 String fileType = artifactType.getType();
2225 if (parentType.equals(NodeTypeEnum.Resource)) {
2226 retConfig = ConfigurationManager.getConfigurationManager()
2228 .getResourceDeploymentArtifacts()
2231 else if (parentType.equals(NodeTypeEnum.Service)) {
2232 retConfig = ConfigurationManager.getConfigurationManager()
2234 .getServiceDeploymentArtifacts()
2237 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2238 retConfig = ConfigurationManager.getConfigurationManager()
2240 .getResourceInstanceDeploymentArtifacts()
2246 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2247 // extract heat parameters
2248 if (artifactInfo.getPayloadData() != null) {
2249 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2250 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2251 .getArtifactType());
2252 if (heatParameters.isRight() && (!heatParameters.right()
2254 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2255 log.info("failed to parse heat parameters ");
2256 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2257 .getArtifactType());
2258 return Either.right(responseFormat);
2260 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2261 artifactInfo.setListHeatParameters(heatParameters.left().value());
2264 return Either.left(true);
2269 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2270 String fileType = artifactType.getType();
2271 List<String> acceptedTypes = null;
2272 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2273 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2274 log.debug("parent type of artifact can be either resource or service");
2275 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2279 if (deploymentAcceptedTypes == null) {
2280 log.debug("parent type of artifact can be either resource or service");
2281 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2282 .getArtifactType()));
2286 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2289 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2292 String artifactName = artifactInfo.getArtifactName();
2293 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2294 // Pavel - File extension validation is case-insensitive - Ella,
2296 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2297 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2298 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2303 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2305 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2306 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2307 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2309 if (errorWrapper.isEmpty()) {
2310 validateValidYaml(errorWrapper, artifactInfo);
2313 if (errorWrapper.isEmpty()) {
2314 // Validate Heat Exist
2315 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2316 .getComponentType());
2319 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2320 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2323 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2324 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2328 Either<Boolean, ResponseFormat> eitherResponse;
2329 if (errorWrapper.isEmpty()) {
2330 eitherResponse = Either.left(true);
2333 eitherResponse = Either.right(errorWrapper.getInnerElement());
2335 return eitherResponse;
2338 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2339 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2340 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2341 if (fillArtifactPayload.isRight()) {
2342 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2343 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2347 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2351 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2352 Either<Boolean, ResponseFormat> result = Either.left(true);
2353 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2355 if (eitherArtifactData.isLeft()) {
2356 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2357 data = Base64.encodeBase64(data);
2358 payloadWrapper.setInnerElement(data);
2361 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2364 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2365 result = Either.right(responseFormat);
2371 @SuppressWarnings("unchecked")
2372 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2373 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2374 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2375 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2376 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2378 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2379 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2380 if (eitherHeatEnvProperties.isRight()) {
2381 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2382 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2383 errorWrapper.setInnerElement(responseFormat);
2384 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2386 else if (eitherHeatProperties.isRight()) {
2387 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2388 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2389 .getArtifactName(), heatArtifact.getArtifactName());
2390 errorWrapper.setInnerElement(responseFormat);
2391 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2392 .getArtifactName());
2395 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2396 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2397 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2398 if (!heatEnvPropertiesKeys.isEmpty()) {
2399 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2400 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2401 .getArtifactName(), heatArtifact.getArtifactName());
2402 errorWrapper.setInnerElement(responseFormat);
2407 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2408 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2409 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2411 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2412 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2413 .getArtifactType());
2414 errorWrapper.setInnerElement(responseFormat);
2415 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2419 private boolean isValidXml(byte[] xmlToParse) {
2420 boolean isXmlValid = true;
2422 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2423 setFeatures(reader);
2424 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2426 catch (ParserConfigurationException | IOException | SAXException e) {
2427 log.debug("Xml is invalid : {}", e.getMessage(), e);
2433 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2435 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2436 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2438 catch (SAXNotRecognizedException e) {
2439 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2443 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2444 boolean artifactNameFound = false;
2445 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2448 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2449 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2451 if (artifactNameFound) {
2452 String parentName = parentComponent.getName();
2453 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2454 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2455 .name(), parentName, artifactName);
2457 errorWrapper.setInnerElement(responseFormat);
2458 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2463 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2464 ComponentTypeEnum componentType) {
2465 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2466 if (res.isRight()) {
2467 ResponseFormat responseFormat;
2468 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2469 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2472 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2474 errorWrapper.setInnerElement(responseFormat);
2477 ArtifactDefinition heatArtifact = res.left().value();
2478 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2481 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2482 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2483 // timeout > 0 for HEAT artifacts
2484 Integer timeout = artifactInfo.getTimeout();
2485 if (timeout == null) {
2486 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2487 artifactInfo.setTimeout(defaultTimeout);
2488 // HEAT artifact but timeout is invalid
2490 else if (timeout < 1) {
2491 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2494 // US649856 - Allow several HEAT files on Resource
2495 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2496 return Either.left(true);
2499 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2500 String listToString = (typeList != null) ? typeList.toString() : "";
2501 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2502 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2503 .getArtifactName(), listToString, resourceType.getValue());
2504 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2505 String resourceTypeName = resourceType.name();
2506 if (typeList != null && typeList.contains(resourceTypeName)) {
2507 either = Either.left(true);
2512 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2513 if (artifactInfo.getHeatParameters() != null) {
2514 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2515 String parameterType = heatParam.getType();
2516 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2517 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2518 if (heatParameterType == null) {
2519 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2521 return Either.right(responseFormat);
2524 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2525 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2526 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2527 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2528 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2529 .getType(), heatParam.getName());
2530 return Either.right(responseFormat);
2534 return Either.left(artifactInfo);
2537 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2538 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2539 if (parentComponent.getDeploymentArtifacts() != null) {
2540 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2541 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2542 if (getRI.isRight()) {
2543 return deploymentArtifacts;
2545 ComponentInstance ri = getRI.left().value();
2546 if (ri.getDeploymentArtifacts() != null) {
2547 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2550 else if (parentComponent.getDeploymentArtifacts() != null) {
2551 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2554 return deploymentArtifacts;
2557 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2558 // on create if null add informational to current
2559 if (artifactInfo.getArtifactGroupType() == null) {
2560 artifactInfo.setArtifactGroupType(type);
2562 if (artifactInfo.getUniqueId() != null) {
2563 log.error("artifact uniqid cannot be set ignoring");
2565 artifactInfo.setUniqueId(null);
2567 if (artifactInfo.getArtifactRef() != null) {
2568 log.error("artifact ref cannot be set ignoring");
2570 artifactInfo.setArtifactRef(null);
2572 if (artifactInfo.getArtifactRepository() != null) {
2573 log.error("artifact repository cannot be set ignoring");
2575 artifactInfo.setArtifactRepository(null);
2577 if (artifactInfo.getUserIdCreator() != null) {
2578 log.error("creator uuid cannot be set ignoring");
2580 artifactInfo.setArtifactCreator(user.getUserId());
2582 if (artifactInfo.getUserIdLastUpdater() != null) {
2583 log.error("userId of last updater cannot be set ignoring");
2585 artifactInfo.setUserIdLastUpdater(user.getUserId());
2587 if (artifactInfo.getCreatorFullName() != null) {
2588 log.error("creator Full name cannot be set ignoring");
2590 String fullName = user.getFirstName() + " " + user.getLastName();
2591 artifactInfo.setUpdaterFullName(fullName);
2593 if (artifactInfo.getUpdaterFullName() != null) {
2594 log.error("updater Full name cannot be set ignoring");
2596 artifactInfo.setUpdaterFullName(fullName);
2598 if (artifactInfo.getCreationDate() != null) {
2599 log.error("Creation Date cannot be set ignoring");
2601 long time = System.currentTimeMillis();
2602 artifactInfo.setCreationDate(time);
2604 if (artifactInfo.getLastUpdateDate() != null) {
2605 log.error("Last Update Date cannot be set ignoring");
2607 artifactInfo.setLastUpdateDate(time);
2609 if (artifactInfo.getEsId() != null) {
2610 log.error("es id cannot be set ignoring");
2612 artifactInfo.setEsId(null);
2617 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2618 String id = artifactId;
2619 if (artifactId == null || artifactId.isEmpty()) {
2620 String uniqueId = null;
2621 if (interfaceName != null && operationName != null) {
2622 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2623 .getArtifactLabel());
2626 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2628 artifactInfo.setUniqueId(uniqueId);
2629 artifactInfo.setEsId(uniqueId);
2633 artifactInfo.setUniqueId(artifactId);
2634 artifactInfo.setEsId(artifactId);
2639 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2640 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2641 BeEcompErrorManager.getInstance()
2642 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2643 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2644 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2647 boolean artifactTypeExist = false;
2648 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2649 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2651 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2652 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2656 allArtifactTypes = elementOperation.getAllArtifactTypes();
2658 if (allArtifactTypes.isRight()) {
2659 BeEcompErrorManager.getInstance()
2660 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2664 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2666 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2669 for (ArtifactType type : allArtifactTypes.left().value()) {
2670 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2671 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2672 artifactTypeExist = true;
2677 if (!artifactTypeExist) {
2678 BeEcompErrorManager.getInstance()
2679 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2680 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2681 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2682 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2683 .getArtifactType()));
2686 return Either.left(ActionStatus.OK);
2689 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2691 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2692 List<ArtifactType> artifactTypes = new ArrayList<>();
2694 if (parentType.equals(NodeTypeEnum.Service)) {
2695 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2697 .getServiceDeploymentArtifacts();
2699 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2700 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2702 .getResourceInstanceDeploymentArtifacts();
2705 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2707 .getResourceDeploymentArtifacts();
2709 if (deploymentArtifacts != null) {
2710 for (String artifactType : deploymentArtifacts.keySet()) {
2711 ArtifactType artifactT = new ArtifactType();
2712 artifactT.setName(artifactType);
2713 artifactTypes.add(artifactT);
2715 return Either.left(artifactTypes);
2718 return Either.right(ActionStatus.GENERAL_ERROR);
2723 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2724 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2725 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2727 return Either.left(true);
2731 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2732 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2733 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2736 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2737 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2738 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2740 artifactInfo.setArtifactName(normalizeFileName);
2742 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2743 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2746 return Either.left(true);
2749 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2750 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2751 log.info("artifact type is missing operation ignored");
2752 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2755 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2756 log.info("artifact type cannot be changed operation ignored");
2757 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2759 return Either.left(true);
2762 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2763 if (artifactInfo.getArtifactGroupType() == null) {
2764 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2767 else if (!currentArtifact.getArtifactGroupType()
2769 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2770 log.info("artifact group type cannot be changed. operation failed");
2771 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2773 return Either.left(artifactInfo);
2776 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2778 // on update if null add informational to current
2779 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2780 currentArtifact.setArtifactGroupType(type);
2783 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2784 log.error("artifact uniqid cannot be set ignoring");
2786 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2788 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2789 .equals(artifactInfo.getArtifactRef())) {
2790 log.error("artifact ref cannot be set ignoring");
2792 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2794 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2795 .equals(artifactInfo.getArtifactRepository())) {
2796 log.error("artifact repository cannot be set ignoring");
2798 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2800 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2801 .equals(artifactInfo.getUserIdCreator())) {
2802 log.error("creator uuid cannot be set ignoring");
2804 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2806 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2807 .equals(artifactInfo.getArtifactCreator())) {
2808 log.error("artifact creator cannot be set ignoring");
2810 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2812 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2813 .equals(artifactInfo.getUserIdLastUpdater())) {
2814 log.error("userId of last updater cannot be set ignoring");
2816 artifactInfo.setUserIdLastUpdater(user.getUserId());
2818 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2819 .equals(artifactInfo.getCreatorFullName())) {
2820 log.error("creator Full name cannot be set ignoring");
2822 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2824 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2825 .equals(artifactInfo.getUpdaterFullName())) {
2826 log.error("updater Full name cannot be set ignoring");
2828 String fullName = user.getFirstName() + " " + user.getLastName();
2829 artifactInfo.setUpdaterFullName(fullName);
2831 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2832 .equals(artifactInfo.getCreationDate())) {
2833 log.error("Creation Date cannot be set ignoring");
2835 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2837 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2838 .equals(artifactInfo.getLastUpdateDate())) {
2839 log.error("Last Update Date cannot be set ignoring");
2841 long time = System.currentTimeMillis();
2842 artifactInfo.setLastUpdateDate(time);
2844 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2845 log.error("es id cannot be set ignoring");
2847 artifactInfo.setEsId(currentArtifact.getUniqueId());
2849 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2850 .equals(artifactInfo.getArtifactDisplayName())) {
2851 log.error(" Artifact Display Name cannot be set ignoring");
2853 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2855 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2856 .equals(artifactInfo.getServiceApi())) {
2857 log.debug("serviceApi cannot be set. ignoring.");
2859 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2861 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2862 .equals(artifactInfo.getArtifactGroupType())) {
2863 log.debug("artifact group cannot be set. ignoring.");
2865 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2867 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2869 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2870 .isEmpty() && !currentArtifact.getArtifactUUID()
2871 .equals(artifactInfo.getArtifactUUID())) {
2872 log.debug("artifact UUID cannot be set. ignoring.");
2874 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2876 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2877 .getHeatParameters()
2878 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2879 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2883 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2885 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2886 for (HeatParameterDefinition parameter : heatParameters) {
2887 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2889 if (currentParam != null) {
2891 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2892 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2893 parameter.setName(currentParam.getName());
2895 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2896 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2897 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2898 parameter.setDefaultValue(currentParam.getDefaultValue());
2900 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2901 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2902 parameter.setType(currentParam.getType());
2904 if (parameter.getDescription() != null && !parameter.getDescription()
2905 .equalsIgnoreCase(currentParam.getDescription())) {
2906 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2907 parameter.setDescription(currentParam.getDescription());
2910 // check and set current value
2911 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2912 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2913 parameter.setCurrentValue(currentParam.getDefaultValue());
2919 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2921 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2922 for (HeatParameterDefinition param : currentParameters) {
2923 currentParamsMap.put(param.getUniqueId(), param);
2925 return currentParamsMap;
2928 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2929 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2930 log.debug("Artifact url cannot be empty.");
2931 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2933 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2935 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2936 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2938 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2939 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2942 return Either.left(true);
2945 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2946 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2947 log.debug("Artifact description cannot be empty.");
2948 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2950 String description = artifactInfo.getDescription();
2951 description = ValidationUtils.removeNoneUtf8Chars(description);
2952 description = ValidationUtils.normaliseWhitespace(description);
2953 description = ValidationUtils.stripOctets(description);
2954 description = ValidationUtils.removeHtmlTagsOnly(description);
2955 if (!ValidationUtils.validateIsEnglish(description)) {
2956 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2958 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2959 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2960 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2962 artifactInfo.setDescription(description);
2963 return Either.left(true);
2966 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2967 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2968 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2969 String prevArtifactId = null;
2970 String currArtifactId = artifactId;
2972 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2973 Either<ArtifactDefinition, Operation> insideEither = null;
2975 log.trace("Try to update entry on graph");
2976 String artifactUniqueId = null;
2977 ArtifactDefinition artifactDefinition = artifactInfo;
2978 StorageOperationStatus error;
2981 if (interfaceType == null || operationUuid == null) {
2982 log.debug("Entity on graph is updated. Update artifact in ES");
2984 // Changing previous and current artifactId for auditing
2985 prevArtifactId = currArtifactId;
2986 currArtifactId = artifactDefinition.getUniqueId();
2989 if (decodedPayload == null) {
2990 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2991 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2993 if (artifactFromCassandra.isRight()) {
2994 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2995 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2997 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2998 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2999 resultOp = Either.right(responseFormat);
3002 // clone data to new artifact
3003 artifactData.setData(artifactFromCassandra.left().value().getData());
3004 artifactData.setId(artifactFromCassandra.left().value().getId());
3007 if (artifactDefinition.getEsId() == null) {
3008 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3009 artifactData.setId(artifactDefinition.getUniqueId());
3013 NodeTypeEnum convertParentType = convertParentType(componentType);
3014 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
3015 .getUniqueId(), artifactId, convertParentType, parentId);
3016 isLeft = result.isLeft();
3018 artifactUniqueId = result.left().value().getUniqueId();
3019 artifactDefinition = result.left().value();
3020 String artifactType = artifactInfo.getArtifactType();
3021 if (NodeTypeEnum.Resource == convertParentType
3022 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3023 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3024 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3025 && !artifactUniqueId.equals(artifactId)) {
3026 // need to update the generated id in heat env
3027 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3028 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3030 .filter(a -> a.getValue()
3031 .getGeneratedFromId() != null && a
3033 .getGeneratedFromId()
3034 .equals(artifactId))
3036 if (findFirst.isPresent()) {
3037 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3038 artifactEnvInfo.setArtifactChecksum(null);
3039 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3042 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3044 insideEither = Either.left(result.left().value());
3045 resultOp = Either.left(insideEither);
3046 if (error != StorageOperationStatus.OK) {
3051 error = result.right().value();
3055 // create new entry in ES
3057 if (artifactData.getData() != null) {
3058 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3059 artifactData.setId(artifactDefinition.getEsId());
3061 res = saveArtifacts(artifactData, parentId);
3067 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3068 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3069 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3071 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3072 log.debug(FAILED_SAVE_ARTIFACT);
3073 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3074 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3075 resultOp = Either.right(responseFormat);
3078 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3079 decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3080 currArtifactId, artifactDefinition);
3086 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3087 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3088 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3089 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3090 ArtifactDefinition artifactDefinition) {
3091 StorageOperationStatus error;
3092 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3093 if (decodedPayload == null) {
3094 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3095 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3097 if (artifactFromCassandra.isRight()) {
3098 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3099 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3101 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3102 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3103 resultOp = Either.right(responseFormat);
3106 // clone data to new artifact
3107 artifactData.setData(artifactFromCassandra.left().value().getData());
3108 artifactData.setId(artifactFromCassandra.left().value().getId());
3110 // todo if not exist(first time)
3114 if (artifactDefinition.getEsId() == null) {
3115 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3116 artifactData.setId(artifactDefinition.getUniqueId());
3119 NodeTypeEnum convertParentType = convertParentType(componentType);
3120 // Set additional fields for artifact
3121 artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
3122 artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
3124 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
3125 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
3126 if(updateArtifactOnResourceEither.isRight()){
3127 log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
3128 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
3129 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3131 if (artifactData.getData() != null) {
3132 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3133 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3134 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
3135 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3136 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3137 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3141 Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
3142 if(updateOprEither.isRight()){
3143 return Either.right(updateOprEither.right().value());
3146 return Either.left(Either.left(updateOprEither.left().value()));
3149 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3150 log.trace("Starting payload handling");
3151 byte[] payload = artifactInfo.getPayloadData();
3152 byte[] decodedPayload = null;
3154 if (payload != null && payload.length != 0) {
3155 // the generated artifacts were already decoded by the handler
3156 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3157 if (decodedPayload.length == 0) {
3158 log.debug("Failed to decode the payload.");
3159 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3160 return Either.right(responseFormat);
3163 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3164 artifactInfo.setArtifactChecksum(checkSum);
3165 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3167 // Specific payload validations of different types
3168 Either<Boolean, ResponseFormat> result = Either.left(true);
3169 if (isDeploymentArtifact(artifactInfo)) {
3170 log.trace("Starting deployment artifacts payload validation");
3171 String artifactType = artifactInfo.getArtifactType();
3172 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
3173 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
3174 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
3175 if (isPayloadValid.isRight()) {
3176 ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
3177 return Either.right(responseFormat);
3180 if (payloadType.isHeatRelated()) {
3181 log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
3182 result = extractHeatParameters(artifactInfo);
3185 if (result.isRight()) {
3186 return Either.right(result.right().value());
3189 } // null/empty payload is normal if called from metadata update ONLY.
3190 // The validation of whether this is metadata/payload update case is
3191 // currently done separately
3193 if (!isArtifactMetadataUpdate) {
3194 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3195 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3196 return Either.right(responseFormat);
3199 log.trace("Ended payload handling");
3200 return Either.left(decodedPayload);
3203 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3204 boolean inTransaction) {
3205 User user = new User();
3206 user.setUserId(userUserId);
3207 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3208 if (parent.isRight()) {
3209 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3212 return Either.right(responseFormat);
3214 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3217 false, inTransaction);
3218 if (handleDelete.isRight()) {
3219 return Either.right(handleDelete.right().value());
3221 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3222 return Either.left(result.right().value());
3226 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3227 Operation op = new Operation();
3228 long time = System.currentTimeMillis();
3229 op.setCreationDate(time);
3231 String artifactName = artifactInfo.getArtifactName();
3232 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3234 op.setImplementation(artifactInfo);
3235 op.setLastUpdateDate(time);
3239 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3240 String newArtifactName = operationName + "_" + artifactName;
3241 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3242 return newArtifactName;
3246 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3248 // General validation
3249 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3250 log.debug(NULL_PARAMETER);
3251 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3254 // Normalizing artifact name
3255 artifactName = ValidationUtils.normalizeFileName(artifactName);
3257 // Resource validation
3258 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3259 if (validateResourceNameAndVersion.isRight()) {
3260 return Either.right(validateResourceNameAndVersion.right().value());
3263 Resource resource = validateResourceNameAndVersion.left().value();
3264 String resourceId = resource.getUniqueId();
3266 // Service validation
3267 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3268 if (validateServiceNameAndVersion.isRight()) {
3269 return Either.right(validateServiceNameAndVersion.right().value());
3272 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3273 if (artifacts == null || artifacts.isEmpty()) {
3274 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3275 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3278 ArtifactDefinition deploymentArtifact = null;
3280 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3281 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3282 .equals(artifactName)) {
3283 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3284 deploymentArtifact = artifactDefinition;
3289 if (deploymentArtifact == null) {
3290 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3291 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3294 // Downloading the artifact
3295 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3296 if (downloadArtifactEither.isRight()) {
3297 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3298 return Either.right(downloadArtifactEither.right().value());
3300 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3301 return Either.left(downloadArtifactEither.left().value().getRight());
3305 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3307 // General validation
3308 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3309 log.debug(NULL_PARAMETER);
3310 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3313 // Normalizing artifact name
3314 artifactName = ValidationUtils.normalizeFileName(artifactName);
3316 // Service validation
3317 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3318 if (validateServiceNameAndVersion.isRight()) {
3319 return Either.right(validateServiceNameAndVersion.right().value());
3322 Service service = validateServiceNameAndVersion.left().value();
3324 // ResourceInstance validation
3325 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3326 if (validateResourceInstance.isRight()) {
3327 return Either.right(validateResourceInstance.right().value());
3330 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3332 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3334 final String finalArtifactName = artifactName;
3335 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3337 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3339 .anyMatch(filterArtifactByName);
3340 ArtifactDefinition deployableArtifact;
3342 if (!hasDeploymentArtifacts) {
3343 log.debug("Deployment artifact with name {} not found", artifactName);
3344 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3347 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3348 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3349 // Downloading the artifact
3350 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3352 if (downloadArtifactEither.isRight()) {
3353 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3354 return Either.right(downloadArtifactEither.right().value());
3356 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3357 return Either.left(downloadArtifactEither.left().value().getRight());
3360 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3362 List<ComponentInstance> riList = service.getComponentInstances();
3363 for (ComponentInstance ri : riList) {
3364 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3365 return Either.left(ri);
3369 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3372 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3374 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3375 if (serviceListBySystemName.isRight()) {
3376 log.debug("Couldn't fetch any service with name {}", serviceName);
3377 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3379 .value(), ComponentTypeEnum.SERVICE), serviceName));
3381 List<Service> serviceList = serviceListBySystemName.left().value();
3382 if (serviceList == null || serviceList.isEmpty()) {
3383 log.debug("Couldn't fetch any service with name {}", serviceName);
3384 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3387 Service foundService = null;
3388 for (Service service : serviceList) {
3389 if (service.getVersion().equals(serviceVersion)) {
3390 log.trace("Found service with version {}", serviceVersion);
3391 foundService = service;
3396 if (foundService == null) {
3397 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3398 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3399 .getValue(), serviceVersion));
3401 return Either.left(foundService);
3404 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3406 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3407 if (resourceListBySystemName.isRight()) {
3408 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3409 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3411 .value()), resourceName));
3413 return Either.left(resourceListBySystemName.left().value());
3416 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3418 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3419 if (serviceName == null || serviceVersion == null || artifactName == null) {
3420 log.debug(NULL_PARAMETER);
3421 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3424 // Normalizing artifact name
3425 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3427 // Service validation
3428 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3429 if (validateServiceNameAndVersion.isRight()) {
3430 return Either.right(validateServiceNameAndVersion.right().value());
3433 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3435 // Looking for deployment or tosca artifacts
3436 Service service = validateServiceNameAndVersion.left().value();
3438 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3439 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3440 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3443 Optional<ArtifactDefinition> foundArtifactOptl = null;
3445 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3446 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3447 // filters artifact by name
3448 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3450 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3451 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3452 // filters TOSCA artifact by name
3453 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3455 if (!foundArtifactOptl.isPresent()) {
3456 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3457 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3459 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3460 // Downloading the artifact
3461 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3463 if (downloadArtifactEither.isRight()) {
3464 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3465 return Either.right(downloadArtifactEither.right().value());
3467 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3468 return Either.left(downloadArtifactEither.left().value().getRight());
3471 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3472 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3473 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3474 if (artifactById.isRight()) {
3475 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3476 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3477 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3479 ArtifactDefinition artifactDefinition = artifactById.left().value();
3480 if (artifactDefinition == null) {
3481 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3482 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3485 return downloadArtifact(artifactDefinition);
3488 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3489 boolean found = false;
3490 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3491 if (artifactsS != null) {
3492 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3493 if (entry.getValue().getUniqueId().equals(artifactId)) {
3499 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3500 if (!found && deploymentArtifactsS != null) {
3501 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3502 if (entry.getValue().getUniqueId().equals(artifactId)) {
3508 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3509 if (!found && toscaArtifactsS != null) {
3510 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3511 if (entry.getValue().getUniqueId().equals(artifactId)) {
3518 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3519 if (!found && interfaces != null) {
3520 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3521 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3522 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3523 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3524 .getImplementation()
3526 .equals(artifactId)) {
3534 switch (component.getComponentType()) {
3538 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3539 if (!found && apiArtifacts != null) {
3540 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3541 if (entry.getValue().getUniqueId().equals(artifactId)) {
3555 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3557 boolean found = false;
3558 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3559 ComponentInstance resourceInstance = null;
3560 for (ComponentInstance ri : resourceInstances) {
3561 if (ri.getUniqueId().equals(resourceInstanceId)) {
3562 resourceInstance = ri;
3566 if (resourceInstance != null) {
3567 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3568 if (artifacts != null) {
3569 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3570 if (entry.getValue().getUniqueId().equals(artifactId)) {
3577 artifacts = resourceInstance.getArtifacts();
3578 if (artifacts != null) {
3579 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3580 if (entry.getValue().getUniqueId().equals(artifactId)) {
3591 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3592 String containerComponentType) {
3594 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3595 componentForAudit.getNodeType();
3597 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3598 .getToscaFullElement(componentId);
3600 if (componentResult.isRight()) {
3601 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3602 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3603 log.debug("Service not found, serviceId {}", componentId);
3604 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3605 return Either.right(responseFormat);
3607 return Either.left(componentResult.left().value());
3610 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3611 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3612 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3613 if (canWork.isRight()) {
3614 String uniqueId = component.getUniqueId();
3615 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3616 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3618 .getComponentType(), null);
3619 return Either.right(canWork.right().value());
3622 return Either.left(true);
3625 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3627 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3628 String role = user.getRole();
3629 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3630 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3631 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3632 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3633 return Either.right(responseFormat);
3636 return Either.left(true);
3639 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3642 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3643 } catch(ByResponseFormatComponentException e){
3644 ResponseFormat responseFormat = e.getResponseFormat();
3645 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3647 } catch(ByActionStatusComponentException e){
3648 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3649 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3652 return Either.left(user);
3655 private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
3656 ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
3657 User user = new User();
3658 user.setUserId(userId);
3659 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3662 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3663 AuditingActionEnum auditingAction = null;
3664 switch (operation.getArtifactOperationEnum()) {
3666 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3669 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3672 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3675 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3680 return auditingAction;
3683 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3684 String esArtifactId = artifactDefinition.getEsId();
3685 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3686 if (artifactfromES.isRight()) {
3687 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3688 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3689 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3690 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3691 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3692 .getArtifactDisplayName());
3694 return Either.right(responseFormat);
3697 ESArtifactData esArtifactData = artifactfromES.left().value();
3698 byte[] data = esArtifactData.getDataAsArray();
3700 log.debug("Artifact data from ES is null");
3701 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3703 String artifactName = artifactDefinition.getArtifactName();
3704 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3705 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3708 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3709 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3712 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3713 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3715 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3716 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3719 log.info("Failed to save artifact {}.", artifactData.getId());
3725 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3726 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3729 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3730 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3733 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3734 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3735 if (user.isRight()) {
3736 ResponseFormat responseFormat;
3737 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3738 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3739 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3742 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3743 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3745 return Either.right(responseFormat);
3748 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3750 .value(), groupType);
3751 return Either.left(artifactDefinition);
3754 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3755 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3757 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3758 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3759 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3761 artifactInfo.setArtifactDisplayName(artifactName);
3762 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3763 artifactInfo.setArtifactType(artifactType);
3764 artifactInfo.setDescription(artifactDescription);
3765 artifactInfo.setArtifactGroupType(groupType);
3766 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3768 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3770 return artifactInfo;
3773 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3774 String uniqueId = null;
3776 if (resourceId != null) {
3777 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3779 artifactInfo.setUniqueId(uniqueId);
3781 artifactInfo.setUserIdCreator(user.getUserId());
3782 String fullName = user.getFullName();
3783 artifactInfo.setUpdaterFullName(fullName);
3785 long time = System.currentTimeMillis();
3787 artifactInfo.setCreatorFullName(fullName);
3788 artifactInfo.setCreationDate(time);
3790 artifactInfo.setLastUpdateDate(time);
3791 artifactInfo.setUserIdLastUpdater(user.getUserId());
3793 artifactInfo.setMandatory(true);
3796 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3797 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3800 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3801 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3804 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3806 byte[] payload = payloadStr.getBytes();
3808 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3809 return Either.left(artifactData);
3813 * @param artifactDefinition
3816 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3817 String instanceId, boolean shouldLock, boolean inTransaction) {
3818 String payload = generateHeatEnvPayload(artifactDefinition);
3819 String prevUUID = artifactDefinition.getArtifactUUID();
3820 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3821 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3823 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3826 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3827 boolean shouldLock, boolean inTransaction, String instanceId) {
3828 String payload = generateHeatEnvPayload(artifactDefinition);
3829 String prevUUID = artifactDefinition.getArtifactUUID();
3830 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3831 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3833 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3836 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3837 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3838 List<ComponentInstance> componentInstances = component.getComponentInstances();
3839 if (componentInstances != null) {
3840 Optional<ComponentInstance> findFirst = componentInstances.stream()
3841 .filter(ci -> ci.getUniqueId()
3842 .equals(instanceId))
3844 if (findFirst.isPresent()) {
3845 ComponentInstance relevantInst = findFirst.get();
3846 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3847 .getGroupInstances());
3849 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3850 updatedGroupInstances.forEach(gi -> {
3851 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3852 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3854 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3855 if (status.isRight()) {
3856 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3857 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3858 .convertFromStorageResponse(status.right()
3859 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3860 return Either.right(responseFormat);
3866 return Either.left(updatedArtDef);
3869 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3870 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3871 StringBuilder sb = new StringBuilder();
3872 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3873 sb.append("parameters:\n");
3874 if (heatParameters != null) {
3875 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3877 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3879 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3881 String heatValue = heatParameterDefinition.getCurrentValue();
3882 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3883 heatValue = heatParameterDefinition.getDefaultValue();
3884 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3885 empltyHeatValues.add(heatParameterDefinition);
3889 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3894 .append(heatParameterDefinition.getName())
3897 .append(Boolean.parseBoolean(heatValue))
3902 .append(heatParameterDefinition.getName())
3905 .append(new BigDecimal(heatValue).toPlainString())
3908 case COMMA_DELIMITED_LIST:
3911 .append(heatParameterDefinition.getName())
3918 String value = heatValue;
3919 boolean starts = value.startsWith("\"");
3920 boolean ends = value.endsWith("\"");
3921 if (!(starts && ends)) {
3922 starts = value.startsWith("'");
3923 ends = value.endsWith("'");
3924 if (!(starts && ends)) {
3925 value = "\"" + value + "\"";
3929 .append(heatParameterDefinition.getName())
3939 if (!empltyHeatValues.isEmpty()) {
3940 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3941 empltyHeatValues.forEach(hv -> {
3942 sb.append(" ").append(hv.getName()).append(":");
3943 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3944 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3945 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3946 sb.append(" \"\"").append("\n");
3949 sb.append(" ").append("\n");
3954 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3957 return sb.toString().replaceAll("\\\\n", "\n");
3961 * @param artifactDefinition
3965 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3966 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3967 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
3968 .getHeatParamsUpdateDate(),
3969 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3973 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3974 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3975 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3976 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3980 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3981 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3983 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3985 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3986 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3988 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3989 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3990 ESArtifactData artifactData = null;
3992 if (artifactDataRes.isLeft()) {
3993 artifactData = artifactDataRes.left().value();
3996 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3997 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3998 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3999 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4001 return Either.right(artifactDataRes.right().value());
4003 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4005 String esArtifactId = artifactDefinition.getEsId();
4006 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4007 ESArtifactData esArtifactData;
4008 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4009 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4010 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4011 if (artifactfromES.isRight()) {
4012 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4013 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4014 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4015 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4016 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4018 esArtifactData = artifactfromES.left().value();
4019 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4022 oldCheckSum = artifactDefinition.getArtifactChecksum();
4025 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4028 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4029 if (lockComponent.isRight()) {
4030 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4031 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4032 return Either.right(lockComponent.right().value());
4036 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4038 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4039 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4040 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4041 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4042 .getArtifactType(), artifactDefinition.getEsId());
4043 if (updateArifactDefinitionStatus.isRight()) {
4044 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4046 .value()), artifactDefinition.getArtifactDisplayName());
4047 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4048 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4049 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4050 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4052 return Either.right(responseFormat);
4057 oldCheckSum = artifactDefinition.getArtifactChecksum();
4058 artifactDefinition.setArtifactChecksum(newCheckSum);
4059 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4060 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4061 .getArtifactType(), artifactDefinition.getEsId());
4062 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4063 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4065 log.trace("Update Payload ", artifactDefinition.getEsId());
4067 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4069 artifactDefinition = updateArifactDefinitionStatus.left().value();
4070 artifactData.setId(artifactDefinition.getUniqueId());
4071 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4073 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4074 if (!inTransaction) {
4075 janusGraphDao.commit();
4077 log.debug("Artifact Saved In ES {}", artifactData.getId());
4078 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4079 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4080 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4081 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4085 if (!inTransaction) {
4086 janusGraphDao.rollback();
4088 log.info("Failed to save artifact {}.", artifactData.getId());
4089 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4090 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4091 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4092 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4094 return Either.right(responseFormat);
4098 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4100 .value()), artifactDefinition.getArtifactDisplayName());
4101 log.debug("Failed To update artifact {}", artifactData.getId());
4102 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4103 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4104 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4106 return Either.right(responseFormat);
4112 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4118 return Either.left(artifactDefinition);
4122 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4123 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4124 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4125 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4129 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4130 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4132 Map<String, Object> json = new HashMap<>();
4133 if (artifactId != null && !artifactId.isEmpty()) {
4134 json.put(Constants.ARTIFACT_ID, artifactId);
4137 json.put(Constants.ARTIFACT_NAME, artifactName);
4138 json.put(Constants.ARTIFACT_TYPE, artifactType);
4139 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4141 if (artifactContent != null) {
4142 log.debug("payload is encoded. perform decode");
4143 String encodedPayload = Base64.encodeBase64String(artifactContent);
4144 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4146 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4147 json.put(Constants.ARTIFACT_LABEL, label);
4148 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4149 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4150 : updatedRequiredArtifacts.stream()
4151 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4153 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4154 .map(e -> e.getFileName())
4155 .collect(Collectors.toList()));
4156 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4161 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4163 String jsonStr = gson.toJson(json);
4164 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4165 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4166 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4167 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4168 if (uploadArtifactToService.isRight()) {
4169 return Either.right(uploadArtifactToService.right().value());
4172 return Either.left(uploadArtifactToService.left().value());
4175 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4176 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4177 convertParentType(componentType);
4178 String parentId = parent.getUniqueId();
4179 ArtifactDefinition currArtifact = artifactInfo;
4181 if (origMd5 != null) {
4182 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4183 if (validateMd5.isRight()) {
4184 ResponseFormat responseFormat = validateMd5.right().value();
4185 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4186 return Either.right(responseFormat);
4189 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4190 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4191 if (deploymentValidationResult.isRight()) {
4192 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4193 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4194 return Either.right(responseFormat);
4197 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4198 if (payloadEither.isRight()) {
4199 ResponseFormat responseFormat = payloadEither.right().value();
4200 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4201 return Either.right(responseFormat);
4205 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4206 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4207 return Either.right(responseFormat);
4213 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4214 if (lockComponent.isRight()) {
4215 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4216 .value(), componentType, null);
4217 return Either.right(lockComponent.right().value());
4220 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4222 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4228 if (resultOp == null || resultOp.isRight()) {
4229 log.debug(ROLLBACK);
4230 if (!inTransaction) {
4231 janusGraphDao.rollback();
4236 if (!inTransaction) {
4237 janusGraphDao.commit();
4241 componentType = parent.getComponentType();
4243 NodeTypeEnum nodeType = componentType.getNodeType();
4244 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4248 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4249 ComponentTypeEnum componentType, String origMd5) {
4251 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4252 Either<ArtifactDefinition, Operation> insideEither = null;
4253 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4254 if (getRI.isRight()) {
4255 return Either.right(getRI.right().value());
4257 ComponentInstance ri = getRI.left().value();
4258 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4259 if (getArtifactRes.isRight()) {
4260 return Either.right(getArtifactRes.right().value());
4262 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4264 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4265 .equals(ArtifactTypeEnum.HEAT_VOL
4266 .getType()) || currArtifact
4268 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4269 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4270 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4272 return Either.right(responseFormat);
4274 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4275 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4276 new ArrayList<HeatParameterDefinition>();
4279 if (origMd5 != null) {
4280 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4281 .getName(), currentHeatEnvParams,
4282 updatedHeatEnvParams, currArtifact.getArtifactName());
4283 if (uploadParamsValidationResult.isRight()) {
4284 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4285 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4287 return Either.right(responseFormat);
4289 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4292 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4294 if (validateAndConvertHeatParamers.isRight()) {
4295 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4296 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4298 return Either.right(responseFormat);
4301 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4302 // fill reduced heat env parameters List for updating
4303 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4304 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4305 currArtifact.setListHeatParameters(currentHeatEnvParams);
4307 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4308 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4309 if (updateArifactRes.isRight()) {
4310 log.debug("Failed to update artifact on graph - {}", artifactId);
4311 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4314 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4316 return Either.right(responseFormat);
4318 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4319 if (error != StorageOperationStatus.OK) {
4320 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4321 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4323 return Either.right(responseFormat);
4326 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4328 .getUniqueId(), parent.getUniqueId());
4329 if (error != StorageOperationStatus.OK) {
4330 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4331 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4333 return Either.right(responseFormat);
4337 insideEither = Either.left(currArtifact);
4338 resultOp = Either.left(insideEither);
4339 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4340 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4345 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4346 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4347 String paramName = heatEnvParam.getName();
4348 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4349 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4350 String updatedParamValue = heatEnvParam.getCurrentValue();
4351 currHeatParam.setCurrentValue(updatedParamValue);
4357 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4358 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4360 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4361 Either<ArtifactDefinition, Operation> insideEither = null;
4362 String currentHeatId = currHeatArtifact.getUniqueId();
4364 String esArtifactId = currHeatArtifact.getEsId();
4365 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4366 if (artifactFromES.isRight()) {
4367 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4368 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4369 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4370 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4371 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4374 ESArtifactData esArtifactData = artifactFromES.left().value();
4376 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4378 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4379 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4380 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4382 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4386 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4388 paramName = heatEnvParam.getName();
4389 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4390 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4392 String updatedParamValue = heatEnvParam.getCurrentValue();
4393 if (updatedParamValue == null) {
4394 updatedParamValue = heatEnvParam.getDefaultValue();
4396 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4397 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4398 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4399 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4400 .getType(), paramType.getType(), paramName);
4401 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4402 return Either.right(responseFormat);
4405 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4406 newHeatEnvParams.add(currHeatParam);
4411 if (!newHeatEnvParams.isEmpty()) {
4412 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4413 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4414 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4416 if (operationStatus.isRight()) {
4417 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4419 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4422 return Either.right(responseFormat);
4425 updatedHeatArt = operationStatus.left().value();
4427 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4428 esArtifactData.setId(updatedHeatArt.getEsId());
4430 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4433 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4434 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4435 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4436 .getUniqueId(), responseFormat, componentType, null);
4439 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4440 log.debug(FAILED_SAVE_ARTIFACT);
4441 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4442 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4443 .getUniqueId(), responseFormat, componentType, null);
4444 resultOp = Either.right(responseFormat);
4447 insideEither = Either.left(updatedHeatArt);
4450 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4451 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4452 artifactEnvInfo.setArtifactChecksum(null);
4453 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4454 .getUniqueId(), componentType.getNodeType(), componentId);
4457 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4461 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4462 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4464 .value(), parent, componentType);
4465 if (result != ActionStatus.OK) {
4466 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4467 return Either.right(responseFormat);
4471 if (updatedHeatEnvParams.isEmpty()) {
4472 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4474 resultOp = Either.left(insideEither);
4475 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4476 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4481 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4482 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4483 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4484 return Either.right(responseFormat);
4488 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4489 StorageOperationStatus error = StorageOperationStatus.OK;
4490 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4491 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4492 List<String> groupInstancesId = null;
4493 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4494 groupInstancesId = groupsInstances.stream()
4495 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4496 .contains(artifactId))
4497 .map(GroupInstanceDataDefinition::getUniqueId)
4498 .collect(Collectors.toList());
4500 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4501 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4507 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4508 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4510 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4511 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4512 .getArtifactName(), currArtifactName);
4513 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4514 return Either.right(responseFormat);
4517 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4518 String paramName = uploadedHeatParam.getName();
4519 boolean isExistsInHeat = false;
4520 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4521 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4523 isExistsInHeat = true;
4524 uploadedHeatParam.setType(currHeatParam.getType());
4525 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4526 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4527 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4531 if (!isExistsInHeat) {
4532 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4533 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4534 return Either.right(responseFormat);
4537 return Either.left(updatedHeatEnvParams);
4540 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4541 ResponseFormat responseFormat = null;
4542 List<ComponentInstance> ris = component.getComponentInstances();
4543 for (ComponentInstance ri : ris) {
4544 if (riID.equals(ri.getUniqueId())) {
4545 return Either.left(ri);
4548 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4549 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4550 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4551 return Either.right(responseFormat);
4554 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4555 ResponseFormat responseFormat = null;
4556 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4557 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4558 if (artifactId.equals(artifact.getUniqueId())) {
4559 return Either.left(artifact);
4562 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4563 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4565 return Either.right(responseFormat);
4568 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4569 ArtifactDefinition ret;
4570 if (eitherArtifact.isLeft()) {
4571 ret = eitherArtifact.left().value();
4574 ret = eitherArtifact.right().value().getImplementationArtifact();
4580 * downloads artifact of component by UUIDs
4582 * @param componentType
4583 * @param componentUuid
4584 * @param artifactUUID
4585 * @param resourceCommonInfo
4588 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4589 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4590 Either<byte[], ResponseFormat> result;
4591 byte[] downloadedArtifact = null;
4592 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4593 if (errorWrapper.isEmpty() && component != null) {
4594 resourceCommonInfo.setResourceName(component.getName());
4595 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4597 if (errorWrapper.isEmpty()) {
4598 result = Either.left(downloadedArtifact);
4601 result = Either.right(errorWrapper.getInnerElement());
4607 * downloads an artifact of resource instance of component by UUIDs
4609 * @param componentType
4610 * @param componentUuid
4611 * @param resourceInstanceName
4612 * @param artifactUUID
4615 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4616 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4617 Either<byte[], ResponseFormat> result;
4618 byte[] downloadedArtifact = null;
4619 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4620 if (errorWrapper.isEmpty()) {
4621 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4624 if (errorWrapper.isEmpty()) {
4625 result = Either.left(downloadedArtifact);
4628 result = Either.right(errorWrapper.getInnerElement());
4634 * uploads an artifact to a component by UUID
4638 * @param componentType
4639 * @param componentUuid
4640 * @param resourceCommonInfo
4644 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4645 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4646 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4647 Component component = null;
4648 String componentId = null;
4649 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4650 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4651 String userId = request.getHeader(Constants.USER_ID_HEADER);
4653 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4654 if (getComponentRes.isRight()) {
4655 StorageOperationStatus status = getComponentRes.right().value();
4656 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4657 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4659 if (errorWrapper.isEmpty()) {
4660 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4661 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4663 if (!getComponentRes.left()
4665 .getMetadataDataDefinition()
4667 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4668 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4669 if (component != null) {
4670 componentId = component.getUniqueId();
4671 componentName = component.getName();
4674 resourceCommonInfo.setResourceName(componentName);
4676 if (errorWrapper.isEmpty()) {
4677 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4678 if (actionResult.isRight()) {
4679 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4682 return Either.right(actionResult.right().value());
4684 return Either.left(actionResult.left().value().left().value());
4686 return Either.right(errorWrapper.getInnerElement());
4689 * upload an artifact to a resource instance by UUID
4693 * @param componentType
4694 * @param componentUuid
4695 * @param resourceInstanceName
4699 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4700 ArtifactOperationInfo operation) {
4701 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4702 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4703 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4704 ArtifactDefinition uploadArtifact = null;
4705 Component component = null;
4706 String componentInstanceId;
4708 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4709 String userId = request.getHeader(Constants.USER_ID_HEADER);
4711 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4712 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4713 if (getComponentRes.isRight()) {
4714 StorageOperationStatus status = getComponentRes.right().value();
4715 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4716 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4718 if (errorWrapper.isEmpty() && !getComponentRes.left()
4720 .getMetadataDataDefinition()
4722 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4723 component = checkoutParentComponent(componentType, getComponentRes.left()
4725 .getMetadataDataDefinition()
4726 .getUniqueId(), userId, errorWrapper);
4728 if (errorWrapper.isEmpty()) {
4729 if (component == null) {
4730 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4733 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4736 if (errorWrapper.isEmpty()) {
4737 componentInstanceId = componentRiPair.getRight().getUniqueId();
4738 componentId = componentRiPair.getLeft().getUniqueId();
4739 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4741 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4742 .findParamByType(componentType));
4743 if (actionResult.isRight()) {
4744 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4747 errorWrapper.setInnerElement(actionResult.right().value());
4750 if (errorWrapper.isEmpty()) {
4751 uploadArtifact = actionResult.left().value().left().value();
4752 uploadArtifactResult = Either.left(uploadArtifact);
4755 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4757 return uploadArtifactResult;
4761 * updates an artifact on a component by UUID
4765 * @param componentType
4766 * @param componentUuid
4767 * @param artifactUUID
4771 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4772 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4773 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4774 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4775 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4776 ArtifactDefinition updateArtifact = null;
4777 Component component = null;
4778 String componentId = null;
4779 String artifactId = null;
4780 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4781 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4782 String userId = request.getHeader(Constants.USER_ID_HEADER);
4784 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4785 if (getComponentRes.isRight()) {
4786 StorageOperationStatus status = getComponentRes.right().value();
4787 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4788 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4790 if (errorWrapper.isEmpty()) {
4791 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4792 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4794 if (!getComponentRes.left()
4796 .getMetadataDataDefinition()
4798 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4799 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4800 if (component != null) {
4801 componentId = component.getUniqueId();
4802 componentName = component.getName();
4805 resourceCommonInfo.setResourceName(componentName);
4807 if (errorWrapper.isEmpty()) {
4808 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4810 if (errorWrapper.isEmpty()) {
4811 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4812 if (actionResult.isRight()) {
4813 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4816 errorWrapper.setInnerElement(actionResult.right().value());
4819 if (errorWrapper.isEmpty()) {
4820 updateArtifact = actionResult.left().value().left().value();
4821 updateArtifactResult = Either.left(updateArtifact);
4825 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4827 return updateArtifactResult;
4831 * updates an artifact on a resource instance by UUID
4835 * @param componentType
4836 * @param componentUuid
4837 * @param resourceInstanceName
4838 * @param artifactUUID
4839 * @param operation TODO
4842 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4843 ArtifactOperationInfo operation) {
4845 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4846 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4847 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4848 ArtifactDefinition updateArtifact = null;
4849 Component component = null;
4850 String componentInstanceId = null;
4851 String componentId = null;
4852 String artifactId = null;
4853 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4854 String userId = request.getHeader(Constants.USER_ID_HEADER);
4856 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4857 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4858 if (getComponentRes.isRight()) {
4859 StorageOperationStatus status = getComponentRes.right().value();
4860 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4861 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4863 if (errorWrapper.isEmpty() && !getComponentRes.left()
4865 .getMetadataDataDefinition()
4867 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4868 component = checkoutParentComponent(componentType, getComponentRes.left()
4870 .getMetadataDataDefinition()
4871 .getUniqueId(), userId, errorWrapper);
4873 if (errorWrapper.isEmpty()) {
4874 if (component == null) {
4875 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4878 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4881 if (errorWrapper.isEmpty()) {
4882 componentInstanceId = componentRiPair.getRight().getUniqueId();
4883 componentId = componentRiPair.getLeft().getUniqueId();
4884 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4886 if (errorWrapper.isEmpty()) {
4887 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4889 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4890 .findParamByType(componentType));
4891 if (actionResult.isRight()) {
4892 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4895 errorWrapper.setInnerElement(actionResult.right().value());
4898 if (errorWrapper.isEmpty()) {
4899 updateArtifact = actionResult.left().value().left().value();
4900 updateArtifactResult = Either.left(updateArtifact);
4903 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4905 return updateArtifactResult;
4908 private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4909 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4910 if (componentStorageOperationStatusEither.isRight()) {
4911 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4912 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4913 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4915 Component storedComponent = componentStorageOperationStatusEither.left().value();
4917 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4918 if(!optionalInterface.isPresent()) {
4919 log.debug("Failed to get resource interface for resource Id {}", componentId);
4920 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4923 //fetch the operation from storage
4924 InterfaceDefinition gotInterface = optionalInterface.get();
4925 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4926 Optional<Operation> optionalOperation = operationsMap.values()
4928 .filter(o -> o.getUniqueId().equals(operationUuid))
4930 if (!optionalOperation.isPresent()) {
4931 log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4932 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4933 return Either.right(responseFormat);
4936 Operation operation = optionalOperation.get();
4937 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
4938 implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
4939 implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
4940 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
4941 implementationArtifact.setDescription(artifactInfo.getDescription());
4942 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
4943 implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
4944 implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
4945 implementationArtifact.setEsId(artifactInfo.getEsId());
4946 operation.setImplementation(implementationArtifact);
4947 gotInterface.setOperationsMap(operationsMap);
4948 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
4949 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
4950 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
4951 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
4952 ActionStatus actionStatus =
4953 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
4954 return Either.right(componentsUtils.getResponseFormat(actionStatus));
4957 return Either.left(artifactInfo);
4961 * updates an artifact on a component by UUID
4965 * @param componentType
4966 * @param componentUuid
4967 * @param artifactUUID
4971 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4972 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4973 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
4974 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4975 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4976 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4977 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4978 ArtifactDefinition updateArtifact = null;
4979 String componentId = null;
4980 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4981 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4982 String userId = request.getHeader(Constants.USER_ID_HEADER);
4983 ArtifactDefinition existingArtifactInfo = null;
4984 String interfaceName = null;
4986 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4987 if (getComponentRes.isRight()) {
4988 StorageOperationStatus status = getComponentRes.right().value();
4989 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4990 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4993 if (errorWrapper.isEmpty()) {
4994 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4995 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4996 if (!getComponentRes.left()
4998 .getMetadataDataDefinition()
5000 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5001 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5002 if (component != null) {
5003 componentId = component.getUniqueId();
5004 componentName = component.getName();
5008 resourceCommonInfo.setResourceName(componentName);
5011 if(errorWrapper.isEmpty()){
5012 Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
5013 if (interfaceNameEither.isRight()) {
5014 errorWrapper.setInnerElement(interfaceNameEither.right().value());
5017 interfaceName = interfaceNameEither.left().value();
5020 if(errorWrapper.isEmpty()){
5021 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
5022 if (toscaComponentEither.isRight()) {
5023 StorageOperationStatus status = toscaComponentEither.right().value();
5024 log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
5025 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5028 if (errorWrapper.isEmpty()) {
5029 NodeTypeEnum parentType = convertParentType(componentType);
5030 List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
5031 for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
5032 if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
5033 existingArtifactInfo = artifactDefinition;
5037 if(existingArtifactInfo != null){
5038 return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
5044 if (errorWrapper.isEmpty()) {
5045 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5046 artifactUUID, artifactInfo, origMd5, data, interfaceName,
5047 operationUUID, null, null);
5048 if (actionResult.isRight()) {
5049 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5052 errorWrapper.setInnerElement(actionResult.right().value());
5056 if (errorWrapper.isEmpty()) {
5057 updateArtifact = actionResult.left().value().left().value();
5058 updateArtifactResult = Either.left(updateArtifact);
5062 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5064 return updateArtifactResult;
5067 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5068 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5069 if (componentStorageOperationStatusEither.isRight()) {
5070 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5071 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5072 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5074 Component storedComponent = componentStorageOperationStatusEither.left().value();
5076 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5077 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5078 if(!optionalInterface.isPresent()) {
5079 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5081 return Either.left(optionalInterface.get().getType());
5086 * deletes an artifact on a component by UUID
5089 * @param componentType
5090 * @param componentUuid
5091 * @param artifactUUID
5092 * @param resourceCommonInfo
5093 * @param operation TODO
5096 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5097 ArtifactOperationInfo operation) {
5099 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5100 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5101 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5102 ArtifactDefinition deleteArtifact = null;
5103 Component component = null;
5104 String componentId = null;
5105 String artifactId = null;
5106 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5107 String userId = request.getHeader(Constants.USER_ID_HEADER);
5109 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5110 if (getComponentRes.isRight()) {
5111 StorageOperationStatus status = getComponentRes.right().value();
5112 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5113 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5115 if (errorWrapper.isEmpty()) {
5116 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5117 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5118 if (!getComponentRes.left()
5120 .getMetadataDataDefinition()
5122 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5123 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5124 if (component != null) {
5125 componentId = component.getUniqueId();
5126 componentName = component.getName();
5129 resourceCommonInfo.setResourceName(componentName);
5131 if (errorWrapper.isEmpty()) {
5132 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5134 if (errorWrapper.isEmpty()) {
5135 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5136 if (actionResult.isRight()) {
5137 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5140 errorWrapper.setInnerElement(actionResult.right().value());
5143 if (errorWrapper.isEmpty()) {
5144 deleteArtifact = actionResult.left().value().left().value();
5145 deleteArtifactResult = Either.left(deleteArtifact);
5148 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5150 return deleteArtifactResult;
5154 * deletes an artifact from a resource instance by UUID
5157 * @param componentType
5158 * @param componentUuid
5159 * @param resourceInstanceName
5160 * @param artifactUUID
5161 * @param operation TODO
5164 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5165 ArtifactOperationInfo operation) {
5167 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5168 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5169 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5170 ArtifactDefinition deleteArtifact = null;
5171 Component component = null;
5172 String componentInstanceId = null;
5173 String componentId = null;
5174 String artifactId = null;
5175 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5176 String userId = request.getHeader(Constants.USER_ID_HEADER);
5177 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5178 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5179 if (getComponentRes.isRight()) {
5180 StorageOperationStatus status = getComponentRes.right().value();
5181 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5182 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5184 if (errorWrapper.isEmpty() && !getComponentRes.left()
5186 .getMetadataDataDefinition()
5188 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5189 component = checkoutParentComponent(componentType, getComponentRes.left()
5191 .getMetadataDataDefinition()
5192 .getUniqueId(), userId, errorWrapper);
5194 if (errorWrapper.isEmpty()) {
5195 if (component == null) {
5196 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5199 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5202 if (errorWrapper.isEmpty()) {
5203 componentInstanceId = componentRiPair.getRight().getUniqueId();
5204 componentId = componentRiPair.getLeft().getUniqueId();
5205 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5207 if (errorWrapper.isEmpty()) {
5209 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5210 .findParamByType(componentType));
5212 if (actionResult.isRight()) {
5213 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5216 errorWrapper.setInnerElement(actionResult.right().value());
5219 if (errorWrapper.isEmpty()) {
5220 deleteArtifact = actionResult.left().value().left().value();
5221 deleteArtifactResult = Either.left(deleteArtifact);
5224 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5226 return deleteArtifactResult;
5229 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5230 String artifactId = null;
5231 ArtifactDefinition foundArtifact = null;
5232 if (instance.getDeploymentArtifacts() != null) {
5233 foundArtifact = instance.getDeploymentArtifacts()
5236 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5237 .equals(artifactUUID))
5241 if (foundArtifact == null && instance.getArtifacts() != null) {
5242 foundArtifact = instance.getArtifacts()
5245 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5246 .equals(artifactUUID))
5250 if (foundArtifact == null) {
5251 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5252 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5255 artifactId = foundArtifact.getUniqueId();
5260 @SuppressWarnings("unchecked")
5261 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5262 Map<String, String> existingEnvVersions) {
5263 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5265 .getDeploymentResourceInstanceArtifacts();
5266 if (deploymentResourceArtifacts == null) {
5267 log.debug("no deployment artifacts are configured for generated artifacts");
5268 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5270 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5271 if (placeHolderData == null) {
5272 log.debug("no env type {} are configured for generated artifacts", envType);
5273 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5276 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5277 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5278 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5279 if (createArtifactPlaceHolder.isRight()) {
5280 return Either.right(createArtifactPlaceHolder.right().value());
5282 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5283 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5284 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5285 artifactHeatEnv.setTimeout(0);
5286 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5287 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5288 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5289 ArtifactDefinition heatEnvPlaceholder;
5290 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5291 if (parentType != NodeTypeEnum.ResourceInstance) {
5292 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5293 .getUniqueId(), parentType, parentId);
5294 if (addHeatEnvArtifact.isRight()) {
5295 log.debug("failed to create heat env artifact on resource instance");
5296 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5298 .value(), false), "", null));
5300 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5303 heatEnvPlaceholder = artifactHeatEnv;
5304 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5305 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5308 ComponentTypeEnum componentType = component.getComponentType();
5309 if (parentType == NodeTypeEnum.ResourceInstance) {
5310 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5312 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5313 new ResourceCommonInfo(parentName, componentType.getValue()),
5314 ResourceVersionInfo.newBuilder().build(),
5315 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5316 null, heatEnvPlaceholder, null);
5317 return Either.left(heatEnvPlaceholder);
5320 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5321 if (artifact.getListHeatParameters() == null) {
5324 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5325 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5326 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5327 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5328 heatEnvParameter.setCurrentValue(null);
5329 heatEnvParameters.add(heatEnvParameter);
5331 artifactDefinition.setListHeatParameters(heatEnvParameters);
5334 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5335 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5336 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5337 String name = heatArtifact.getArtifactName();
5340 name = heatArtifact.getArtifactLabel();
5341 fileName = name + "." + envExtension;
5344 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5346 heatEnvArtifact.setArtifactName(fileName);
5349 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5350 if (null != existingEnvVersions) {
5351 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5352 if (null != prevVersion) {
5353 heatEnvArtifact.setArtifactVersion(prevVersion);
5359 * Handles Artifacts Request For Inner Component
5361 * @param artifactsToHandle
5364 * @param vfcsNewCreatedArtifacts
5367 * @param inTransaction
5370 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5371 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5373 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5374 ComponentTypeEnum componentType = component.getComponentType();
5375 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5376 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5377 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5381 for (ArtifactDefinition artifact : artifactsToHandle) {
5382 originData = buildJsonStringForCsarVfcArtifact(artifact);
5383 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5384 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5385 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5386 if (actionResult.isRight()) {
5387 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5388 .getName(), actionResult.right().value());
5389 errorWrapper.setInnerElement(actionResult.right().value());
5390 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5391 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5395 uploadedArtifacts.add(actionResult.left().value().left().value());
5397 if (errorWrapper.isEmpty()) {
5398 handleArtifactsResult = Either.left(uploadedArtifacts);
5401 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5404 catch (Exception e) {
5405 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5406 handleArtifactsResult = Either.right(responseFormat);
5407 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5409 return handleArtifactsResult;
5412 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5413 ComponentInstance componentInstance = null;
5414 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5415 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5416 if (errorWrapper.isEmpty()) {
5417 componentInstance = component.getComponentInstances()
5419 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5420 .equals(normalizedName))
5423 if (componentInstance == null) {
5424 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5426 .getValue(), component.getName()));
5427 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5430 return componentInstance;
5433 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5435 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5436 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5437 ComponentInstance componentInstance = component.getComponentInstances()
5439 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5440 .equals(normalizedName))
5443 if (componentInstance == null) {
5444 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5446 .getValue(), component.getName()));
5447 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5450 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5452 return relatedComponentComponentInstancePair;
5455 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5456 ComponentInstance componentInstance;
5457 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5458 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5459 if (errorWrapper.isEmpty()) {
5460 componentInstance = component.getComponentInstances()
5462 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5465 if (componentInstance == null) {
5466 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5468 .getValue(), component.getName()));
5469 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5472 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5475 return relatedComponentComponentInstancePair;
5478 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5480 byte[] downloadedArtifact = null;
5481 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5482 List<ArtifactDefinition> artifactsList = null;
5483 ArtifactDefinition deploymentArtifact = null;
5484 if (artifacts != null && !artifacts.isEmpty()) {
5485 artifactsList = artifacts.values()
5487 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5488 .equals(artifactUUID))
5489 .collect(Collectors.toList());
5491 if (artifactsList == null || artifactsList.isEmpty()) {
5492 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5493 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5495 if (errorWrapper.isEmpty()) {
5496 deploymentArtifact = artifactsList.get(0);
5497 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5498 if (downloadArtifactEither.isRight()) {
5499 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5500 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5503 if (errorWrapper.isEmpty()) {
5504 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5505 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5507 return downloadedArtifact;
5510 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5511 Component component = null;
5512 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5513 if (getComponentRes.isRight()) {
5514 StorageOperationStatus status = getComponentRes.right().value();
5515 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5516 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5519 component = getComponentRes.left().value();
5524 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5525 Component component = null;
5526 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5527 if (getComponentRes.isRight()) {
5528 StorageOperationStatus status = getComponentRes.right().value();
5529 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5530 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5533 List<Component> value = getComponentRes.left().value();
5534 if (value.isEmpty()) {
5535 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5536 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5537 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5540 component = value.get(0);
5546 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5547 String artifactId = null;
5548 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5549 StorageOperationStatus storageStatus;
5550 ArtifactDefinition latestArtifact = null;
5551 List<ArtifactDefinition> artifacts = null;
5552 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5553 if (getArtifactsRes.isRight()) {
5554 storageStatus = getArtifactsRes.right().value();
5555 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5556 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5557 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5559 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5561 if (errorWrapper.isEmpty()) {
5562 artifacts = getArtifactsRes.left()
5566 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5567 .equals(artifactUUID))
5568 .collect(Collectors.toList());
5569 if (artifacts == null || artifacts.isEmpty()) {
5570 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5571 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5574 if (errorWrapper.isEmpty()) {
5575 latestArtifact = artifacts.stream().max((a1, a2) -> {
5576 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5577 if (compareRes == 0) {
5578 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5579 .getLastUpdateDate());
5583 if (latestArtifact == null) {
5584 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5585 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5588 if (errorWrapper.isEmpty()) {
5589 artifactId = latestArtifact.getUniqueId();
5594 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5596 Component component = null;
5597 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5598 if (getUserRes.isRight()) {
5599 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5602 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5604 if (errorWrapper.isEmpty()) {
5605 User modifier = getUserRes.left().value();
5606 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5607 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5608 if (checkoutRes.isRight()) {
5609 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5610 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5611 errorWrapper.setInnerElement(checkoutRes.right().value());
5614 component = checkoutRes.left().value();
5620 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5621 Map<String, Object> json = new HashMap<>();
5622 String artifactName = artifact.getArtifactName();
5623 json.put(Constants.ARTIFACT_NAME, artifactName);
5624 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5625 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5626 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5627 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5628 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5629 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5630 return gson.toJson(json);
5634 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5635 this.nodeTemplateOperation = nodeTemplateOperation;