c331deb134a43ebe782070b0760e3c793bdb3512
[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  *
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.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
23
24 import java.io.IOException;
25 import java.util.ArrayList;
26 import java.util.Collections;
27 import java.util.HashMap;
28 import java.util.List;
29 import java.util.Map;
30 import java.util.Optional;
31 import javax.activation.DataHandler;
32 import javax.inject.Named;
33 import javax.ws.rs.core.Response;
34 import org.apache.commons.lang3.tuple.Pair;
35 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
36 import org.openecomp.sdc.activitylog.ActivityLogManager;
37 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
38 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
39 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
40 import org.openecomp.sdc.common.errors.Messages;
41 import org.openecomp.sdc.common.utils.SdcCommon;
42 import org.openecomp.sdc.datatypes.error.ErrorLevel;
43 import org.openecomp.sdc.datatypes.error.ErrorMessage;
44 import org.openecomp.sdc.logging.api.Logger;
45 import org.openecomp.sdc.logging.api.LoggerFactory;
46 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
47 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
48 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
49 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
50 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
51 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.OnboardingPackageProcessor;
52 import org.openecomp.sdc.vendorsoftwareproduct.types.OnboardPackageInfo;
53 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
54 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
55 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
57 import org.openecomp.sdc.versioning.dao.types.Version;
58 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
59 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
60 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
61 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
62 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
63 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
64 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
65 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
66 import org.springframework.context.annotation.Scope;
67 import org.springframework.stereotype.Service;
68
69 @Named
70 @Service("orchestrationTemplateCandidate")
71 @Scope(value = "prototype")
72 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
73   private static final Logger LOGGER =
74       LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
75   private final OrchestrationTemplateCandidateManager candidateManager;
76
77   private final VendorSoftwareProductManager vendorSoftwareProductManager;
78   private final ActivityLogManager activityLogManager;
79
80
81   public OrchestrationTemplateCandidateImpl() {
82     this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
83     this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
84     this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
85   }
86
87   // Constructor used in test to avoid mock static
88   public OrchestrationTemplateCandidateImpl(
89       OrchestrationTemplateCandidateManager candidateManager,
90       VendorSoftwareProductManager vendorSoftwareProductManager,
91       ActivityLogManager activityLogManager) {
92     this.candidateManager = candidateManager;
93     this.vendorSoftwareProductManager = vendorSoftwareProductManager;
94     this.activityLogManager = activityLogManager;
95   }
96
97   @Override
98   public Response upload(final String vspId, final String versionId,
99                          final Attachment fileToUpload, final String user) {
100     final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class);
101     final DataHandler dataHandler = fileToUpload.getDataHandler();
102     final String filename = dataHandler.getName();
103
104     final OnboardingPackageProcessor onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes);
105     if (onboardingPackageProcessor.hasErrors()) {
106       final UploadFileResponseDto uploadFileResponseDto =
107           buildUploadResponseWithError(onboardingPackageProcessor.getErrorMessageSet().toArray(new ErrorMessage[0]));
108       return Response.ok(uploadFileResponseDto).build();
109     }
110
111     final OnboardPackageInfo onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null);
112
113     if (onboardPackageInfo == null) {
114       final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
115           new ErrorMessage(ErrorLevel.ERROR, Messages.PACKAGE_PROCESS_ERROR.formatMessage(filename)));
116       return Response.ok(uploadFileResponseDto).build();
117     }
118
119     final VspDetails vspDetails = new VspDetails(vspId, new Version(versionId));
120     return processOnboardPackage(onboardPackageInfo, vspDetails);
121   }
122
123     private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails) {
124         final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo);
125         final UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
126             .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
127         return Response.ok(uploadFileResponseDto).build();
128     }
129
130   private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) {
131     final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
132     final Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
133     final List<ErrorMessage> errorMessageList = new ArrayList<>();
134     Collections.addAll(errorMessageList, errorMessages);
135     errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList);
136     uploadFileResponseDto.setErrors(errorMap);
137     return uploadFileResponseDto;
138   }
139
140   @Override
141   public Response get(String vspId, String versionId, String user) throws IOException {
142     Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
143     String fileName;
144     if (zipFile.isPresent()) {
145       fileName = "Candidate." + zipFile.get().getLeft();
146     } else {
147       zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
148
149       if (!zipFile.isPresent()) {
150         ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
151             getErrorWithParameters(
152                 Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
153                 ""));
154         LOGGER.error(errorMessage.getMessage());
155         return Response.status(Response.Status.NOT_FOUND).build();
156       }
157       fileName = "Processed." + zipFile.get().getLeft();
158     }
159     Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
160     response.header("Content-Disposition", "attachment; filename=" + fileName);
161     return response.build();
162   }
163
164   @Override
165   public Response abort(String vspId, String versionId) {
166     candidateManager.abort(vspId, new Version(versionId));
167     return Response.ok().build();
168   }
169
170   @Override
171   public Response process(String vspId, String versionId, String user) {
172
173     Version version = new Version(versionId);
174     OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
175
176     activityLogManager.logActivity(new ActivityLogEntity(vspId, version,
177             ActivityType.Upload_Network_Package, user, true, "", ""));
178
179     OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
180
181     return Response.ok(responseDto).build();
182   }
183
184   @Override
185   public Response updateFilesDataStructure(
186       String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
187
188     FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
189
190     ValidationResponse response = candidateManager
191         .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
192
193     if (!response.isValid()) {
194       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
195           new MapValidationResponseToDto()
196               .applyMapping(response, ValidationResponseDto.class)).build();
197     }
198     return Response.ok(fileDataStructureDto).build();
199   }
200
201   @Override
202   public Response getFilesDataStructure(String vspId, String versionId, String user) {
203     Optional<FilesDataStructure> filesDataStructure =
204         candidateManager.getFilesDataStructure(vspId, new Version(versionId));
205     if (!filesDataStructure.isPresent()) {
206       filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId,
207           new Version(versionId));
208     }
209
210     FileDataStructureDto fileDataStructureDto =
211         filesDataStructure.map(dataStructure -> new MapFilesDataStructureToDto()
212             .applyMapping(dataStructure, FileDataStructureDto.class))
213             .orElse(new FileDataStructureDto());
214     return Response.ok(fileDataStructureDto).build();
215   }
216
217   private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response){
218     OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
219     result.setErrors(response.getErrors());
220     result.setFileNames(response.getFileNames());
221     result.setStatus(response.getStatus());
222     return result;
223   }
224
225   private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto){
226     FilesDataStructure filesDataStructure = new FilesDataStructure();
227     filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
228     filesDataStructure.setModules(fileDataStructureDto.getModules());
229     filesDataStructure.setNested(fileDataStructureDto.getNested());
230     filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
231     return filesDataStructure;
232   }
233
234 }