Fix Security Vulnerabilities
[sdc.git] / openecomp-be / api / openecomp-sdc-rest-webapp / vendor-software-products-rest / vendor-software-products-rest-services / src / main / java / org / openecomp / sdcrests / vsp / rest / services / OrchestrationTemplateCandidateImpl.java
1 /*
2  * Copyright © 2016-2018 European Support Limited
3  * Copyright © 2021 Nokia
4  * Copyright © 2021 Nordix Foundation
5  *
6  * Licensed under the Apache License, Version 2.0 (the "License");
7  * you may not use this file except in compliance with the License.
8  * You may obtain a copy of the License at
9  *
10  *      http://www.apache.org/licenses/LICENSE-2.0
11  *
12  * Unless required by applicable law or agreed to in writing, software
13  * distributed under the License is distributed on an "AS IS" BASIS,
14  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15  * See the License for the specific language governing permissions and
16  * limitations under the License.
17  * ============LICENSE_END=========================================================
18  * Modifications copyright (c) 2019 Nokia
19  * ================================================================================
20  */
21
22 package org.openecomp.sdcrests.vsp.rest.services;
23
24 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
25
26 import java.io.IOException;
27 import java.util.ArrayList;
28 import java.util.Collections;
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 javax.ws.rs.core.Response.Status;
37 import org.apache.commons.lang3.tuple.Pair;
38 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
39 import org.openecomp.sdc.activitylog.ActivityLogManager;
40 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
41 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
42 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
43 import org.openecomp.sdc.common.errors.Messages;
44 import org.openecomp.sdc.common.util.ValidationUtils;
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.impl.onboarding.OnboardingPackageProcessor;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
57 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
58 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
59 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
60 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
61 import org.openecomp.sdc.versioning.dao.types.Version;
62 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
63 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
64 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
65 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
66 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
67 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
68 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
69 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
70 import org.springframework.context.annotation.Scope;
71 import org.springframework.stereotype.Service;
72
73 @Named
74 @Service("orchestrationTemplateCandidate")
75 @Scope(value = "prototype")
76 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
77   private static final Logger LOGGER =
78       LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
79   private final OrchestrationTemplateCandidateManager candidateManager;
80
81   private final VendorSoftwareProductManager vendorSoftwareProductManager;
82   private final ActivityLogManager activityLogManager;
83
84
85   public OrchestrationTemplateCandidateImpl() {
86     this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
87     this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
88     this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
89   }
90
91   // Constructor used in test to avoid mock static
92   public OrchestrationTemplateCandidateImpl(
93       OrchestrationTemplateCandidateManager candidateManager,
94       VendorSoftwareProductManager vendorSoftwareProductManager,
95       ActivityLogManager activityLogManager) {
96     this.candidateManager = candidateManager;
97     this.vendorSoftwareProductManager = vendorSoftwareProductManager;
98     this.activityLogManager = activityLogManager;
99   }
100
101   @Override
102   public Response upload(final String vspId, final String versionId,
103                          final Attachment fileToUpload, final String user) {
104     final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class);
105     final DataHandler dataHandler = fileToUpload.getDataHandler();
106     final String filename = ValidationUtils.sanitizeInputString(dataHandler.getName());
107
108     final OnboardingPackageProcessor onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes);
109     if (onboardingPackageProcessor.hasErrors()) {
110       final UploadFileResponseDto uploadFileResponseDto =
111           buildUploadResponseWithError(onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0]));
112       return Response.status(Status.NOT_ACCEPTABLE).entity(uploadFileResponseDto).build();
113     }
114
115     final OnboardPackageInfo onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null);
116
117     if (onboardPackageInfo == null) {
118       final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
119           new ErrorMessage(ErrorLevel.ERROR, Messages.PACKAGE_PROCESS_ERROR.formatMessage(filename)));
120       return Response.ok(uploadFileResponseDto).build();
121     }
122
123     final VspDetails vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId),
124         new Version(ValidationUtils.sanitizeInputString(versionId)));
125     return processOnboardPackage(onboardPackageInfo, vspDetails);
126   }
127
128     private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails) {
129         final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo);
130         final UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
131             .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
132         return Response.ok(uploadFileResponseDto).build();
133     }
134
135   private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) {
136     final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
137     final Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
138     final List<ErrorMessage> errorMessageList = new ArrayList<>();
139     Collections.addAll(errorMessageList, errorMessages);
140     errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList);
141     uploadFileResponseDto.setErrors(errorMap);
142     return uploadFileResponseDto;
143   }
144
145   @Override
146   public Response get(String vspId, String versionId, String user) throws IOException {
147     Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
148     String fileName;
149     if (zipFile.isPresent()) {
150       fileName = "Candidate." + zipFile.get().getLeft();
151     } else {
152       zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
153
154       if (!zipFile.isPresent()) {
155         ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
156             getErrorWithParameters(
157                 Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
158                 ""));
159         LOGGER.error(errorMessage.getMessage());
160         return Response.status(Response.Status.NOT_FOUND).build();
161       }
162       fileName = "Processed." + zipFile.get().getLeft();
163     }
164     Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
165     response.header("Content-Disposition", "attachment; filename=" + fileName);
166     return response.build();
167   }
168
169   @Override
170   public Response abort(String vspId, String versionId) {
171     candidateManager.abort(vspId, new Version(versionId));
172     return Response.ok().build();
173   }
174
175   @Override
176   public Response process(String vspId, String versionId, String user) {
177
178     Version version = new Version(versionId);
179     OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
180
181     activityLogManager.logActivity(new ActivityLogEntity(vspId, version,
182             ActivityType.Upload_Network_Package, user, true, "", ""));
183
184     OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
185
186     return Response.ok(responseDto).build();
187   }
188
189   @Override
190   public Response updateFilesDataStructure(
191       String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
192
193     FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
194
195     ValidationResponse response = candidateManager
196         .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
197
198     if (!response.isValid()) {
199       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
200           new MapValidationResponseToDto()
201               .applyMapping(response, ValidationResponseDto.class)).build();
202     }
203     return Response.ok(fileDataStructureDto).build();
204   }
205
206   @Override
207   public Response getFilesDataStructure(String vspId, String versionId, String user) {
208     Optional<FilesDataStructure> filesDataStructure =
209         candidateManager.getFilesDataStructure(vspId, new Version(versionId));
210     if (!filesDataStructure.isPresent()) {
211       filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId,
212           new Version(versionId));
213     }
214
215     FileDataStructureDto fileDataStructureDto =
216         filesDataStructure.map(dataStructure -> new MapFilesDataStructureToDto()
217             .applyMapping(dataStructure, FileDataStructureDto.class))
218             .orElse(new FileDataStructureDto());
219     return Response.ok(fileDataStructureDto).build();
220   }
221
222   private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response){
223     OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
224     result.setErrors(response.getErrors());
225     result.setFileNames(response.getFileNames());
226     result.setStatus(response.getStatus());
227     return result;
228   }
229
230   private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto){
231     FilesDataStructure filesDataStructure = new FilesDataStructure();
232     filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
233     filesDataStructure.setModules(fileDataStructureDto.getModules());
234     filesDataStructure.setNested(fileDataStructureDto.getNested());
235     filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
236     return filesDataStructure;
237   }
238
239 }