2 * Copyright © 2016-2018 European Support Limited
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 * ============LICENSE_END=========================================================
16 * Modifications copyright (c) 2019 Nokia
17 * ================================================================================
20 package org.openecomp.sdcrests.vsp.rest.services;
22 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
23 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
24 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
26 import java.io.IOException;
27 import java.nio.ByteBuffer;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
32 import java.util.Optional;
33 import javax.activation.DataHandler;
34 import javax.inject.Named;
35 import javax.ws.rs.core.Response;
36 import org.apache.commons.io.FilenameUtils;
37 import org.apache.commons.lang3.tuple.Pair;
38 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
39 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
40 import org.openecomp.sdc.activitylog.ActivityLogManager;
41 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
42 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
43 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
44 import org.openecomp.sdc.common.errors.Messages;
45 import org.openecomp.sdc.common.utils.SdcCommon;
46 import org.openecomp.sdc.datatypes.error.ErrorLevel;
47 import org.openecomp.sdc.datatypes.error.ErrorMessage;
48 import org.openecomp.sdc.logging.api.Logger;
49 import org.openecomp.sdc.logging.api.LoggerFactory;
50 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
51 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
52 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
53 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
54 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
55 import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackage;
57 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
58 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
59 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
60 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
61 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
62 import org.openecomp.sdc.versioning.dao.types.Version;
63 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
64 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
65 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
66 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
67 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
68 import org.openecomp.sdcrests.vsp.rest.data.PackageArchive;
69 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
70 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
71 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
72 import org.springframework.context.annotation.Scope;
73 import org.springframework.stereotype.Service;
76 @Service("orchestrationTemplateCandidate")
77 @Scope(value = "prototype")
78 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
79 private static final Logger LOGGER =
80 LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
81 private OrchestrationTemplateCandidateManager candidateManager =
82 OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
83 private VendorSoftwareProductManager vendorSoftwareProductManager = VspManagerFactory
84 .getInstance().createInterface();
85 private ActivityLogManager activityLogManager =
86 ActivityLogManagerFactory.getInstance().createInterface();
89 public Response upload(final String vspId, final String versionId,
90 final Attachment fileToUpload, final String user) {
91 final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class);
92 String fileToUploadName = "";
93 String fileToUploadExtension = "";
94 final DataHandler dataHandler = fileToUpload.getDataHandler();
95 if(dataHandler != null) {
96 final String filename = dataHandler.getName();
97 fileToUploadName = FilenameUtils.removeExtension(filename);
98 fileToUploadExtension = FilenameUtils.getExtension(filename);
100 final PackageArchive archive = new PackageArchive(fileToUploadBytes);
101 final Optional<UploadFileResponseDto> validatePackageArchiveResponse =
102 validatePackageArchive(archive);
103 if (!validatePackageArchiveResponse.isPresent()) {
104 final VspDetails vspDetails = new VspDetails(vspId, new Version(versionId));
105 return processOnboardPackage(fileToUpload, fileToUploadBytes, fileToUploadName,
106 fileToUploadExtension, archive, vspDetails);
108 return Response.ok(validatePackageArchiveResponse.get()).build();
112 private Optional<UploadFileResponseDto> validatePackageArchive(final PackageArchive archive) {
113 UploadFileResponseDto uploadFileResponseDto;
115 if (archive.isSigned() && !archive.isSignatureValid()) {
116 final ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
117 getErrorWithParameters(Messages.FAILED_TO_VERIFY_SIGNATURE.getErrorMessage(), ""));
118 LOGGER.error(errorMessage.getMessage());
119 uploadFileResponseDto = buildUploadResponseWithError(errorMessage);
120 //returning OK as SDC UI won't show error message if NOT OK error code.
121 return Optional.of(uploadFileResponseDto);
123 } catch (final SecurityManagerException e) {
124 final ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
125 getErrorWithParameters(e.getMessage(), ""));
126 LOGGER.error(errorMessage.getMessage(), e);
127 uploadFileResponseDto = buildUploadResponseWithError(errorMessage);
128 //returning OK as SDC UI won't show error message if NOT OK error code.
129 return Optional.of(uploadFileResponseDto);
131 return Optional.empty();
134 private Response processOnboardPackage(final Attachment fileToUpload,
135 final byte[] fileToUploadBytes,
136 final String fileToUploadName,
137 final String fileToUploadExtension,
138 final PackageArchive archive,
139 final VspDetails vspDetails) {
140 final String filename = archive.getArchiveFileName()
141 .orElse(fileToUpload.getContentDisposition().getFilename());
142 UploadFileResponseDto uploadFileResponseDto;
144 final String archiveFileExtension = getFileExtension(filename);
145 final OnboardPackageInfo onboardPackageInfo;
146 if (OnboardingTypesEnum.CSAR.toString().equalsIgnoreCase(archiveFileExtension)) {
147 final OnboardPackage onboardPackage = new OnboardPackage(getNetworkPackageName(filename),
148 archiveFileExtension, ByteBuffer.wrap(archive.getPackageFileContents()));
149 onboardPackageInfo = new OnboardPackageInfo(fileToUploadName,
150 fileToUploadExtension, ByteBuffer.wrap(fileToUploadBytes), onboardPackage);
152 onboardPackageInfo = new OnboardPackageInfo(fileToUploadName,
153 fileToUploadExtension, ByteBuffer.wrap(fileToUploadBytes));
155 final UploadFileResponse uploadFileResponse = candidateManager
156 .upload(vspDetails, onboardPackageInfo);
157 uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
158 .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
160 return Response.ok(uploadFileResponseDto).build();
161 } catch (final SecurityManagerException e) {
162 final ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
163 getErrorWithParameters(e.getMessage(), ""));
164 LOGGER.error(errorMessage.getMessage(), e);
165 uploadFileResponseDto = buildUploadResponseWithError(errorMessage);
166 //returning OK as SDC UI won't show error message if NOT OK error code.
167 return Response.ok(uploadFileResponseDto).build();
171 private UploadFileResponseDto buildUploadResponseWithError(ErrorMessage errorMessage) {
172 UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
173 Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
174 List<ErrorMessage> errorMessages = new ArrayList<>();
175 errorMessages.add(errorMessage);
176 errorMap.put(SdcCommon.UPLOAD_FILE, errorMessages);
177 uploadFileResponseDto.setErrors(errorMap);
178 return uploadFileResponseDto;
182 public Response get(String vspId, String versionId, String user) throws IOException {
183 Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
185 if (zipFile.isPresent()) {
186 fileName = "Candidate." + zipFile.get().getLeft();
188 zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
190 if (!zipFile.isPresent()) {
191 ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
192 getErrorWithParameters(
193 Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
195 LOGGER.error(errorMessage.getMessage());
196 return Response.status(Response.Status.NOT_FOUND).build();
198 fileName = "Processed." + zipFile.get().getLeft();
200 Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
201 response.header("Content-Disposition", "attachment; filename=" + fileName);
202 return response.build();
206 public Response abort(String vspId, String versionId) {
207 candidateManager.abort(vspId, new Version(versionId));
208 return Response.ok().build();
212 public Response process(String vspId, String versionId, String user) {
214 Version version = new Version(versionId);
215 OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
217 activityLogManager.logActivity(new ActivityLogEntity(vspId, version,
218 ActivityType.Upload_Network_Package, user, true, "", ""));
220 OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
222 return Response.ok(responseDto).build();
226 public Response updateFilesDataStructure(
227 String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
229 FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
231 ValidationResponse response = candidateManager
232 .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
234 if (!response.isValid()) {
235 return Response.status(Response.Status.EXPECTATION_FAILED).entity(
236 new MapValidationResponseToDto()
237 .applyMapping(response, ValidationResponseDto.class)).build();
239 return Response.ok(fileDataStructureDto).build();
243 public Response getFilesDataStructure(String vspId, String versionId, String user) {
244 Optional<FilesDataStructure> filesDataStructure =
245 candidateManager.getFilesDataStructure(vspId, new Version(versionId));
246 if (!filesDataStructure.isPresent()) {
247 filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId,
248 new Version(versionId));
251 FileDataStructureDto fileDataStructureDto =
252 filesDataStructure.map(dataStructure -> new MapFilesDataStructureToDto()
253 .applyMapping(dataStructure, FileDataStructureDto.class))
254 .orElse(new FileDataStructureDto());
255 return Response.ok(fileDataStructureDto).build();
258 private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response){
259 OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
260 result.setErrors(response.getErrors());
261 result.setFileNames(response.getFileNames());
262 result.setStatus(response.getStatus());
266 private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto){
267 FilesDataStructure filesDataStructure = new FilesDataStructure();
268 filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
269 filesDataStructure.setModules(fileDataStructureDto.getModules());
270 filesDataStructure.setNested(fileDataStructureDto.getNested());
271 filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
272 return filesDataStructure;