10f96e9d3b4b45c41ffa8521a5510b29fd5df92e
[sdc.git] /
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  *
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
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
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  * ================================================================================
18  */
19
20 package org.openecomp.sdcrests.vsp.rest.services;
21
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;
25
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;
31 import java.util.Map;
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;
74
75 @Named
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();
87
88   @Override
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);
99     }
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);
107     } else {
108       return Response.ok(validatePackageArchiveResponse.get()).build();
109     }
110   }
111
112   private Optional<UploadFileResponseDto> validatePackageArchive(final PackageArchive archive) {
113     UploadFileResponseDto uploadFileResponseDto;
114     try {
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);
122       }
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);
130     }
131     return Optional.empty();
132   }
133
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;
143     try {
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);
151       } else {
152         onboardPackageInfo = new OnboardPackageInfo(fileToUploadName,
153             fileToUploadExtension, ByteBuffer.wrap(fileToUploadBytes));
154       }
155       final UploadFileResponse uploadFileResponse = candidateManager
156           .upload(vspDetails, onboardPackageInfo);
157       uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
158           .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
159
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();
168     }
169   }
170
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;
179   }
180
181   @Override
182   public Response get(String vspId, String versionId, String user) throws IOException {
183     Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
184     String fileName;
185     if (zipFile.isPresent()) {
186       fileName = "Candidate." + zipFile.get().getLeft();
187     } else {
188       zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
189
190       if (!zipFile.isPresent()) {
191         ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
192             getErrorWithParameters(
193                 Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
194                 ""));
195         LOGGER.error(errorMessage.getMessage());
196         return Response.status(Response.Status.NOT_FOUND).build();
197       }
198       fileName = "Processed." + zipFile.get().getLeft();
199     }
200     Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
201     response.header("Content-Disposition", "attachment; filename=" + fileName);
202     return response.build();
203   }
204
205   @Override
206   public Response abort(String vspId, String versionId) {
207     candidateManager.abort(vspId, new Version(versionId));
208     return Response.ok().build();
209   }
210
211   @Override
212   public Response process(String vspId, String versionId, String user) {
213
214     Version version = new Version(versionId);
215     OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
216
217     activityLogManager.logActivity(new ActivityLogEntity(vspId, version,
218             ActivityType.Upload_Network_Package, user, true, "", ""));
219
220     OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
221
222     return Response.ok(responseDto).build();
223   }
224
225   @Override
226   public Response updateFilesDataStructure(
227       String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
228
229     FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
230
231     ValidationResponse response = candidateManager
232         .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
233
234     if (!response.isValid()) {
235       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
236           new MapValidationResponseToDto()
237               .applyMapping(response, ValidationResponseDto.class)).build();
238     }
239     return Response.ok(fileDataStructureDto).build();
240   }
241
242   @Override
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));
249     }
250
251     FileDataStructureDto fileDataStructureDto =
252         filesDataStructure.map(dataStructure -> new MapFilesDataStructureToDto()
253             .applyMapping(dataStructure, FileDataStructureDto.class))
254             .orElse(new FileDataStructureDto());
255     return Response.ok(fileDataStructureDto).build();
256   }
257
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());
263     return result;
264   }
265
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;
273   }
274
275 }