2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.function.Predicate;
37 import java.util.function.Supplier;
38 import java.util.stream.Collectors;
40 import javax.servlet.http.HttpServletRequest;
42 import org.apache.commons.codec.binary.Base64;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.apache.commons.collections.MapUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
47 import org.openecomp.sdc.be.components.ArtifactsResolver;
48 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
49 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
52 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
55 import org.openecomp.sdc.be.config.ConfigurationManager;
56 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
59 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
60 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
61 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
62 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
67 import org.openecomp.sdc.be.model.ArtifactDefinition;
68 import org.openecomp.sdc.be.model.ArtifactType;
69 import org.openecomp.sdc.be.model.Component;
70 import org.openecomp.sdc.be.model.ComponentInstance;
71 import org.openecomp.sdc.be.model.ComponentParametersView;
72 import org.openecomp.sdc.be.model.GroupDefinition;
73 import org.openecomp.sdc.be.model.GroupInstance;
74 import org.openecomp.sdc.be.model.HeatParameterDefinition;
75 import org.openecomp.sdc.be.model.InterfaceDefinition;
76 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
77 import org.openecomp.sdc.be.model.LifecycleStateEnum;
78 import org.openecomp.sdc.be.model.Operation;
79 import org.openecomp.sdc.be.model.Resource;
80 import org.openecomp.sdc.be.model.Service;
81 import org.openecomp.sdc.be.model.User;
82 import org.openecomp.sdc.be.model.heat.HeatParameterType;
83 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
84 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
85 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
86 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
87 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
88 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
89 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
90 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
91 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
92 import org.openecomp.sdc.be.resources.data.ESArtifactData;
93 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
94 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
95 import org.openecomp.sdc.be.servlets.RepresentationUtils;
96 import org.openecomp.sdc.be.tosca.CsarUtils;
97 import org.openecomp.sdc.be.tosca.ToscaError;
98 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
99 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
100 import org.openecomp.sdc.be.user.IUserBusinessLogic;
101 import org.openecomp.sdc.be.user.Role;
102 import org.openecomp.sdc.be.user.UserBusinessLogic;
103 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
104 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
105 import org.openecomp.sdc.common.api.Constants;
106 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
107 import org.openecomp.sdc.common.datastructure.Wrapper;
108 import org.openecomp.sdc.common.util.GeneralUtility;
109 import org.openecomp.sdc.common.util.ValidationUtils;
110 import org.openecomp.sdc.common.util.YamlToObjectConverter;
111 import org.openecomp.sdc.exception.ResponseFormat;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
114 import org.springframework.beans.factory.annotation.Autowired;
115 import org.xml.sax.InputSource;
116 import org.xml.sax.SAXException;
117 import org.xml.sax.SAXNotRecognizedException;
118 import org.xml.sax.SAXNotSupportedException;
119 import org.xml.sax.XMLReader;
120 import org.yaml.snakeyaml.Yaml;
122 import com.google.gson.Gson;
123 import com.google.gson.GsonBuilder;
125 import javax.xml.parsers.ParserConfigurationException;
126 import javax.xml.parsers.SAXParser;
127 import javax.xml.parsers.SAXParserFactory;
129 import fj.data.Either;
131 @org.springframework.stereotype.Component("artifactBusinessLogic")
132 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
133 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
134 private static final String ARTIFACT_DESCRIPTION = "artifact description";
135 private static final String ARTIFACT_LABEL = "artifact label";
136 private static final String ARTIFACT_URL = "artifact url";
137 private static final String ARTIFACT_NAME = "artifact name";
138 private static final String ARTIFACT_PAYLOAD = "artifact payload";
140 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
141 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
142 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
144 public static final String HEAT_ENV_NAME = "heatEnv";
145 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
146 public static final String HEAT_ENV_SUFFIX = "env";
147 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
149 // private static Integer defaultHeatTimeout;
150 // private static final Integer NON_HEAT_TIMEOUT = 0;
151 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
152 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
153 private static XMLReader parser;
154 @javax.annotation.Resource
155 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
156 @javax.annotation.Resource
157 private IUserAdminOperation userOperaton;
159 @javax.annotation.Resource
160 private IElementOperation elementOperation;
162 @javax.annotation.Resource
163 private ResourceBusinessLogic resourceBusinessLogic;
165 @javax.annotation.Resource
166 private ServiceBusinessLogic serviceBusinessLogic;
168 @javax.annotation.Resource
169 private UserBusinessLogic userAdminManager;
171 @javax.annotation.Resource
172 private IHeatParametersOperation heatParametersOperation;
175 private ArtifactCassandraDao artifactCassandraDao;
178 private ToscaExportHandler toscaExportUtils;
181 private CsarUtils csarUtils;
184 private LifecycleBusinessLogic lifecycleBusinessLogic;
187 private IUserBusinessLogic userBusinessLogic;
189 NodeTemplateOperation nodeTemplateOperation;
192 private ArtifactsResolver artifactsResolver;
194 public ArtifactsBusinessLogic() {
195 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
196 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
197 // defaultHeatTimeout = 60;
201 public static enum ArtifactOperationEnum {
202 Create(), Update(), Delete(), Download(), Link();
204 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
205 return (operation.equals(Create) || operation.equals(Link));
210 //SAX XML Parser initialization
212 SAXParserFactory spf = SAXParserFactory.newInstance();
213 SAXParser newSAXParser = null;
216 newSAXParser = spf.newSAXParser();
217 parser = newSAXParser.getXMLReader();
218 } catch (ParserConfigurationException | SAXException e1) {
219 log.debug("SAX XML Parser could not been initialized", e1);
223 parser.setFeature("http://apache.org/xml/features/validation/schema", false);
224 } catch (SAXNotRecognizedException e) {
225 log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
227 } catch (SAXNotSupportedException e) {
228 log.debug("SAX Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
233 public class ArtifactOperationInfo {
235 private ArtifactOperationEnum artifactOperationEnum;
236 private boolean isExternalApi;
237 private boolean ignoreLifecycleState;
239 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
240 this.artifactOperationEnum = artifactOperationEnum;
241 this.isExternalApi = isExternalApi;
242 this.ignoreLifecycleState = ignoreLifecycleState;
245 public boolean isExternalApi() {
246 return isExternalApi;
249 public boolean ignoreLifecycleState() {
250 return ignoreLifecycleState;
253 public ArtifactOperationEnum getArtifactOperationEnum() {
254 return artifactOperationEnum;
260 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
261 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
262 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
265 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
266 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
268 // step 1 - detect auditing type
269 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
270 // step 2 - check header
271 if (userId == null) {
272 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
273 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
274 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
275 return Either.right(responseFormat);
277 // step 3 - check user existence
278 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
279 if (userResult.isRight()) {
280 return Either.right(userResult.right().value());
283 // step 4 - check user's role
284 User user = userResult.left().value();
285 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
286 if (validateUserRole.isRight()) {
287 return Either.right(validateUserRole.right().value());
291 // 5. check service/resource existence
292 // 6. check service/resource check out
293 // 7. user is owner of checkout state
294 org.openecomp.sdc.be.model.Component component = null;
295 // ComponentInstance resourceInstance = null;
296 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
297 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
298 if (validateComponent.isRight()) {
299 return Either.right(validateComponent.right().value());
301 component = validateComponent.left().value();
302 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
303 if (validateWorkOnResource.isRight()) {
304 return Either.right(validateWorkOnResource.right().value());
307 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
308 shouldLock, inTransaction, true);
314 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
315 * For regular usage use <br>
316 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
320 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
321 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
322 Component parent = component;
323 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
325 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
326 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
328 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
329 if (errorWrapper.isEmpty()) {
331 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
333 result = Either.right(errorWrapper.getInnerElement());
338 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
339 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
340 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
341 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
342 if (validateArtifact.isRight()) {
343 ResponseFormat responseFormat = validateArtifact.right().value();
344 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
345 errorWrapper.setInnerElement(validateArtifact.right().value());
347 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
348 artifactInfo = validateArtifact.left().value();
349 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
356 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
357 Wrapper<ResponseFormat> errorWrapper) {
358 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
360 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
361 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
362 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
363 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
365 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
366 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
367 if (eitherGenerated.isRight()) {
368 errorWrapper.setInnerElement(eitherGenerated.right().value());
374 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
375 boolean needGenerate;
376 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
377 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
381 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
382 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
385 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
386 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
388 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
389 if (generated.isRight()) {
392 byte[] decodedPayload = artifactDefinition.getPayloadData();
393 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
394 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
395 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
396 shouldLock, inTransaction);
400 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
401 log.debug("tosca artifact generation");
402 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
403 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
405 if (generated.isRight()) {
406 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
408 return Either.right(generated.right().value());
410 byte[] value = generated.left().value();
411 artifactInfo.setPayload(value);
414 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
415 if (exportComponent.isRight()) {
416 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
417 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
418 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
419 return Either.right(responseFormat);
421 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
422 String payload = exportComponent.left().value().getMainYaml();
423 artifactInfo.setPayloadData(payload);
425 return Either.left(Either.left(artifactInfo));
428 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
429 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
430 if (interfaceName != null && operationName != null) {
431 interfaceName = interfaceName.toLowerCase();
432 operationName = operationName.toLowerCase();
434 switch (operation.getArtifactOperationEnum()) {
436 if (artifactGenerationRequired(parent, artifactInfo)) {
437 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
439 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
441 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
443 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
444 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
445 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
446 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
447 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
448 if (needUpdateGroup && result.isLeft()) {
449 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
450 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
451 if (error != ActionStatus.OK) {
452 result = Either.right(componentsUtils.getResponseFormat(error));
456 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
457 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
460 if (result == null) {
461 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
462 if (needUpdateGroup && result.isLeft()) {
463 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
465 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
466 if (error != ActionStatus.OK) {
467 result = Either.right(componentsUtils.getResponseFormat(error));
473 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
475 return handleLink(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
480 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
481 List<GroupDefinition> groups = parent.getGroups();
482 if (groups != null && !groups.isEmpty()) {
483 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
484 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
485 groupToUpdate.forEach(g -> {
486 g.getArtifacts().remove(artifactInfo.getUniqueId());
487 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
488 g.getArtifacts().add(artAfterUpdate.getUniqueId());
489 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
491 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
492 if (status.isRight()) {
493 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
494 return componentsUtils.convertFromStorageResponse(status.right().value());
498 return ActionStatus.OK;
501 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
502 List<GroupDefinition> groups = parent.getGroups();
503 if (groups != null && !groups.isEmpty()) {
504 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
505 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
506 groupToUpdate.forEach(g -> {
507 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
508 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
509 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
510 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
511 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
512 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
514 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
515 if (status.isRight()) {
516 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
517 return componentsUtils.convertFromStorageResponse(status.right().value());
521 return ActionStatus.OK;
524 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
525 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
526 List<GroupInstance> groupInstances = null;
527 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
528 if (componentInstOp.isPresent()) {
529 groupInstances = componentInstOp.get().getGroupInstances();
531 if (CollectionUtils.isNotEmpty(groupInstances)) {
532 boolean isUpdated = false;
533 for (GroupInstance groupInstance : groupInstances) {
535 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
536 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
537 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
540 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
541 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
542 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
546 updatedGroupInstances.add(groupInstance);
550 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
551 if (status.isRight()) {
552 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
553 return componentsUtils.convertFromStorageResponse(status.right().value());
555 return ActionStatus.OK;
558 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
559 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
560 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
561 result = generateToscaArtifact(parent, artifactInfo, false, false);
563 String heatArtifactId = artifactInfo.getGeneratedFromId();
564 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
565 if (heatRes.isRight()) {
566 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
567 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
568 return Either.right(responseFormat);
570 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
571 artifactInfo.setPayloadData(generatedPayload);
572 result = Either.left(Either.left(artifactInfo));
577 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
578 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
579 convertParentType(componentType);
580 String parentId = parent.getUniqueId();
581 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
582 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
584 if (origMd5 != null) {
585 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
586 if (validateMd5.isRight()) {
587 ResponseFormat responseFormat = validateMd5.right().value();
588 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
589 return Either.right(responseFormat);
592 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
594 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
595 if (payloadEither.isRight()) {
596 ResponseFormat responseFormat = payloadEither.right().value();
597 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
598 return Either.right(responseFormat);
600 } else { // duplicate
601 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
602 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
603 return Either.right(responseFormat);
609 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
610 if (lockComponent.isRight()) {
611 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
612 return Either.right(lockComponent.right().value());
615 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
617 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
622 if (resultOp == null || resultOp.isRight()) {
623 log.debug("all changes rollback");
624 if (false == inTransaction)
627 log.debug("all changes committed");
628 if (false == inTransaction)
632 componentType = parent.getComponentType();
633 NodeTypeEnum nodeType = componentType.getNodeType();
634 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
635 // graphLockOperation.unlockComponent(parentId, parentType);
639 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
640 if (artifactGenerationRequired(component, csarArtifact)) {
641 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
643 if (generated.isRight()) {
644 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
646 return Either.right(generated.right().value());
648 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
650 return downloadArtifact(csarArtifact, component);
653 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
654 // perform all validation in common flow
655 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
656 null, parentId, containerComponentType);
657 if (result.isRight()) {
658 return Either.right(result.right().value());
660 ArtifactDefinition artifactDefinition;
661 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
662 if (insideValue.isLeft()) {
663 artifactDefinition = insideValue.left().value();
665 artifactDefinition = insideValue.right().value().getImplementationArtifact();
667 // for tosca artifacts and heat env on VF level generated on download without saving
668 if (artifactDefinition.getPayloadData() != null) {
669 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
671 return downloadArtifact(artifactDefinition, null);
674 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
676 // detect auditing type
677 Map<String, ArtifactDefinition> resMap = null;
678 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
683 if (userId == null) {
684 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
685 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
687 resultOp = Either.right(responseFormat);
691 // check user existence
695 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
696 if (userResult.isRight()) {
698 resultOp = Either.right(userResult.right().value());
702 userResult.left().value();
705 // 5. check service/resource existence
706 // 6. check service/resource check out
707 // 7. user is owner of checkout state
708 org.openecomp.sdc.be.model.Component component = null;
709 // ComponentInstance resourceInstance = null;
710 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
711 ComponentParametersView componentFilter = new ComponentParametersView();
712 componentFilter.disableAll();
713 componentFilter.setIgnoreArtifacts(false);
714 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
715 componentFilter.setIgnoreComponentInstances(false);
717 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
719 if (validateComponent.isRight()) {
720 resultOp = Either.right(validateComponent.right().value());
723 component = validateComponent.left().value();
724 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
725 if (lockComponent.isRight()) {
727 resultOp = Either.right(lockComponent.right().value());
732 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
734 if (groupType == null) {
735 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
736 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
738 resultOp = Either.right(responseFormat);
742 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
743 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
744 if (list != null && !list.isEmpty()) {
745 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
747 resMap = new HashMap<>();
749 resultOp = Either.left(resMap);
753 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
754 if (artifactsMapStatus.isRight()) {
755 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
756 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
757 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
758 resultOp = Either.right(responseFormat);
760 resMap = new HashMap<>();
761 resultOp = Either.left(resMap);
764 resMap = artifactsMapStatus.left().value();
765 resultOp = Either.left(resMap);
771 if (resultOp == null || resultOp.isRight()) {
772 log.debug("all changes rollback");
775 log.debug("all changes committed");
780 componentType = component.getComponentType();
781 NodeTypeEnum nodeType = componentType.getNodeType();
782 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
783 // graphLockOperation.unlockComponent(parentId, parentType);
788 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
789 boolean inTransaction) {
791 // check artifact existence
792 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
793 if (artifactResult.isRight()) {
794 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
795 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
796 log.debug("addArtifact - artifact {} not found", artifactId);
797 return Either.right(responseFormat);
800 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
801 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
802 return Either.right(responseFormat);
806 // check artifact belong to component
807 boolean found = false;
808 switch (componentType) {
811 found = checkArtifactInComponent(component, artifactId);
813 case RESOURCE_INSTANCE:
814 found = checkArtifactInResourceInstance(component, componentId, artifactId);
820 // String component =
821 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
823 String componentName = componentType.name().toLowerCase();
824 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
825 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
826 return Either.right(responseFormat);
828 return Either.left(artifactResult.left().value());
831 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
832 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
834 String artifactId = null;
837 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
838 if (payloadEither.isRight()) {
839 return Either.right(payloadEither.right().value());
841 byte[] decodedPayload = payloadEither.left().value();
842 convertParentType(componentType);
845 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
846 if (lockComponent.isRight()) {
847 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
848 return Either.right(lockComponent.right().value());
851 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
854 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
858 unlockComponent(resultOp, parent, inTransaction);
865 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(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) {
869 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
870 if (lockComponent.isRight()) {
871 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
872 return Either.right(lockComponent.right().value());
875 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
878 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
882 unlockComponent(resultOp, parent, inTransaction);
889 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
890 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
892 convertParentType(componentType);
896 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
898 if (lockComponent.isRight()) {
899 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
900 return Either.right(lockComponent.right().value());
904 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
906 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
911 unlockComponent(resultOp, parent, inTransaction);
916 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
917 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
919 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
921 if (payloadEither.isRight()) {
922 return Either.right(payloadEither.right().value());
924 byte[] decodedPayload = payloadEither.left().value();
926 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
929 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
930 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
932 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
933 if (validateMd5.isRight()) {
934 ResponseFormat responseFormat = validateMd5.right().value();
935 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
936 return Either.right(responseFormat);
940 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
941 if (validateResult.isRight()) {
942 ResponseFormat responseFormat = validateResult.right().value();
943 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
944 return Either.right(validateResult.right().value());
947 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
948 if (payloadEither.isRight()) {
949 ResponseFormat responseFormat = payloadEither.right().value();
950 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
951 log.debug("Error during handle payload");
952 return Either.right(responseFormat);
955 // validate heat parameters. this part must be after the parameters are
956 // extracted in "handlePayload"
957 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
958 if (validateAndConvertHeatParamers.isRight()) {
959 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
960 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
961 log.debug("Error during handle payload");
962 return Either.right(responseFormat);
964 return payloadEither;
967 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
968 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
970 if (auditingActionEnum != null && auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
974 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
978 user.setUserId("UNKNOWN");
980 switch (componentTypeEnum) {
983 Resource resource = (Resource) component;
984 if (resource == null) {
985 // In that case, component ID should be instead of name
986 resource = new Resource();
987 resource.setName(componentId);
989 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
993 Service service = (Service) component;
994 if (service == null) {
995 // In that case, component ID should be instead of name
996 service = new Service();
997 service.setName(componentId);
999 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
1002 case RESOURCE_INSTANCE:
1003 if (resourceInstanceName == null) {
1004 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1006 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
1007 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
1015 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1016 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
1017 String resourceInstanceName = null;
1018 if (resourceInstance != null) {
1019 resourceInstanceName = resourceInstance.getName();
1021 return resourceInstanceName;
1024 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
1025 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
1026 // Putting together artifact info
1027 String artifactData = buildAuditingArtifactData(artifactDefinition);
1028 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
1029 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
1030 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
1031 return auditingFields;
1036 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1037 StringBuilder sb = new StringBuilder();
1038 if (artifactDefinition != null) {
1039 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
1040 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
1043 if (artifactDefinition.getArtifactVersion() != null) {
1045 sb.append(artifactDefinition.getArtifactVersion());
1050 if (artifactDefinition.getArtifactUUID() != null) {
1051 sb.append(artifactDefinition.getArtifactUUID());
1056 return sb.toString();
1059 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1061 if (origMd5 != null) {
1062 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1064 if (false == encodeBase64Str.equals(origMd5)) {
1065 log.debug("The calculated md5 is different then the received one");
1066 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1069 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1070 if (payload!=null && payload.length != 0) {
1071 log.debug("Missing md5 header during artifact create");
1072 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1076 if (payload != null && payload.length != 0) {
1077 log.debug("Cannot have payload while md5 header is missing");
1078 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1081 return Either.left(true);
1084 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1085 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1087 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1088 if (artifactById.isRight()) {
1089 return Either.right(artifactById.right().value());
1091 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1093 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1094 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1095 if (validateInformationalArtifactRes.isRight()) {
1096 return Either.right(validateInformationalArtifactRes.right().value());
1098 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1099 if (validateAndSetArtifactname.isRight()) {
1100 return Either.right(validateAndSetArtifactname.right().value());
1102 if (operationName != null && interfaceName != null) {
1103 operationName = operationName.toLowerCase();
1104 interfaceName = interfaceName.toLowerCase();
1106 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
1107 if (logicalNameStatus.isRight()) {
1108 return Either.right(logicalNameStatus.right().value());
1110 // This is a patch to block possibility of updating service api fields
1111 // through other artifacts flow
1113 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1114 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1116 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1119 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1120 if (currentArtifactInfo != null) {
1121 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1124 // artifactGroupType is not allowed to be updated
1125 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1126 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1127 if (validateGroupType.isRight()) {
1128 return Either.right(validateGroupType.right().value());
1132 NodeTypeEnum parentType = convertParentType(componentType);
1135 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1137 if (isDeploymentArtifact(artifactInfo)) {
1138 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1139 if (deploymentValidationResult.isRight()) {
1140 return Either.right(deploymentValidationResult.right().value());
1143 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1146 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1147 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1151 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1152 if (descriptionResult.isRight()) {
1153 return Either.right(descriptionResult.right().value());
1156 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1157 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1158 if (validateServiceApiType.isRight()) {
1159 return Either.right(validateServiceApiType.right().value());
1161 // Change of type is not allowed and should be ignored
1163 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1165 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1166 if (validateUrl.isRight()) {
1167 return Either.right(validateUrl.right().value());
1170 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1171 if (validateUpdate.isRight()) {
1172 log.debug("serviceApi first update cnnot be without payload.");
1173 return Either.right(validateUpdate.right().value());
1176 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1177 if (validateArtifactType.isRight()) {
1178 return Either.right(validateArtifactType.right().value());
1180 if (artifactInfo.getApiUrl() != null) {
1181 artifactInfo.setApiUrl(null);
1182 log.error("Artifact URL cannot be set through this API - ignoring");
1185 if (artifactInfo.getServiceApi() != null) {
1186 if (artifactInfo.getServiceApi()) {
1187 artifactInfo.setServiceApi(false);
1188 log.error("Artifact service API flag cannot be changed - ignoring");
1193 return Either.left(artifactInfo);
1196 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1197 if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
1198 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1199 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1200 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1204 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1206 Either<ArtifactDefinition, ResponseFormat> result = null;
1207 ArtifactDefinition foundArtifact = null;
1208 if (StringUtils.isNotEmpty(artifactId)) {
1209 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1211 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1212 log.debug("Artifact {} already exist", artifactId);
1213 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1215 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1216 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1217 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1219 if (result == null) {
1220 result = Either.left(foundArtifact);
1225 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1226 ArtifactDefinition foundArtifact;
1227 if (parentComponent.getUniqueId().equals(parentId)) {
1228 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1230 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1231 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1233 return foundArtifact;
1236 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1237 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1238 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1239 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1240 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1241 if (artifactType == null) {
1242 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1243 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1244 String artifactTypeName = artifactType.getType();
1245 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1246 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1247 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1248 if (!validArtifactTypes.contains(artifactTypeName)) {
1249 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1251 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1252 if (!validResourceType.contains(parentResourceType.name())) {
1253 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1257 return validationResult;
1260 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1261 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1262 return NodeTypeEnum.Resource;
1263 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1264 return NodeTypeEnum.ResourceInstance;
1266 return NodeTypeEnum.Service;
1270 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1271 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1273 NodeTypeEnum parentType = convertParentType(componentType);
1274 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1275 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1276 ArtifactDefinition foundArtifact = null;
1277 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1278 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1279 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1280 boolean isDuplicated = false;
1282 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1285 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1286 if (lockComponent.isRight()) {
1287 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1288 resultOp = Either.right(lockComponent.right().value());
1291 if (resultOp == null) {
1292 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1293 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1294 if (getContainerRes.isRight()) {
1295 log.debug("Failed to fetch the container component {}. ", parentId);
1296 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1297 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1298 resultOp = Either.right(responseFormat);
1301 if (resultOp == null) {
1302 fetchedContainerComponent = getContainerRes.left().value();
1303 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1304 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1305 if (getArtifactRes.isRight()) {
1306 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1307 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1308 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1309 resultOp = Either.right(responseFormat);
1311 foundArtifact = getArtifactRes.left().value().getLeft();
1312 esId = foundArtifact.getEsId();
1315 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1316 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1317 if (needCloneRes.isRight()) {
1318 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1319 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1320 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1321 resultOp = Either.right(responseFormat);
1324 boolean isNeedToDeleteArtifactFromDB = true;
1325 if (resultOp == null) {
1327 if(componentType == ComponentTypeEnum.RESOURCE_INSTANCE){
1328 String instanceId = parentId;
1329 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1331 if (isOnlyResourceInstanceArtifact.isRight()) {
1332 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1333 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right().value(), foundArtifact.getArtifactDisplayName());
1334 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1335 resultOp = Either.right(responseFormat);
1337 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1340 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1341 if (updatedArtifactRes.isRight()) {
1342 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1343 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1344 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1345 resultOp = Either.right(responseFormat);
1347 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1351 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1353 if(isNeedToDeleteArtifactFromDB){
1354 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1355 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1356 if (cassandraStatus != CassandraOperationStatus.OK) {
1357 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1358 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1359 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1360 resultOp = Either.right(responseFormat);
1364 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1366 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1367 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1368 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1369 if (status.isRight()) {
1370 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1371 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1372 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1373 resultOp = Either.right(responseFormat);
1377 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1378 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1379 if (status != StorageOperationStatus.OK) {
1380 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1381 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1382 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1383 resultOp = Either.right(responseFormat);
1386 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1387 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1388 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1389 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1390 if (status.isRight()) {
1391 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1392 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1393 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1394 resultOp = Either.right(responseFormat);
1398 if (resultOp == null) {
1399 resultOp = Either.left(Either.left(foundArtifact));
1400 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1405 unlockComponent(resultOp, parent, inTransaction);
1410 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact( ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1411 Either<Boolean, ActionStatus> result = Either.left(true);
1412 ComponentInstance foundInstance = null;
1413 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1414 if (!componentInstanceOpt.isPresent()) {
1415 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1417 foundInstance = componentInstanceOpt.get();
1418 String componentUid = foundInstance.getComponentUid();
1419 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1420 if (getContainerRes.isRight()) {
1421 log.debug("Failed to fetch the container component {}. ", componentUid);
1422 result = Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1424 Component origComponent = getContainerRes.left().value();
1425 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1426 if( deploymentArtifacts!= null && !deploymentArtifacts.isEmpty()){
1427 Optional<String> op = deploymentArtifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
1429 return Either.left(false);
1432 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1433 if( artifacts!= null && !artifacts.isEmpty()){
1434 Optional<String> op = artifacts.keySet().stream().filter(a -> a.equals(foundArtifact.getArtifactLabel())).findAny();
1436 return Either.left(false);
1444 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1445 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1446 boolean isUpdated = false;
1447 if (groups != null) {
1448 for (GroupDefinition group : groups) {
1450 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1451 group.getArtifacts().remove(artifactId);
1454 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1455 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1459 updatedGroups.add(group);
1463 return updatedGroups;
1466 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1467 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1468 if (CollectionUtils.isNotEmpty(groupInstances)) {
1469 boolean isUpdated = false;
1470 for (GroupInstance groupInstance : groupInstances) {
1472 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1473 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1476 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1477 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1481 updatedGroupInstances.add(groupInstance);
1485 return updatedGroupInstances;
1488 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1490 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1491 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1492 String componentId = component.getUniqueId();
1493 String instanceId = componentId.equals(parentId) ? null : parentId;
1495 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1496 resetMandatoryArtifactFields(foundArtifact);
1497 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1498 } else if (cloneIsNeeded) {
1499 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1500 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1502 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1503 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1508 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1510 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1511 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1512 ComponentInstance foundInstance = null;
1513 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1514 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1515 if (!componentInstanceOpt.isPresent()) {
1516 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1518 foundInstance = componentInstanceOpt.get();
1519 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1522 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1524 if (result == null) {
1525 if (artifacts.containsKey(artifactId)) {
1526 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1528 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1534 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1535 Map<String, ArtifactDefinition> currArtifacts;
1536 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1537 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1538 if (MapUtils.isNotEmpty(currArtifacts)) {
1539 artifacts.putAll(currArtifacts);
1542 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1543 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1544 if (MapUtils.isNotEmpty(currArtifacts)) {
1545 artifacts.putAll(currArtifacts);
1548 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1549 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1550 if (MapUtils.isNotEmpty(currArtifacts)) {
1551 artifacts.putAll(currArtifacts);
1556 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1557 Map<String, ArtifactDefinition> currArtifacts;
1558 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1559 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1560 if (MapUtils.isNotEmpty(currArtifacts)) {
1561 artifacts.putAll(currArtifacts);
1564 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1565 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1566 if (MapUtils.isNotEmpty(currArtifacts)) {
1567 artifacts.putAll(currArtifacts);
1572 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1573 StorageOperationStatus result;
1574 switch (cassandraStatus) {
1576 result = StorageOperationStatus.OK;
1579 result = StorageOperationStatus.NOT_FOUND;
1581 case CLUSTER_NOT_CONNECTED:
1582 case KEYSPACE_NOT_CONNECTED:
1583 result = StorageOperationStatus.CONNECTION_FAILURE;
1586 result = StorageOperationStatus.GENERAL_ERROR;
1592 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1593 if (fetchedArtifact != null) {
1594 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1595 fetchedArtifact.setEsId(null);
1596 fetchedArtifact.setArtifactName(null);
1597 fetchedArtifact.setDescription(null);
1598 fetchedArtifact.setApiUrl(null);
1599 fetchedArtifact.setArtifactChecksum(null);
1600 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1601 fetchedArtifact.setArtifactUUID(null);
1602 long time = System.currentTimeMillis();
1603 fetchedArtifact.setPayloadUpdateDate(time);
1604 fetchedArtifact.setHeatParameters(null);
1605 fetchedArtifact.setHeatParamsUpdateDate(null);
1609 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1610 StorageOperationStatus error = StorageOperationStatus.OK;
1611 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1612 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1613 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1618 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1619 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1620 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1621 if (artifactById.isRight()) {
1622 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1623 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1624 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1625 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1626 return Either.right(responseFormat);
1628 ArtifactDefinition artifactDefinition = artifactById.left().value();
1629 if (artifactDefinition == null) {
1630 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1631 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1632 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1633 return Either.right(responseFormat);
1636 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1637 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1638 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1639 return Either.left(insideEither);
1642 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1643 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1644 if (!(ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) && artifactById.isRight()) {
1645 // in case of update artifact must be
1646 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1647 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1648 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1650 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && artifactById.isLeft()) {
1651 log.debug("Artifact {} already exist", artifactId);
1652 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1654 ArtifactDefinition currentArtifactInfo = null;
1655 if (artifactById.isLeft()) {
1656 // get previous value
1657 currentArtifactInfo = artifactById.left().value();
1659 return Either.left(currentArtifactInfo);
1662 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1663 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
1665 String artifactLabel = artifactInfo.getArtifactLabel();
1666 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1667 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1668 log.debug("missing artifact logical name for component {}", componentId);
1669 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1671 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1673 if (operationName != null) {
1674 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1675 log.debug("artifact label cannot be set {}", artifactLabel);
1676 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1678 artifactLabel = operationName;
1681 String displayName = artifactInfo.getArtifactDisplayName();
1682 if (displayName == null || displayName.isEmpty())
1683 displayName = artifactLabel;
1684 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1685 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1686 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1687 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1689 artifactInfo.setArtifactDisplayName(displayName);
1691 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1692 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1693 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1695 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1697 if (artifactLabel.isEmpty()) {
1698 log.debug("missing normalized artifact logical name for component {}", componentId);
1699 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1702 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1703 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1704 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1706 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1707 log.debug("Non unique Artifact label : {}", artifactLabel);
1708 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1711 artifactInfo.setArtifactLabel(artifactLabel);
1713 return Either.left(ActionStatus.OK);
1716 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1717 boolean isUnique = true;
1718 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1719 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1720 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1722 artifacts = artifactToscaOperation.getArtifacts(componentId);
1725 if (artifacts.isLeft()) {
1726 for (String label : artifacts.left().value().keySet()) {
1727 if (label.equals(artifactLabel)) {
1733 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1734 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
1735 if (allInterfacesOfResource.isLeft()) {
1736 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1737 for (Operation operation : interace.getOperationsMap().values()) {
1738 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1749 // ***************************************************************
1751 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1752 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1753 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1754 Either<ArtifactDefinition, Operation> insideEither = null;
1755 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1756 String instanceId = null;
1757 String instanceName = null;
1758 if (foundInstance != null) {
1759 instanceId = foundInstance.getUniqueId();
1760 instanceName = foundInstance.getName();
1762 boolean isLeft = false;
1763 String artifactUniqueId = null;
1764 StorageOperationStatus error = null;
1765 // information/deployment/api aritfacts
1766 log.trace("Try to create entry on graph");
1767 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1768 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1770 isLeft = result.isLeft();
1772 artifactUniqueId = result.left().value().getUniqueId();
1773 result.left().value();
1775 insideEither = Either.left(result.left().value());
1776 resultOp = Either.left(insideEither);
1778 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1779 if (error != StorageOperationStatus.OK) {
1784 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1785 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1788 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1789 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1790 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1791 resultOp = Either.right(responseFormat);
1797 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1798 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1800 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1801 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1802 Either<ArtifactDefinition, Operation> insideEither = null;
1803 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1804 String instanceId = null;
1805 String instanceName = null;
1806 if (foundInstance != null) {
1807 instanceId = foundInstance.getUniqueId();
1808 instanceName = foundInstance.getName();
1810 if (artifactData == null) {
1811 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1812 log.debug("Failed to create artifact object for ES.");
1813 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1814 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1815 resultOp = Either.right(responseFormat);
1819 // set on graph object id of artifact in ES!
1820 artifactInfo.setEsId(artifactData.getId());
1822 boolean isLeft = false;
1823 String artifactUniqueId = null;
1824 StorageOperationStatus error = null;
1825 if (interfaceType != null && operationName != null) {
1826 // lifecycle artifact
1827 Operation operation = convertToOperation(artifactInfo, operationName);
1829 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1831 isLeft = result.isLeft();
1833 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1834 result.left().value().getImplementation();
1836 insideEither = Either.right(result.left().value());
1837 resultOp = Either.left(insideEither);
1839 error = result.right().value();
1842 // information/deployment/api aritfacts
1843 log.trace("Try to create entry on graph");
1844 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1845 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1847 isLeft = result.isLeft();
1849 artifactUniqueId = result.left().value().getUniqueId();
1850 result.left().value();
1852 insideEither = Either.left(result.left().value());
1853 resultOp = Either.left(insideEither);
1855 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1856 if (error != StorageOperationStatus.OK) {
1861 error = result.right().value();
1865 boolean res = saveArtifacts(artifactData, parentId, false);
1866 // String uniqueId = artifactDefinition.getUniqueId();
1869 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1871 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1872 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1875 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1876 log.debug("Failed to save the artifact.");
1877 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1878 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1880 resultOp = Either.right(responseFormat);
1884 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1885 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1886 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1887 resultOp = Either.right(responseFormat);
1893 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1894 ComponentInstance foundInstance = null;
1895 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1896 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1898 return foundInstance;
1901 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1903 Either<Boolean, ResponseFormat> result = Either.left(true);
1904 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1906 validateArtifactTypeExists(responseWrapper, artifactInfo);
1908 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1910 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1912 if (responseWrapper.isEmpty()) {
1913 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1916 if (responseWrapper.isEmpty()) {
1917 // Common code for all types
1918 // not allowed to change artifactType
1920 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1921 if (validateServiceApiType.isRight()) {
1922 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1926 if (responseWrapper.isEmpty()) {
1927 if (parentType.equals(NodeTypeEnum.Resource)) {
1928 // if (parentComponent instanceof Resource) {
1929 Resource resource = (Resource) parentComponent;
1930 ResourceTypeEnum resourceType = resource.getResourceType();
1931 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1932 if (config == null) {
1933 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1935 List<String> myList = config.getValidForResourceTypes();
1936 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1937 if (either.isRight()) {
1938 responseWrapper.setInnerElement(either.right().value());
1943 if (responseWrapper.isEmpty()) {
1944 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1947 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1948 String artifactName = artifactInfo.getArtifactName();
1949 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1950 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1954 if (responseWrapper.isEmpty()) {
1955 switch (artifactType) {
1959 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1963 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1964 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1967 case DCAE_INVENTORY_TOSCA:
1968 case DCAE_INVENTORY_JSON:
1969 case DCAE_INVENTORY_POLICY:
1970 // Validation is done in handle payload.
1971 case DCAE_INVENTORY_DOC:
1972 case DCAE_INVENTORY_BLUEPRINT:
1973 case DCAE_INVENTORY_EVENT:
1974 // No specific validation
1976 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1982 if (!responseWrapper.isEmpty()) {
1983 result = Either.right(responseWrapper.getInnerElement());
1988 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1989 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1990 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1991 responseWrapper.setInnerElement(responseFormat);
1992 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1996 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1997 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1998 if (parentType.equals(NodeTypeEnum.Resource)) {
1999 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2000 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2001 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2003 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2005 return resourceDeploymentArtifacts;
2008 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2009 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2010 if (artifactType == null) {
2011 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
2012 responseWrapper.setInnerElement(responseFormat);
2013 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2017 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2018 ArtifactTypeConfig retConfig = null;
2019 String fileType = artifactType.getType();
2020 if (parentType.equals(NodeTypeEnum.Resource)) {
2021 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
2022 } else if (parentType.equals(NodeTypeEnum.Service)) {
2023 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
2024 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2025 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
2030 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2031 // extract heat parameters
2032 if (artifactInfo.getPayloadData() != null) {
2033 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2034 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
2035 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2036 log.info("failed to parse heat parameters ");
2037 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
2038 return Either.right(responseFormat);
2039 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2040 artifactInfo.setListHeatParameters(heatParameters.left().value());
2043 return Either.left(true);
2048 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2049 String fileType = artifactType.getType();
2050 List<String> acceptedTypes = null;
2051 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2052 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2053 log.debug("parent type of artifact can be either resource or service");
2054 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2058 if (deploymentAcceptedTypes == null) {
2059 log.debug("parent type of artifact can be either resource or service");
2060 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2063 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2066 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2068 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
2069 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
2070 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
2071 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
2074 String artifactName = artifactInfo.getArtifactName();
2075 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2076 // Pavel - File extension validation is case-insensitive - Ella,
2078 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2079 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2080 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2085 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2087 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
2088 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
2089 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2091 if (errorWrapper.isEmpty()) {
2092 validateValidYaml(errorWrapper, artifactInfo);
2095 if (errorWrapper.isEmpty()) {
2096 // Validate Heat Exist
2097 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
2100 // if (errorWrapper.isEmpty() && isCreate) {
2101 // // Validate Only Single HeatEnv Artifact
2102 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
2105 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2106 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2109 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2110 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2114 Either<Boolean, ResponseFormat> eitherResponse;
2115 if (errorWrapper.isEmpty()) {
2116 eitherResponse = Either.left(true);
2118 eitherResponse = Either.right(errorWrapper.getInnerElement());
2120 return eitherResponse;
2123 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2124 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2125 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2126 if (fillArtifactPayload.isRight()) {
2127 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2128 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2131 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2135 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2136 Either<Boolean, ResponseFormat> result = Either.left(true);
2137 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
2138 if (eitherArtifactData.isLeft()) {
2139 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2140 data = Base64.encodeBase64(data);
2141 payloadWrapper.setInnerElement(data);
2143 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
2144 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2145 result = Either.right(responseFormat);
2151 @SuppressWarnings("unchecked")
2152 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2153 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2154 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2155 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2156 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2158 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2159 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2160 if (eitherHeatEnvProperties.isRight()) {
2161 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2162 errorWrapper.setInnerElement(responseFormat);
2163 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2164 } else if (eitherHeatProperties.isRight()) {
2165 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2166 errorWrapper.setInnerElement(responseFormat);
2167 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2169 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2170 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2171 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2172 if (heatEnvPropertiesKeys.size() > 0) {
2173 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2174 errorWrapper.setInnerElement(responseFormat);
2179 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2180 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2181 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2183 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2184 errorWrapper.setInnerElement(responseFormat);
2185 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2189 public boolean isValidXml(byte[] xmlToParse) {
2190 if(parser == null) {
2191 log.debug("SAX XML Parser have not been initialized");
2194 boolean isXmlValid = true;
2197 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2198 } catch (IOException | SAXException e) {
2199 log.debug("Xml is invalid : {}", e.getMessage(), e);
2206 public boolean isValidJson(byte[] jsonToParse) {
2207 String parsed = new String(jsonToParse);
2209 gson.fromJson(parsed, Object.class);
2210 } catch (Exception e) {
2211 log.debug("Json is invalid : {}", e.getMessage(), e);
2217 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2218 boolean typeArtifactFound = false;
2219 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2220 // (parentType == NodeTypeEnum.Resource) ?
2221 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2222 // parentComponent).iterator()
2223 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2225 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2227 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2228 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2229 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2231 if (typeArtifactFound) {
2232 String parentName = parentComponent.getName();
2233 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2235 errorWrapper.setInnerElement(responseFormat);
2236 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2241 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2242 boolean artifactNameFound = false;
2243 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2244 // (parentType == NodeTypeEnum.Resource) ?
2245 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2246 // parentComponent).iterator()
2247 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2249 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2251 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2252 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2254 if (artifactNameFound) {
2255 String parentName = parentComponent.getName();
2256 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2258 errorWrapper.setInnerElement(responseFormat);
2259 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2264 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2265 ComponentTypeEnum componentType) {
2266 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2267 if (res.isRight()) {
2268 ResponseFormat responseFormat;
2269 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2270 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2272 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2274 errorWrapper.setInnerElement(responseFormat);
2278 ArtifactDefinition heatArtifact = res.left().value();
2279 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2280 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2281 // while (!heatFound && parentArtifactsItr.hasNext()) {
2282 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2283 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2284 // heatFound = true;
2285 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2286 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2288 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2289 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2293 // if (!heatFound) {
2294 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2295 // errorWrapper.setInnerElement(responseFormat);
2296 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2301 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2302 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2303 // timeout > 0 for HEAT artifacts
2304 Integer timeout = artifactInfo.getTimeout();
2305 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2306 if (timeout == null) {
2307 artifactInfo.setTimeout(defaultTimeout);
2308 // HEAT artifact but timeout is invalid
2309 } else if (timeout < 1) {
2310 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2313 // US649856 - Allow several HEAT files on Resource
2315 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2316 * Either.right(errorWrapper.getInnerElement()); } }
2319 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2320 return Either.left(true);
2323 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2324 String listToString = (typeList != null) ? typeList.toString() : "";
2325 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2326 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2327 String resourceTypeName = resourceType.name();
2328 if (typeList != null && typeList.contains(resourceTypeName)) {
2329 either = Either.left(true);
2334 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2335 if (artifactInfo.getHeatParameters() != null) {
2336 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2337 String parameterType = heatParam.getType();
2338 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2339 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2340 if (heatParameterType == null) {
2341 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2342 return Either.right(responseFormat);
2345 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2346 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2347 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2348 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2349 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2350 return Either.right(responseFormat);
2354 return Either.left(artifactInfo);
2357 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2358 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2359 if (parentComponent.getDeploymentArtifacts() != null) {
2360 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2361 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2362 if (getRI.isRight()) {
2363 return deploymentArtifacts;
2365 ComponentInstance ri = getRI.left().value();
2366 if (ri.getDeploymentArtifacts() != null) {
2367 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2369 } else if (parentComponent.getDeploymentArtifacts() != null) {
2370 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2373 return deploymentArtifacts;
2376 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2377 // on create if null add informational to current
2378 if (artifactInfo.getArtifactGroupType() == null) {
2379 artifactInfo.setArtifactGroupType(type);
2381 if (artifactInfo.getUniqueId() != null) {
2382 log.error("artifact uniqid cannot be set ignoring");
2384 artifactInfo.setUniqueId(null);
2386 if (artifactInfo.getArtifactRef() != null) {
2387 log.error("artifact ref cannot be set ignoring");
2389 artifactInfo.setArtifactRef(null);
2391 if (artifactInfo.getArtifactRepository() != null) {
2392 log.error("artifact repository cannot be set ignoring");
2394 artifactInfo.setArtifactRepository(null);
2396 if (artifactInfo.getUserIdCreator() != null) {
2397 log.error("creator uuid cannot be set ignoring");
2399 artifactInfo.setArtifactCreator(user.getUserId());
2401 if (artifactInfo.getUserIdLastUpdater() != null) {
2402 log.error("userId of last updater cannot be set ignoring");
2404 artifactInfo.setUserIdLastUpdater(user.getUserId());
2406 if (artifactInfo.getCreatorFullName() != null) {
2407 log.error("creator Full name cannot be set ignoring");
2409 String fullName = user.getFirstName() + " " + user.getLastName();
2410 artifactInfo.setUpdaterFullName(fullName);
2412 if (artifactInfo.getUpdaterFullName() != null) {
2413 log.error("updater Full name cannot be set ignoring");
2415 artifactInfo.setUpdaterFullName(fullName);
2417 if (artifactInfo.getCreationDate() != null) {
2418 log.error("Creation Date cannot be set ignoring");
2420 long time = System.currentTimeMillis();
2421 artifactInfo.setCreationDate(time);
2423 if (artifactInfo.getLastUpdateDate() != null) {
2424 log.error("Last Update Date cannot be set ignoring");
2426 artifactInfo.setLastUpdateDate(time);
2428 if (artifactInfo.getEsId() != null) {
2429 log.error("es id cannot be set ignoring");
2431 artifactInfo.setEsId(null);
2436 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2437 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2438 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2439 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2440 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2441 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2444 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2445 String id = artifactId;
2446 if (artifactId == null || artifactId.isEmpty()) {
2447 String uniqueId = null;
2448 if (interfaceName != null && operationName != null) {
2449 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2451 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2453 artifactInfo.setUniqueId(uniqueId);
2454 artifactInfo.setEsId(uniqueId);
2457 artifactInfo.setUniqueId(artifactId);
2458 artifactInfo.setEsId(artifactId);
2463 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2464 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2465 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2466 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2467 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2470 boolean artifactTypeExist = false;
2471 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2472 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2474 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2475 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2478 allArtifactTypes = elementOperation.getAllArtifactTypes();
2480 if (allArtifactTypes.isRight()) {
2481 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2482 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2483 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2486 for (ArtifactType type : allArtifactTypes.left().value()) {
2487 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2488 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2489 artifactTypeExist = true;
2494 if (!artifactTypeExist) {
2495 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2496 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2497 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2500 return Either.left(ActionStatus.OK);
2503 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2505 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2506 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2508 if (parentType.equals(NodeTypeEnum.Service)) {
2509 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2510 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2511 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2513 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2515 if (deploymentArtifacts != null) {
2516 for (String artifactType : deploymentArtifacts.keySet()) {
2517 ArtifactType artifactT = new ArtifactType();
2518 artifactT.setName(artifactType);
2519 artifactTypes.add(artifactT);
2521 return Either.left(artifactTypes);
2523 return Either.right(ActionStatus.GENERAL_ERROR);
2528 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2529 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2530 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2532 return Either.left(true);
2536 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2537 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2538 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2541 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2542 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2543 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2545 artifactInfo.setArtifactName(normalizeFileName);
2547 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2548 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2551 return Either.left(true);
2554 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2555 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2556 log.info("artifact type is missing operation ignored");
2557 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2560 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2561 log.info("artifact type cannot be changed operation ignored");
2562 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2564 return Either.left(true);
2567 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2568 if (artifactInfo.getArtifactGroupType() == null) {
2569 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2572 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2573 log.info("artifact group type cannot be changed. operation failed");
2574 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2576 return Either.left(artifactInfo);
2579 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2581 // on update if null add informational to current
2582 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2583 currentArtifact.setArtifactGroupType(type);
2586 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2587 log.error("artifact uniqid cannot be set ignoring");
2589 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2591 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2592 log.error("artifact ref cannot be set ignoring");
2594 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2596 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2597 log.error("artifact repository cannot be set ignoring");
2599 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2601 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2602 log.error("creator uuid cannot be set ignoring");
2604 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2606 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2607 log.error("artifact creator cannot be set ignoring");
2609 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2611 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2612 log.error("userId of last updater cannot be set ignoring");
2614 artifactInfo.setUserIdLastUpdater(user.getUserId());
2616 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2617 log.error("creator Full name cannot be set ignoring");
2619 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2621 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2622 log.error("updater Full name cannot be set ignoring");
2624 String fullName = user.getFirstName() + " " + user.getLastName();
2625 artifactInfo.setUpdaterFullName(fullName);
2627 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2628 log.error("Creation Date cannot be set ignoring");
2630 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2632 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2633 log.error("Last Update Date cannot be set ignoring");
2635 long time = System.currentTimeMillis();
2636 artifactInfo.setLastUpdateDate(time);
2638 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2639 log.error("es id cannot be set ignoring");
2641 artifactInfo.setEsId(currentArtifact.getUniqueId());
2643 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2644 log.error(" Artifact Display Name cannot be set ignoring");
2646 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2648 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2649 log.debug("serviceApi cannot be set. ignoring.");
2651 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2653 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2654 log.debug("artifact group cannot be set. ignoring.");
2656 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2658 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2660 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2661 log.debug("artifact UUID cannot be set. ignoring.");
2663 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2665 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2666 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2670 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2672 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2673 for (HeatParameterDefinition parameter : heatParameters) {
2674 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2676 if (currentParam != null) {
2678 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2679 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2680 parameter.setName(currentParam.getName());
2682 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2683 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2684 parameter.setDefaultValue(currentParam.getDefaultValue());
2686 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2687 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2688 parameter.setType(currentParam.getType());
2690 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2691 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2692 parameter.setDescription(currentParam.getDescription());
2695 // check and set current value
2696 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2697 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2698 parameter.setCurrentValue(currentParam.getDefaultValue());
2704 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2706 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2707 for (HeatParameterDefinition param : currentParameters) {
2708 currentParamsMap.put(param.getUniqueId(), param);
2710 return currentParamsMap;
2713 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2714 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2715 log.debug("Artifact url cannot be empty.");
2716 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2718 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2720 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2721 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2723 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2724 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2727 return Either.left(true);
2730 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2731 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2732 log.debug("Artifact description cannot be empty.");
2733 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2735 String description = artifactInfo.getDescription();
2736 description = ValidationUtils.removeNoneUtf8Chars(description);
2737 description = ValidationUtils.normaliseWhitespace(description);
2738 description = ValidationUtils.stripOctets(description);
2739 description = ValidationUtils.removeHtmlTagsOnly(description);
2740 if (!ValidationUtils.validateIsEnglish(description)) {
2741 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2743 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2744 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2746 artifactInfo.setDescription(description);
2747 return Either.left(true);
2750 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2751 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2752 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2753 String prevArtifactId = null;
2754 String currArtifactId = artifactId;
2756 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2757 Either<ArtifactDefinition, Operation> insideEither = null;
2759 if (artifactData == null) {
2760 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2761 log.debug("Failed to create artifact object for ES.");
2762 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2763 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2764 resultOp = Either.right(responseFormat);
2767 log.trace("Try to update entry on graph");
2768 String artifactUniqueId = null;
2769 ArtifactDefinition artifactDefinition = artifactInfo;
2770 StorageOperationStatus error = null;
2772 boolean isLeft = false;
2773 if (interfaceType != null && operationName != null) {
2774 // lifecycle artifact
2776 * Operation operation = convertToOperation(artifactInfo, operationName);
2778 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2780 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2782 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2785 log.debug("Enty on graph is updated. Update artifact in ES");
2787 // Changing previous and current artifactId for auditing
2788 prevArtifactId = currArtifactId;
2789 currArtifactId = artifactDefinition.getUniqueId();
2791 NodeTypeEnum convertParentType = convertParentType(componentType);
2793 if (decodedPayload == null) {
2794 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2795 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2796 // Either<ESArtifactData, ResourceUploadStatus>
2797 // artifactfromES = daoUploader.getArtifact(artifactId);
2798 if (artifactFromCassandra.isRight()) {
2799 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2800 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2801 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2802 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2803 resultOp = Either.right(responseFormat);
2806 // clone data to new artifact
2807 artifactData.setData(artifactFromCassandra.left().value().getData());
2808 artifactData.setId(artifactFromCassandra.left().value().getId());
2811 if (artifactDefinition.getEsId() == null) {
2812 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2813 artifactData.setId(artifactDefinition.getUniqueId());
2817 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2818 isLeft = result.isLeft();
2820 artifactUniqueId = result.left().value().getUniqueId();
2821 artifactDefinition = result.left().value();
2822 String artifactType = artifactInfo.getArtifactType();
2823 if (NodeTypeEnum.Resource == convertParentType
2824 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2826 if (!artifactUniqueId.equals(artifactId)) {
2827 // need to update the generated id in heat env
2828 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2829 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2830 if (findFirst.isPresent()) {
2831 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2832 artifactEnvInfo.setArtifactChecksum(null);
2833 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2838 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2840 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2841 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2846 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2848 insideEither = Either.left(result.left().value());
2849 resultOp = Either.left(insideEither);
2850 if (error != StorageOperationStatus.OK) {
2855 error = result.right().value();
2859 // create new entry in ES
2861 if (artifactData.getData() != null) {
2862 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2863 artifactData.setId(artifactDefinition.getEsId());
2864 res = saveArtifacts(artifactData, parentId, false);
2870 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2871 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2872 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2873 // resultOp = Either.left(result.left().value());
2876 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2877 log.debug("Failed to save the artifact.");
2878 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2879 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2880 resultOp = Either.right(responseFormat);
2888 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2889 log.trace("Starting payload handling");
2890 byte[] payload = artifactInfo.getPayloadData();
2891 byte[] decodedPayload = null;
2893 if (payload != null && payload.length != 0) {
2894 // the generated artifacts were already decoded by the handler
2895 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2896 if (decodedPayload.length == 0) {
2897 log.debug("Failed to decode the payload.");
2898 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2899 return Either.right(responseFormat);
2902 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
2903 artifactInfo.setArtifactChecksum(checkSum);
2904 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2906 // Specific payload validations of different types
2907 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2908 if (isDeploymentArtifact(artifactInfo)) {
2909 log.trace("Starting deployment artifacts payload validation");
2910 String artifactType = artifactInfo.getArtifactType();
2911 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2912 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2913 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2914 if (isValidPayload.isLeft()) {
2915 isValidPayload = extractHeatParameters(artifactInfo);
2917 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2918 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2919 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
2920 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2922 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2924 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2925 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2926 String artifactFileName = artifactInfo.getArtifactName();
2927 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2928 switch (fileExtension) {
2930 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2933 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2937 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2942 if (isValidPayload.isRight()) {
2943 ResponseFormat responseFormat = isValidPayload.right().value();
2944 return Either.right(responseFormat);
2947 } // null/empty payload is normal if called from metadata update ONLY.
2948 // The validation of whether this is metadata/payload update case is
2949 // currently done separately
2951 if (!isArtifactMetadataUpdate) {
2952 log.debug("Payload is missing.");
2953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2954 return Either.right(responseFormat);
2957 log.trace("Ended payload handling");
2958 return Either.left(decodedPayload);
2961 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2962 // Basic YAML validation
2963 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2964 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2965 log.debug("Invalid YAML format");
2966 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2967 return Either.right(responseFormat);
2969 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2970 // HEAT specific YAML validation
2971 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2972 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2973 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2974 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2975 return Either.right(responseFormat);
2979 return Either.left(true);
2982 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2983 Either<Boolean, ResponseFormat> res = Either.left(true);
2984 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2985 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2986 log.debug("Invalid YAML format");
2987 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2988 res = Either.right(responseFormat);
2994 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
2995 boolean isXmlValid = isValidXml(payload);
2997 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2998 log.debug("Invalid XML content");
2999 return Either.right(responseFormat);
3001 return Either.left(true);
3004 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
3005 boolean isJsonValid = isValidJson(payload);
3007 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
3008 log.debug("Invalid JSON content");
3009 return Either.right(responseFormat);
3011 return Either.left(true);
3014 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
3015 if (opState == null || opState.isRight()) {
3016 titanDao.rollback();
3022 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
3023 boolean inTransaction) {
3024 User user = new User();
3025 user.setUserId(userUserId);
3026 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3027 if (parent.isRight()) {
3028 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
3029 return Either.right(responseFormat);
3031 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
3032 false, inTransaction);
3033 if (handleDelete.isRight()) {
3034 return Either.right(handleDelete.right().value());
3036 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3037 return Either.left(result.right().value());
3041 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3042 Operation op = new Operation();
3043 long time = System.currentTimeMillis();
3044 op.setCreationDate(time);
3046 String artifactName = artifactInfo.getArtifactName();
3047 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3049 op.setImplementation(artifactInfo);
3050 op.setLastUpdateDate(time);
3054 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3055 String newArtifactName = operationName + "_" + artifactName;
3056 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3057 return newArtifactName;
3061 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3063 // General validation
3064 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3065 log.debug("One of the function parameteres is null");
3066 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3069 // Normalizing artifact name
3070 artifactName = ValidationUtils.normalizeFileName(artifactName);
3072 // Resource validation
3073 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3074 if (validateResourceNameAndVersion.isRight()) {
3075 return Either.right(validateResourceNameAndVersion.right().value());
3078 Resource resource = validateResourceNameAndVersion.left().value();
3079 String resourceId = resource.getUniqueId();
3081 // Service validation
3082 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3083 if (validateServiceNameAndVersion.isRight()) {
3084 return Either.right(validateServiceNameAndVersion.right().value());
3087 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3088 if (artifacts == null || artifacts.isEmpty()) {
3089 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3090 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3093 ArtifactDefinition deploymentArtifact = null;
3095 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3096 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
3097 log.debug("Found deployment artifact {}", artifactName);
3098 deploymentArtifact = artifactDefinition;
3103 if (deploymentArtifact == null) {
3104 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3105 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3108 // Downloading the artifact
3109 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
3110 if (downloadArtifactEither.isRight()) {
3111 log.debug("Download artifact {} failed", artifactName);
3112 return Either.right(downloadArtifactEither.right().value());
3114 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3115 return Either.left(downloadArtifactEither.left().value().getRight());
3119 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3121 // General validation
3122 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3123 log.debug("One of the function parameteres is null");
3124 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3127 // Normalizing artifact name
3128 artifactName = ValidationUtils.normalizeFileName(artifactName);
3130 // Resource validation
3132 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3133 * Either.right(validateResourceNameAndVersion.right().value()); }
3135 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3138 // Service validation
3139 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3140 if (validateServiceNameAndVersion.isRight()) {
3141 return Either.right(validateServiceNameAndVersion.right().value());
3144 Service service = validateServiceNameAndVersion.left().value();
3146 // ResourceInstance validation
3147 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3148 if (validateResourceInstance.isRight()) {
3149 return Either.right(validateResourceInstance.right().value());
3152 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3154 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3156 final String finalArtifactName = artifactName;
3157 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3159 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3160 ArtifactDefinition deployableArtifact;
3162 if (!hasDeploymentArtifacts) {
3163 log.debug("Deployment artifact with name {} not found", artifactName);
3164 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3167 log.debug("Found deployment artifact {}", artifactName);
3168 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3169 // Downloading the artifact
3170 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact, service );
3172 if (downloadArtifactEither.isRight()) {
3173 log.debug("Download artifact {} failed", artifactName);
3174 return Either.right(downloadArtifactEither.right().value());
3176 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3177 return Either.left(downloadArtifactEither.left().value().getRight());
3180 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3182 List<ComponentInstance> riList = service.getComponentInstances();
3183 for (ComponentInstance ri : riList) {
3184 if (ri.getNormalizedName().equals(resourceInstanceName))
3185 return Either.left(ri);
3188 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3191 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3193 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3194 if (serviceListBySystemName.isRight()) {
3195 log.debug("Couldn't fetch any service with name {}", serviceName);
3196 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3198 List<Service> serviceList = serviceListBySystemName.left().value();
3199 if (serviceList == null || serviceList.isEmpty()) {
3200 log.debug("Couldn't fetch any service with name {}", serviceName);
3201 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3204 Service foundService = null;
3205 for (Service service : serviceList) {
3206 if (service.getVersion().equals(serviceVersion)) {
3207 log.trace("Found service with version {}", serviceVersion);
3208 foundService = service;
3213 if (foundService == null) {
3214 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3215 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3217 return Either.left(foundService);
3220 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3222 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3223 if (resourceListBySystemName.isRight()) {
3224 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3225 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3227 return Either.left(resourceListBySystemName.left().value());
3230 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3232 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3233 if (serviceName == null || serviceVersion == null || artifactName == null) {
3234 log.debug("One of the function parameteres is null");
3235 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3238 // Normalizing artifact name
3239 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3241 // Service validation
3242 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3243 if (validateServiceNameAndVersion.isRight()) {
3244 return Either.right(validateServiceNameAndVersion.right().value());
3247 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3249 // Looking for deployment or tosca artifacts
3250 Service service = validateServiceNameAndVersion.left().value();
3252 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3253 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3254 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3257 Optional<ArtifactDefinition> foundArtifactOptl = null;
3259 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3260 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3261 // filters artifact by name
3262 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3264 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3265 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3266 // filters TOSCA artifact by name
3267 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3269 if (!foundArtifactOptl.isPresent()) {
3270 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3271 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3273 log.debug("Found deployment artifact {}", normalizedArtifactName);
3274 // Downloading the artifact
3275 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get(), service);
3276 if (downloadArtifactEither.isRight()) {
3277 log.debug("Download artifact {} failed", normalizedArtifactName);
3278 return Either.right(downloadArtifactEither.right().value());
3280 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3281 return Either.left(downloadArtifactEither.left().value().getRight());
3284 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3285 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3286 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3287 if (artifactById.isRight()) {
3288 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3289 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3290 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3292 ArtifactDefinition artifactDefinition = artifactById.left().value();
3293 if (artifactDefinition == null) {
3294 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3295 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3298 return downloadArtifact(artifactDefinition, null);
3301 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3302 boolean found = false;
3303 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3304 if (artifactsS != null) {
3305 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3306 if (entry.getValue().getUniqueId().equals(artifactId)) {
3312 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3313 if (!found && deploymentArtifactsS != null) {
3314 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3315 if (entry.getValue().getUniqueId().equals(artifactId)) {
3321 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3322 if (!found && toscaArtifactsS != null) {
3323 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3324 if (entry.getValue().getUniqueId().equals(artifactId)) {
3330 switch (component.getComponentType()) {
3332 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3333 if (!found && interfaces != null) {
3334 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3335 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3336 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3337 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3346 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3347 if (!found && apiArtifacts != null) {
3348 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3349 if (entry.getValue().getUniqueId().equals(artifactId)) {
3363 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3365 boolean found = false;
3366 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3367 ComponentInstance resourceInstance = null;
3368 for (ComponentInstance ri : resourceInstances) {
3369 if (ri.getUniqueId().equals(resourceInstanceId)) {
3370 resourceInstance = ri;
3374 if (resourceInstance != null) {
3375 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3376 if (artifacts != null) {
3377 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3378 if (entry.getValue().getUniqueId().equals(artifactId)) {
3385 artifacts = resourceInstance.getArtifacts();
3386 if (artifacts != null) {
3387 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3388 if (entry.getValue().getUniqueId().equals(artifactId)) {
3399 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3400 String containerComponentType, boolean inTransaction) {
3402 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3403 componentForAudit.getNodeType();
3405 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3407 if (componentResult.isRight()) {
3408 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3409 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3410 log.debug("Service not found, serviceId {}", componentId);
3411 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3412 return Either.right(responseFormat);
3414 return Either.left(componentResult.left().value());
3417 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3418 ComponentTypeEnum componentType) {
3419 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3420 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3421 if (canWork.isRight()) {
3422 String uniqueId = component.getUniqueId();
3423 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3424 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3425 return Either.right(canWork.right().value());
3428 return Either.left(true);
3431 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3433 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3434 String role = user.getRole();
3435 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3436 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3437 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3438 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3439 return Either.right(responseFormat);
3442 return Either.left(true);
3445 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3446 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3448 if (validateUserExists.isRight()) {
3449 User user = new User();
3450 user.setUserId(userId);
3451 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3452 return Either.right(validateUserExists.right().value());
3454 return Either.left(validateUserExists.left().value());
3457 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3458 AuditingActionEnum auditingAction = null;
3459 switch (operation.getArtifactOperationEnum()) {
3461 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3464 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3467 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3470 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3475 return auditingAction;
3478 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition, Component component) {
3479 String esArtifactId = artifactDefinition.getEsId();
3480 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3481 if (artifactfromES.isRight()) {
3482 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3483 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3484 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3485 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3486 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName());
3487 handleAuditing(AuditingActionEnum.DOWNLOAD_ARTIFACT, component, null, null, artifactDefinition, null, artifactDefinition.getArtifactUUID(), responseFormat, null, null);
3489 return Either.right(responseFormat);
3492 ESArtifactData esArtifactData = artifactfromES.left().value();
3493 byte[] data = esArtifactData.getDataAsArray();
3495 log.debug("Artifact data from ES is null");
3496 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3498 String artifactName = artifactDefinition.getArtifactName();
3499 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3500 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3503 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3504 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3505 return artifactData;
3508 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3510 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3512 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3513 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3515 log.info("Failed to save artifact {}.", artifactData.getId());
3521 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3522 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3525 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3526 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3529 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3530 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3531 if (user.isRight()) {
3532 ResponseFormat responseFormat;
3533 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3534 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3535 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3537 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3538 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3540 return Either.right(responseFormat);
3543 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3544 return Either.left(artifactDefinition);
3547 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3548 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3550 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3551 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3552 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3554 artifactInfo.setArtifactDisplayName(artifactName);
3555 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3556 artifactInfo.setArtifactType(artifactType);
3557 artifactInfo.setDescription(artifactDescription);
3558 artifactInfo.setArtifactGroupType(groupType);
3559 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3561 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3563 return artifactInfo;
3566 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3567 String uniqueId = null;
3569 if (resourceId != null) {
3570 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3571 artifactInfo.setUniqueId(uniqueId);
3573 artifactInfo.setUserIdCreator(user.getUserId());
3574 String fullName = user.getFullName();
3575 artifactInfo.setUpdaterFullName(fullName);
3577 long time = System.currentTimeMillis();
3579 artifactInfo.setCreatorFullName(fullName);
3580 artifactInfo.setCreationDate(time);
3582 artifactInfo.setLastUpdateDate(time);
3583 artifactInfo.setUserIdLastUpdater(user.getUserId());
3585 artifactInfo.setMandatory(true);
3588 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3589 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3592 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3593 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3596 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3598 byte[] payload = payloadStr.getBytes();
3600 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3601 return Either.left(artifactData);
3606 * @param artifactDefinition
3609 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3610 boolean shouldLock, String instanceId) {
3611 String payload = generateHeatEnvPayload(artifactDefinition);
3612 String prevUUID = artifactDefinition.getArtifactUUID();
3613 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3614 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId)
3616 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3619 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3620 boolean shouldLock, String instanceId) {
3621 String payload = generateHeatEnvPayload(artifactDefinition);
3622 String prevUUID = artifactDefinition.getArtifactUUID();
3623 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3624 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId)
3626 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3629 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3630 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3631 List<ComponentInstance> componentInstances = component.getComponentInstances();
3632 if (componentInstances != null) {
3633 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3634 if (findFirst.isPresent()) {
3635 ComponentInstance relevantInst = findFirst.get();
3636 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3638 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3639 updatedGroupInstances.forEach(gi -> {
3640 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3641 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3643 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3644 if (status.isRight()) {
3645 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3646 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3647 return Either.right(responseFormat);
3653 return Either.left(updatedArtDef);
3656 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3657 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3658 StringBuilder sb = new StringBuilder();
3659 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3660 sb.append("parameters:\n");
3661 if (heatParameters != null) {
3662 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3664 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3666 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3668 String heatValue = heatParameterDefinition.getCurrentValue();
3669 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3670 heatValue = heatParameterDefinition.getDefaultValue();
3671 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3672 empltyHeatValues.add(heatParameterDefinition);
3676 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3680 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3683 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3685 case COMMA_DELIMITED_LIST:
3687 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3690 String value = heatValue;
3691 boolean starts = value.startsWith("\"");
3692 boolean ends = value.endsWith("\"");
3693 if (!(starts && ends)) {
3694 starts = value.startsWith("'");
3695 ends = value.endsWith("'");
3696 if (!(starts && ends)) {
3697 value = "\"" + value + "\"";
3700 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3707 if (!empltyHeatValues.isEmpty()) {
3708 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3709 empltyHeatValues.forEach(hv -> {
3710 sb.append(" ").append(hv.getName()).append(":");
3711 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3712 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3713 sb.append(" \"\"").append("\n");
3715 sb.append(" ").append("\n");
3720 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3723 String result = sb.toString().replaceAll("\\\\n", "\n");
3730 * @param artifactDefinition
3734 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3735 User modifier, boolean shouldLock, String instanceId) {
3736 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3737 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3741 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3742 User modifier, boolean shouldLock, String instanceId) {
3743 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, System::currentTimeMillis,
3744 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3748 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3749 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3751 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3752 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3754 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3755 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3756 ESArtifactData artifactData = null;
3758 if (artifactDataRes.isLeft()) {
3759 artifactData = artifactDataRes.left().value();
3761 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3762 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3763 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3765 return Either.right(artifactDataRes.right().value());
3767 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
3769 String esArtifactId = artifactDefinition.getEsId();
3770 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3771 ESArtifactData esArtifactData;
3772 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3773 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
3774 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3775 if (artifactfromES.isRight()) {
3776 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3777 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3778 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3779 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus.name(), esArtifactId);
3780 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3782 esArtifactData = artifactfromES.left().value();
3783 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
3785 oldCheckSum = artifactDefinition.getArtifactChecksum();
3788 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3791 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3792 if (lockComponent.isRight()) {
3793 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3794 return Either.right(lockComponent.right().value());
3798 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3800 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3801 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3802 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3803 if (updateArifactDefinitionStatus.isRight()) {
3804 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3805 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3806 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3807 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3809 return Either.right(responseFormat);
3813 oldCheckSum = artifactDefinition.getArtifactChecksum();
3814 artifactDefinition.setArtifactChecksum(newCheckSum);
3815 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3816 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3817 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3818 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3820 log.trace("Update Payload ", artifactDefinition.getEsId());
3822 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3824 artifactDefinition = updateArifactDefinitionStatus.left().value();
3825 artifactData.setId(artifactDefinition.getUniqueId());
3826 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3828 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3830 log.debug("Artifact Saved In ES {}", artifactData.getId());
3831 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3832 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3833 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3836 titanDao.rollback();
3837 log.info("Failed to save artifact {}.", artifactData.getId());
3838 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3839 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3840 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3842 return Either.right(responseFormat);
3845 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3846 log.debug("Failed To update artifact {}", artifactData.getId());
3847 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3848 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3850 return Either.right(responseFormat);
3855 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3860 return Either.left(artifactDefinition);
3864 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3865 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef.getArtifactLabel(), artifactDef.getArtifactDisplayName(),
3866 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
3870 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
3871 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
3873 Map<String, Object> json = new HashMap<String, Object>();
3874 if (artifactId != null && !artifactId.isEmpty())
3875 json.put(Constants.ARTIFACT_ID, artifactId);
3877 json.put(Constants.ARTIFACT_NAME, artifactName);
3878 json.put(Constants.ARTIFACT_TYPE, artifactType);
3879 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3881 if (artifactContent != null) {
3882 String encodedPayload = new String(artifactContent);
3884 // boolean isEncoded = GeneralUtility.isBase64Encoded(artifactContentent);
3885 // if (!isEncoded) {
3886 log.debug("payload is encoded. perform decode");
3887 encodedPayload = Base64.encodeBase64String(artifactContent);
3888 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3891 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3892 json.put(Constants.ARTIFACT_LABEL, label);
3893 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3894 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3895 : updatedRequiredArtifacts.stream().filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e.getType().equals(ArtifactTypeEnum.HEAT_NESTED.getType())).map(e -> e.getFileName()).collect(Collectors.toList()));
3896 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
3901 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
3903 String jsonStr = gson.toJson(json);
3904 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
3905 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
3906 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
3907 artifactDefinitionFromJson, null, jsonStr, null, null, null, user, containerComponent, false, false, true);
3908 if (uploadArtifactToService.isRight())
3909 return Either.right(uploadArtifactToService.right().value());
3911 return Either.left(uploadArtifactToService.left().value());
3914 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3915 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3916 convertParentType(componentType);
3917 String parentId = parent.getUniqueId();
3918 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3919 ArtifactDefinition currArtifact = artifactInfo;
3921 if (origMd5 != null) {
3922 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3923 if (validateMd5.isRight()) {
3924 ResponseFormat responseFormat = validateMd5.right().value();
3925 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3926 return Either.right(responseFormat);
3929 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3930 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3931 if (deploymentValidationResult.isRight()) {
3932 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3933 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3934 return Either.right(responseFormat);
3937 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3938 if (payloadEither.isRight()) {
3939 ResponseFormat responseFormat = payloadEither.right().value();
3940 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3941 return Either.right(responseFormat);
3943 } else { // duplicate
3944 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3945 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3946 return Either.right(responseFormat);
3952 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3953 if (lockComponent.isRight()) {
3954 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3955 return Either.right(lockComponent.right().value());
3958 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3960 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
3965 if (resultOp == null || resultOp.isRight()) {
3966 log.debug("all changes rollback");
3967 if (false == inTransaction)
3968 titanDao.rollback();
3970 log.debug("all changes committed");
3971 if (false == inTransaction)
3975 componentType = parent.getComponentType();
3976 NodeTypeEnum nodeType = componentType.getNodeType();
3977 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3978 // graphLockOperation.unlockComponent(parentId, parentType);
3982 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3983 ComponentTypeEnum componentType, String origMd5) {
3985 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3986 Either<ArtifactDefinition, Operation> insideEither = null;
3988 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3990 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3991 if (getRI.isRight()) {
3992 return Either.right(getRI.right().value());
3994 ComponentInstance ri = getRI.left().value();
3995 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3996 if (getArtifactRes.isRight()) {
3997 return Either.right(getArtifactRes.right().value());
3999 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4001 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4002 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4003 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
4004 return Either.right(responseFormat);
4006 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4007 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4008 new ArrayList<HeatParameterDefinition>();
4011 if (origMd5 != null) {
4012 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
4013 updatedHeatEnvParams, currArtifact.getArtifactName());
4014 if (uploadParamsValidationResult.isRight()) {
4015 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4016 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
4017 return Either.right(responseFormat);
4019 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4022 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
4023 if (validateAndConvertHeatParamers.isRight()) {
4024 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4025 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
4026 return Either.right(responseFormat);
4029 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4030 // fill reduced heat env parameters List for updating
4031 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4032 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4033 currArtifact.setListHeatParameters(currentHeatEnvParams);
4035 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4036 if (updateArifactRes.isRight()) {
4037 log.debug("Failed to update artifact on graph - {}", artifactId);
4038 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
4039 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
4040 return Either.right(responseFormat);
4042 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4043 if (error != StorageOperationStatus.OK) {
4044 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4045 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
4046 return Either.right(responseFormat);
4049 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
4050 if (error != StorageOperationStatus.OK) {
4051 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4052 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
4053 return Either.right(responseFormat);
4057 insideEither = Either.left(currArtifact);
4058 resultOp = Either.left(insideEither);
4059 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4060 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
4064 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4065 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4066 String paramName = heatEnvParam.getName();
4067 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4068 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4069 String updatedParamValue = heatEnvParam.getCurrentValue();
4070 currHeatParam.setCurrentValue(updatedParamValue);
4076 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4077 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
4079 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4080 Either<ArtifactDefinition, Operation> insideEither = null;
4082 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
4084 String currentHeatId = currHeatArtifact.getUniqueId();
4086 String esArtifactId = currHeatArtifact.getEsId();
4087 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4088 if (artifactfromES.isRight()) {
4089 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4090 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4091 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4092 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
4093 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4096 ESArtifactData esArtifactData = artifactfromES.left().value();
4097 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4099 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4100 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4101 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4103 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
4106 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4108 paramName = heatEnvParam.getName();
4109 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4110 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4112 String updatedParamValue = heatEnvParam.getCurrentValue();
4113 if (updatedParamValue == null)
4114 updatedParamValue = heatEnvParam.getDefaultValue();
4115 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4116 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4117 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4118 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
4119 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4120 return Either.right(responseFormat);
4123 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4124 newHeatEnvParams.add(currHeatParam);
4129 if (!newHeatEnvParams.isEmpty()) {
4130 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4131 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4133 if (operationStatus.isRight()) {
4134 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4136 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
4137 return Either.right(responseFormat);
4140 updatedHeatArt = operationStatus.left().value();
4142 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
4143 esArtifactData.setId(updatedHeatArt.getEsId());
4144 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
4147 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
4148 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4149 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
4150 // resultOp = Either.left(result.left().value());
4153 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
4154 log.debug("Failed to save the artifact.");
4155 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4156 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
4157 resultOp = Either.right(responseFormat);
4161 insideEither = Either.left(updatedHeatArt);
4164 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4165 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4166 artifactEnvInfo.setArtifactChecksum(null);
4167 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
4169 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
4172 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4173 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
4174 if (result != ActionStatus.OK) {
4175 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4176 return Either.right(responseFormat);
4180 if (updatedHeatEnvParams.isEmpty()) {
4181 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
4183 resultOp = Either.left(insideEither);
4184 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4185 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4190 private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4191 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4192 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4193 return Either.right(responseFormat);
4197 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4198 StorageOperationStatus error = StorageOperationStatus.OK;
4199 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4200 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4201 // List<GroupInstance> associatedGroups = null;
4202 List<String> groupInstancesId = null;
4203 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4204 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4206 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4207 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4208 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4214 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4215 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4217 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4218 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4219 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4220 return Either.right(responseFormat);
4223 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4224 String paramName = uploadedHeatParam.getName();
4225 boolean isExistsInHeat = false;
4226 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4227 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4229 isExistsInHeat = true;
4230 uploadedHeatParam.setType(currHeatParam.getType());
4231 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4232 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4233 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4237 if (!isExistsInHeat) {
4238 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4239 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4240 return Either.right(responseFormat);
4243 return Either.left(updatedHeatEnvParams);
4246 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4247 ResponseFormat responseFormat = null;
4248 List<ComponentInstance> ris = component.getComponentInstances();
4249 for (ComponentInstance ri : ris) {
4250 if (riID.equals(ri.getUniqueId())) {
4251 return Either.left(ri);
4254 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4255 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4256 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4257 return Either.right(responseFormat);
4260 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4261 ResponseFormat responseFormat = null;
4262 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4263 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4264 if (artifactId.equals(artifact.getUniqueId())) {
4265 return Either.left(artifact);
4268 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4269 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4270 return Either.right(responseFormat);
4273 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4274 ArtifactDefinition ret;
4275 if (eitherArtifact.isLeft()) {
4276 ret = eitherArtifact.left().value();
4278 ret = eitherArtifact.right().value().getImplementationArtifact();
4284 * downloads artifact of component by UUIDs
4286 * @param componentType
4287 * @param componentUuid
4288 * @param artifactUUID
4289 * @param auditAdditionalParam
4292 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4293 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4294 Either<byte[], ResponseFormat> result;
4295 byte[] downloadedArtifact = null;
4296 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4297 if (errorWrapper.isEmpty()) {
4298 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4299 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4301 if (errorWrapper.isEmpty()) {
4302 result = Either.left(downloadedArtifact);
4304 result = Either.right(errorWrapper.getInnerElement());
4310 * downloads an artifact of resource instance of component by UUIDs
4312 * @param componentType
4313 * @param componentUuid
4314 * @param resourceInstanceName
4315 * @param artifactUUID
4316 * @param auditAdditionalParam
4319 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4320 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4321 Either<byte[], ResponseFormat> result;
4322 byte[] downloadedArtifact = null;
4323 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4324 if (errorWrapper.isEmpty()) {
4325 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4327 if (errorWrapper.isEmpty()) {
4328 result = Either.left(downloadedArtifact);
4330 result = Either.right(errorWrapper.getInnerElement());
4336 * uploads an artifact to a component by UUID
4340 * @param componentType
4341 * @param componentUuid
4342 * @param additionalParams
4346 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4347 ArtifactOperationInfo operation) {
4348 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4349 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4350 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4351 ArtifactDefinition uploadArtifact = null;
4352 Component component = null;
4353 String componentId = null;
4354 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4355 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4356 String userId = request.getHeader(Constants.USER_ID_HEADER);
4358 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4359 if (getComponentRes.isRight()) {
4360 StorageOperationStatus status = getComponentRes.right().value();
4361 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4362 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4364 if (errorWrapper.isEmpty()) {
4365 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4366 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4368 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4369 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4370 if (component != null) {
4371 componentId = component.getUniqueId();
4372 componentName = component.getName();
4375 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4377 if (errorWrapper.isEmpty()) {
4378 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4379 if (actionResult.isRight()) {
4380 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4381 errorWrapper.setInnerElement(actionResult.right().value());
4384 if (errorWrapper.isEmpty()) {
4385 uploadArtifact = actionResult.left().value().left().value();
4386 uploadArtifactResult = Either.left(uploadArtifact);
4388 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4390 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4391 return uploadArtifactResult;
4395 * upload an artifact to a resource instance by UUID
4399 * @param componentType
4400 * @param componentUuid
4401 * @param resourceInstanceName
4402 * @param additionalParams
4406 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4407 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4408 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4409 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4410 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4411 ArtifactDefinition uploadArtifact = null;
4412 Component component = null;
4413 String componentInstanceId;
4415 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4416 String userId = request.getHeader(Constants.USER_ID_HEADER);
4418 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4419 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4420 if (getComponentRes.isRight()) {
4421 StorageOperationStatus status = getComponentRes.right().value();
4422 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4423 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4425 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4426 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4428 if (errorWrapper.isEmpty()) {
4429 if (component == null) {
4430 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4432 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4435 if (errorWrapper.isEmpty()) {
4436 componentInstanceId = componentRiPair.getRight().getUniqueId();
4437 componentId = componentRiPair.getLeft().getUniqueId();
4438 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4440 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4441 if (actionResult.isRight()) {
4442 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4443 errorWrapper.setInnerElement(actionResult.right().value());
4446 if (errorWrapper.isEmpty()) {
4447 uploadArtifact = actionResult.left().value().left().value();
4448 uploadArtifactResult = Either.left(uploadArtifact);
4450 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4452 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4453 return uploadArtifactResult;
4457 * updates an artifact on a component by UUID
4461 * @param componentType
4462 * @param componentUuid
4463 * @param artifactUUID
4464 * @param additionalParams
4469 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4470 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4471 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4472 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4473 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4474 ArtifactDefinition updateArtifact = null;
4475 Component component = null;
4476 String componentId = null;
4477 String artifactId = null;
4478 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4479 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4480 String userId = request.getHeader(Constants.USER_ID_HEADER);
4482 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4483 if (getComponentRes.isRight()) {
4484 StorageOperationStatus status = getComponentRes.right().value();
4485 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4486 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4488 if (errorWrapper.isEmpty()) {
4489 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4490 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4492 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4493 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4494 if (component != null) {
4495 componentId = component.getUniqueId();
4496 componentName = component.getName();
4499 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4501 if (errorWrapper.isEmpty()) {
4502 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4504 if (errorWrapper.isEmpty()) {
4505 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4506 if (actionResult.isRight()) {
4507 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4508 errorWrapper.setInnerElement(actionResult.right().value());
4511 if (errorWrapper.isEmpty()) {
4512 updateArtifact = actionResult.left().value().left().value();
4513 updateArtifactResult = Either.left(updateArtifact);
4516 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4518 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4519 return updateArtifactResult;
4523 * updates an artifact on a resource instance by UUID
4527 * @param componentType
4528 * @param componentUuid
4529 * @param resourceInstanceName
4530 * @param artifactUUID
4531 * @param additionalParams
4536 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4537 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4539 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4540 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4541 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4542 ArtifactDefinition updateArtifact = null;
4543 Component component = null;
4544 String componentInstanceId = null;
4545 String componentId = null;
4546 String artifactId = null;
4547 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4548 String userId = request.getHeader(Constants.USER_ID_HEADER);
4550 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4551 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4552 if (getComponentRes.isRight()) {
4553 StorageOperationStatus status = getComponentRes.right().value();
4554 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4555 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4557 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4558 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4560 if (errorWrapper.isEmpty()) {
4561 if (component == null) {
4562 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4564 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4567 if (errorWrapper.isEmpty()) {
4568 componentInstanceId = componentRiPair.getRight().getUniqueId();
4569 componentId = componentRiPair.getLeft().getUniqueId();
4570 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4572 if (errorWrapper.isEmpty()) {
4573 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4575 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4576 if (actionResult.isRight()) {
4577 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4578 errorWrapper.setInnerElement(actionResult.right().value());
4581 if (errorWrapper.isEmpty()) {
4582 updateArtifact = actionResult.left().value().left().value();
4583 updateArtifactResult = Either.left(updateArtifact);
4585 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4587 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4588 return updateArtifactResult;
4592 * deletes an artifact on a component by UUID
4595 * @param componentType
4596 * @param componentUuid
4597 * @param artifactUUID
4598 * @param additionalParams
4603 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4604 ArtifactOperationInfo operation) {
4606 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4607 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4608 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4609 ArtifactDefinition deleteArtifact = null;
4610 Component component = null;
4611 String componentId = null;
4612 String artifactId = null;
4613 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4614 String userId = request.getHeader(Constants.USER_ID_HEADER);
4616 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4617 if (getComponentRes.isRight()) {
4618 StorageOperationStatus status = getComponentRes.right().value();
4619 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4620 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4622 if (errorWrapper.isEmpty()) {
4623 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4624 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4625 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4626 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4627 if (component != null) {
4628 componentId = component.getUniqueId();
4629 componentName = component.getName();
4632 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4634 if (errorWrapper.isEmpty()) {
4635 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4637 if (errorWrapper.isEmpty()) {
4638 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4639 if (actionResult.isRight()) {
4640 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4641 errorWrapper.setInnerElement(actionResult.right().value());
4644 if (errorWrapper.isEmpty()) {
4645 deleteArtifact = actionResult.left().value().left().value();
4646 deleteArtifactResult = Either.left(deleteArtifact);
4648 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4650 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4651 return deleteArtifactResult;
4655 * deletes an artifact from a resource instance by UUID
4658 * @param componentType
4659 * @param componentUuid
4660 * @param resourceInstanceName
4661 * @param artifactUUID
4662 * @param additionalParams
4667 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4668 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4670 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4671 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4672 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4673 ArtifactDefinition deleteArtifact = null;
4674 Component component = null;
4675 String componentInstanceId = null;
4676 String componentId = null;
4677 String artifactId = null;
4678 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4679 String userId = request.getHeader(Constants.USER_ID_HEADER);
4680 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4681 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4682 if (getComponentRes.isRight()) {
4683 StorageOperationStatus status = getComponentRes.right().value();
4684 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4685 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4687 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4688 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4690 if (errorWrapper.isEmpty()) {
4691 if (component == null) {
4692 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4694 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4697 if (errorWrapper.isEmpty()) {
4698 componentInstanceId = componentRiPair.getRight().getUniqueId();
4699 componentId = componentRiPair.getLeft().getUniqueId();
4700 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4702 if (errorWrapper.isEmpty()) {
4704 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4706 if (actionResult.isRight()) {
4707 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4708 errorWrapper.setInnerElement(actionResult.right().value());
4711 if (errorWrapper.isEmpty()) {
4712 deleteArtifact = actionResult.left().value().left().value();
4713 deleteArtifactResult = Either.left(deleteArtifact);
4715 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4717 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4718 return deleteArtifactResult;
4721 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4722 String artifactId = null;
4723 ArtifactDefinition foundArtifact = null;
4724 if (instance.getDeploymentArtifacts() != null) {
4725 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4727 if (foundArtifact == null && instance.getArtifacts() != null) {
4728 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4730 if (foundArtifact == null) {
4731 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4732 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4734 artifactId = foundArtifact.getUniqueId();
4739 @SuppressWarnings("unchecked")
4740 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4741 Map<String, String> existingEnvVersions) {
4742 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4743 if (deploymentResourceArtifacts == null) {
4744 log.debug("no deployment artifacts are configured for generated artifacts");
4745 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4747 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4748 if (placeHolderData == null) {
4749 log.debug("no env type {} are configured for generated artifacts", envType);
4750 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4753 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4754 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4755 if (createArtifactPlaceHolder.isRight()) {
4756 return Either.right(createArtifactPlaceHolder.right().value());
4758 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4759 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
4760 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4761 artifactHeatEnv.setTimeout(0);
4762 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
4763 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4764 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4765 ArtifactDefinition heatEnvPlaceholder;
4766 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4767 if (parentType != NodeTypeEnum.ResourceInstance) {
4768 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component.getUniqueId(), parentType, parentId);
4769 if (addHeatEnvArtifact.isRight()) {
4770 log.debug("failed to create heat env artifact on resource instance");
4771 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4773 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
4775 heatEnvPlaceholder = artifactHeatEnv;
4776 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
4777 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
4780 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(heatEnvPlaceholder, "", heatEnvPlaceholder.getUniqueId());
4781 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4782 ComponentTypeEnum componentType = component.getComponentType();
4783 if (parentType == NodeTypeEnum.ResourceInstance) {
4784 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4786 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4787 return Either.left(heatEnvPlaceholder);
4790 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
4791 if (artifact.getListHeatParameters() == null) {
4794 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
4795 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4796 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4797 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4798 heatEnvParameter.setCurrentValue(null);
4799 heatEnvParameters.add(heatEnvParameter);
4801 artifactDefinition.setListHeatParameters(heatEnvParameters);
4804 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4805 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4806 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4807 String name = heatArtifact.getArtifactName();
4810 name = heatArtifact.getArtifactLabel();
4811 fileName = name + "." + envExtension;
4813 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4815 heatEnvArtifact.setArtifactName(fileName);
4818 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4819 if (null != existingEnvVersions) {
4820 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4821 if (null != prevVersion) {
4822 heatEnvArtifact.setArtifactVersion(prevVersion);
4828 * Handles Artifacts Request For Inner Component
4830 * @param artifactsToHandle
4833 * @param vfcsNewCreatedArtifacts
4836 * @param inTransaction
4839 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4840 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4842 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4843 ComponentTypeEnum componentType = component.getComponentType();
4844 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4845 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4846 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4850 for (ArtifactDefinition artifact : artifactsToHandle) {
4851 originData = buildJsonStringForCsarVfcArtifact(artifact);
4852 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
4853 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4854 if (actionResult.isRight()) {
4855 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4856 errorWrapper.setInnerElement(actionResult.right().value());
4857 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
4858 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4862 uploadedArtifacts.add(actionResult.left().value().left().value());
4864 if (errorWrapper.isEmpty()) {
4865 handleArtifactsResult = Either.left(uploadedArtifacts);
4867 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4869 } catch (Exception e) {
4870 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4871 handleArtifactsResult = Either.right(responseFormat);
4872 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4874 return handleArtifactsResult;
4877 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4878 ComponentInstance componentInstance = null;
4879 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4880 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4881 if (errorWrapper.isEmpty()) {
4882 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4883 if (componentInstance == null) {
4884 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4885 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4888 return componentInstance;
4891 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4893 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4894 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4895 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4896 if (componentInstance == null) {
4897 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4898 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4900 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4902 return relatedComponentComponentInstancePair;
4905 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4906 ComponentInstance componentInstance;
4907 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4908 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4909 if (errorWrapper.isEmpty()) {
4910 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4911 if (componentInstance == null) {
4912 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4913 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4915 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4918 return relatedComponentComponentInstancePair;
4921 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4923 byte[] downloadedArtifact = null;
4924 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4925 List<ArtifactDefinition> artifactsList = null;
4926 ArtifactDefinition deploymentArtifact = null;
4927 if (artifacts != null && !artifacts.isEmpty()) {
4928 artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4930 if (artifactsList == null || artifactsList.isEmpty()) {
4931 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4932 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4934 if (errorWrapper.isEmpty()) {
4935 deploymentArtifact = artifactsList.get(0);
4936 downloadArtifactEither = downloadArtifact(deploymentArtifact, null);
4937 if (downloadArtifactEither.isRight()) {
4938 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4939 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4942 if (errorWrapper.isEmpty()) {
4943 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4944 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4946 return downloadedArtifact;
4949 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4950 Component component = null;
4951 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4952 if (getComponentRes.isRight()) {
4953 StorageOperationStatus status = getComponentRes.right().value();
4954 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4955 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4957 component = getComponentRes.left().value();
4962 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4963 Component component = null;
4964 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4965 if (getComponentRes.isRight()) {
4966 StorageOperationStatus status = getComponentRes.right().value();
4967 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4968 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4970 List<Component> value = getComponentRes.left().value();
4971 if (value.isEmpty()){
4972 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4973 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4974 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4976 component = value.get(0);
4982 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4983 String artifactId = null;
4984 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4985 StorageOperationStatus storageStatus;
4986 ArtifactDefinition latestArtifact = null;
4987 List<ArtifactDefinition> artifacts = null;
4988 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4989 if (getArtifactsRes.isRight()) {
4990 storageStatus = getArtifactsRes.right().value();
4991 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4992 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4993 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4995 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4997 if (errorWrapper.isEmpty()) {
4998 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4999 if (artifacts == null || artifacts.isEmpty()) {
5000 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
5001 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5004 if (errorWrapper.isEmpty()) {
5005 latestArtifact = artifacts.stream().max((a1, a2) -> {
5006 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5007 if (compareRes == 0) {
5008 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
5012 if (latestArtifact == null) {
5013 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
5014 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5017 if (errorWrapper.isEmpty()) {
5018 artifactId = latestArtifact.getUniqueId();
5023 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5025 Component component = null;
5026 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5027 if (getUserRes.isRight()) {
5028 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
5029 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5031 if (errorWrapper.isEmpty()) {
5032 User modifier = getUserRes.left().value();
5033 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5034 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5035 if (checkoutRes.isRight()) {
5036 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
5037 errorWrapper.setInnerElement(checkoutRes.right().value());
5039 component = checkoutRes.left().value();
5045 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
5046 if (artifact == null) {
5047 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
5048 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
5049 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
5050 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
5053 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
5054 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
5055 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
5059 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5060 Map<String, Object> json = new HashMap<>();
5061 String artifactName = artifact.getArtifactName();
5062 json.put(Constants.ARTIFACT_NAME, artifactName);
5063 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5064 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5065 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5066 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5067 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5068 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5069 return gson.toJson(json);