cd18cf973b6fdc5b5e5da4374bb879063a48610f
[sdc.git] /
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 package org.openecomp.sdcrests.vsp.rest.services;
22
23 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
24
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.Collections;
28 import java.util.HashMap;
29 import java.util.List;
30 import java.util.Map;
31 import java.util.Optional;
32 import javax.activation.DataHandler;
33 import javax.inject.Named;
34 import javax.ws.rs.core.Response;
35 import javax.ws.rs.core.Response.Status;
36 import org.apache.commons.lang3.tuple.Pair;
37 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
38 import org.openecomp.sdc.activitylog.ActivityLogManager;
39 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
40 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
41 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
42 import org.openecomp.sdc.common.errors.Messages;
43 import org.openecomp.sdc.common.util.ValidationUtils;
44 import org.openecomp.sdc.common.utils.SdcCommon;
45 import org.openecomp.sdc.datatypes.error.ErrorLevel;
46 import org.openecomp.sdc.datatypes.error.ErrorMessage;
47 import org.openecomp.sdc.logging.api.Logger;
48 import org.openecomp.sdc.logging.api.LoggerFactory;
49 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
50 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
51 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
52 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
53 import org.openecomp.sdc.vendorsoftwareproduct.dao.type.VspDetails;
54 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.OnboardingPackageProcessor;
55 import org.openecomp.sdc.vendorsoftwareproduct.impl.onboarding.validation.CnfPackageValidator;
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
78     private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
79     private final OrchestrationTemplateCandidateManager candidateManager;
80     private final VendorSoftwareProductManager vendorSoftwareProductManager;
81     private final ActivityLogManager activityLogManager;
82
83     public OrchestrationTemplateCandidateImpl() {
84         this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
85         this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
86         this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
87     }
88
89     // Constructor used in test to avoid mock static
90     public OrchestrationTemplateCandidateImpl(OrchestrationTemplateCandidateManager candidateManager,
91                                               VendorSoftwareProductManager vendorSoftwareProductManager, 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, final Attachment fileToUpload, final String user) {
99         final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class);
100         final DataHandler dataHandler = fileToUpload.getDataHandler();
101         final String filename = ValidationUtils.sanitizeInputString(dataHandler.getName());
102         final OnboardingPackageProcessor onboardingPackageProcessor =
103             new OnboardingPackageProcessor(filename, fileToUploadBytes, new CnfPackageValidator());
104         final ErrorMessage[] errorMessages = onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0]);
105         if (onboardingPackageProcessor.hasErrors()) {
106             final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
107                 errorMessages);
108             return Response.status(Status.NOT_ACCEPTABLE).entity(uploadFileResponseDto).build();
109         }
110         final OnboardPackageInfo onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null);
111         if (onboardPackageInfo == null) {
112             final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
113                 new ErrorMessage(ErrorLevel.ERROR, Messages.PACKAGE_PROCESS_ERROR.formatMessage(filename)));
114             return Response.ok(uploadFileResponseDto).build();
115         }
116         final VspDetails vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId),
117             new Version(ValidationUtils.sanitizeInputString(versionId)));
118         return processOnboardPackage(onboardPackageInfo, vspDetails, errorMessages);
119     }
120
121     private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails, final ErrorMessage... errorMessages) {
122         final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo);
123         final UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
124             .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
125         if (errorMessages.length > 0) {
126             uploadFileResponseDto.setErrors(getErrorMap(errorMessages));
127         }
128         return Response.ok(uploadFileResponseDto).build();
129     }
130
131     private Map<String, List<ErrorMessage>> getErrorMap(ErrorMessage[] errorMessages) {
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         return errorMap;
137     }
138
139     private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) {
140         final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
141         uploadFileResponseDto.setErrors(getErrorMap(errorMessages));
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             if (!zipFile.isPresent()) {
154                 ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
155                     getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), ""));
156                 LOGGER.error(errorMessage.getMessage());
157                 return Response.status(Response.Status.NOT_FOUND).build();
158             }
159             fileName = "Processed." + zipFile.get().getLeft();
160         }
161         Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
162         response.header("Content-Disposition", "attachment; filename=" + fileName);
163         return response.build();
164     }
165
166     @Override
167     public Response abort(String vspId, String versionId) {
168         candidateManager.abort(vspId, new Version(versionId));
169         return Response.ok().build();
170     }
171
172     @Override
173     public Response process(String vspId, String versionId, String user) {
174         Version version = new Version(versionId);
175         OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
176         activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Upload_Network_Package, user, true, "", ""));
177         OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
178         return Response.ok(responseDto).build();
179     }
180
181     @Override
182     public Response updateFilesDataStructure(String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
183         FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
184         ValidationResponse response = candidateManager.updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
185         if (!response.isValid()) {
186             return Response.status(Response.Status.EXPECTATION_FAILED)
187                 .entity(new MapValidationResponseToDto().applyMapping(response, ValidationResponseDto.class)).build();
188         }
189         return Response.ok(fileDataStructureDto).build();
190     }
191
192     @Override
193     public Response getFilesDataStructure(String vspId, String versionId, String user) {
194         Optional<FilesDataStructure> filesDataStructure = candidateManager.getFilesDataStructure(vspId, new Version(versionId));
195         if (!filesDataStructure.isPresent()) {
196             filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId, new Version(versionId));
197         }
198         FileDataStructureDto fileDataStructureDto = filesDataStructure
199             .map(dataStructure -> new MapFilesDataStructureToDto().applyMapping(dataStructure, FileDataStructureDto.class))
200             .orElse(new FileDataStructureDto());
201         return Response.ok(fileDataStructureDto).build();
202     }
203
204     private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response) {
205         OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
206         result.setErrors(response.getErrors());
207         result.setFileNames(response.getFileNames());
208         result.setStatus(response.getStatus());
209         return result;
210     }
211
212     private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto) {
213         FilesDataStructure filesDataStructure = new FilesDataStructure();
214         filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
215         filesDataStructure.setModules(fileDataStructureDto.getModules());
216         filesDataStructure.setNested(fileDataStructureDto.getNested());
217         filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
218         return filesDataStructure;
219     }
220 }