48ad75d09cec240a4dc6ce01a918b280c9ba6cb4
[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.types.OnboardPackageInfo;
56 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
57 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
58 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
59 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
60 import org.openecomp.sdc.versioning.dao.types.Version;
61 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
62 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
63 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
64 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
65 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
66 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
67 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
68 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
69 import org.springframework.context.annotation.Scope;
70 import org.springframework.stereotype.Service;
71
72 @Named
73 @Service("orchestrationTemplateCandidate")
74 @Scope(value = "prototype")
75 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
76
77     private static final Logger LOGGER = LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
78     private final OrchestrationTemplateCandidateManager candidateManager;
79     private final VendorSoftwareProductManager vendorSoftwareProductManager;
80     private final ActivityLogManager activityLogManager;
81
82     public OrchestrationTemplateCandidateImpl() {
83         this.candidateManager = OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
84         this.vendorSoftwareProductManager = VspManagerFactory.getInstance().createInterface();
85         this.activityLogManager = ActivityLogManagerFactory.getInstance().createInterface();
86     }
87
88     // Constructor used in test to avoid mock static
89     public OrchestrationTemplateCandidateImpl(OrchestrationTemplateCandidateManager candidateManager,
90                                               VendorSoftwareProductManager vendorSoftwareProductManager, ActivityLogManager activityLogManager) {
91         this.candidateManager = candidateManager;
92         this.vendorSoftwareProductManager = vendorSoftwareProductManager;
93         this.activityLogManager = activityLogManager;
94     }
95
96     @Override
97     public Response upload(final String vspId, final String versionId, final Attachment fileToUpload, final String user) {
98         final byte[] fileToUploadBytes = fileToUpload.getObject(byte[].class);
99         final DataHandler dataHandler = fileToUpload.getDataHandler();
100         final String filename = ValidationUtils.sanitizeInputString(dataHandler.getName());
101         final OnboardingPackageProcessor onboardingPackageProcessor = new OnboardingPackageProcessor(filename, fileToUploadBytes);
102         if (onboardingPackageProcessor.hasErrors()) {
103             final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
104                 onboardingPackageProcessor.getErrorMessages().toArray(new ErrorMessage[0]));
105             return Response.status(Status.NOT_ACCEPTABLE).entity(uploadFileResponseDto).build();
106         }
107         final OnboardPackageInfo onboardPackageInfo = onboardingPackageProcessor.getOnboardPackageInfo().orElse(null);
108         if (onboardPackageInfo == null) {
109             final UploadFileResponseDto uploadFileResponseDto = buildUploadResponseWithError(
110                 new ErrorMessage(ErrorLevel.ERROR, Messages.PACKAGE_PROCESS_ERROR.formatMessage(filename)));
111             return Response.ok(uploadFileResponseDto).build();
112         }
113         final VspDetails vspDetails = new VspDetails(ValidationUtils.sanitizeInputString(vspId),
114             new Version(ValidationUtils.sanitizeInputString(versionId)));
115         return processOnboardPackage(onboardPackageInfo, vspDetails);
116     }
117
118     private Response processOnboardPackage(final OnboardPackageInfo onboardPackageInfo, final VspDetails vspDetails) {
119         final UploadFileResponse uploadFileResponse = candidateManager.upload(vspDetails, onboardPackageInfo);
120         final UploadFileResponseDto uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
121             .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
122         return Response.ok(uploadFileResponseDto).build();
123     }
124
125     private UploadFileResponseDto buildUploadResponseWithError(final ErrorMessage... errorMessages) {
126         final UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
127         final Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
128         final List<ErrorMessage> errorMessageList = new ArrayList<>();
129         Collections.addAll(errorMessageList, errorMessages);
130         errorMap.put(SdcCommon.UPLOAD_FILE, errorMessageList);
131         uploadFileResponseDto.setErrors(errorMap);
132         return uploadFileResponseDto;
133     }
134
135     @Override
136     public Response get(String vspId, String versionId, String user) throws IOException {
137         Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
138         String fileName;
139         if (zipFile.isPresent()) {
140             fileName = "Candidate." + zipFile.get().getLeft();
141         } else {
142             zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
143             if (!zipFile.isPresent()) {
144                 ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
145                     getErrorWithParameters(Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(), ""));
146                 LOGGER.error(errorMessage.getMessage());
147                 return Response.status(Response.Status.NOT_FOUND).build();
148             }
149             fileName = "Processed." + zipFile.get().getLeft();
150         }
151         Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
152         response.header("Content-Disposition", "attachment; filename=" + fileName);
153         return response.build();
154     }
155
156     @Override
157     public Response abort(String vspId, String versionId) {
158         candidateManager.abort(vspId, new Version(versionId));
159         return Response.ok().build();
160     }
161
162     @Override
163     public Response process(String vspId, String versionId, String user) {
164         Version version = new Version(versionId);
165         OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
166         activityLogManager.logActivity(new ActivityLogEntity(vspId, version, ActivityType.Upload_Network_Package, user, true, "", ""));
167         OrchestrationTemplateActionResponseDto responseDto = copyOrchestrationTemplateActionResponseToDto(response);
168         return Response.ok(responseDto).build();
169     }
170
171     @Override
172     public Response updateFilesDataStructure(String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user) {
173         FilesDataStructure fileDataStructure = copyFilesDataStructureDtoToFilesDataStructure(fileDataStructureDto);
174         ValidationResponse response = candidateManager.updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
175         if (!response.isValid()) {
176             return Response.status(Response.Status.EXPECTATION_FAILED)
177                 .entity(new MapValidationResponseToDto().applyMapping(response, ValidationResponseDto.class)).build();
178         }
179         return Response.ok(fileDataStructureDto).build();
180     }
181
182     @Override
183     public Response getFilesDataStructure(String vspId, String versionId, String user) {
184         Optional<FilesDataStructure> filesDataStructure = candidateManager.getFilesDataStructure(vspId, new Version(versionId));
185         if (!filesDataStructure.isPresent()) {
186             filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId, new Version(versionId));
187         }
188         FileDataStructureDto fileDataStructureDto = filesDataStructure
189             .map(dataStructure -> new MapFilesDataStructureToDto().applyMapping(dataStructure, FileDataStructureDto.class))
190             .orElse(new FileDataStructureDto());
191         return Response.ok(fileDataStructureDto).build();
192     }
193
194     private OrchestrationTemplateActionResponseDto copyOrchestrationTemplateActionResponseToDto(OrchestrationTemplateActionResponse response) {
195         OrchestrationTemplateActionResponseDto result = new OrchestrationTemplateActionResponseDto();
196         result.setErrors(response.getErrors());
197         result.setFileNames(response.getFileNames());
198         result.setStatus(response.getStatus());
199         return result;
200     }
201
202     private FilesDataStructure copyFilesDataStructureDtoToFilesDataStructure(FileDataStructureDto fileDataStructureDto) {
203         FilesDataStructure filesDataStructure = new FilesDataStructure();
204         filesDataStructure.setArtifacts(fileDataStructureDto.getArtifacts());
205         filesDataStructure.setModules(fileDataStructureDto.getModules());
206         filesDataStructure.setNested(fileDataStructureDto.getNested());
207         filesDataStructure.setUnassigned(fileDataStructureDto.getUnassigned());
208         return filesDataStructure;
209     }
210 }