4978b3fb34ec53ff49e710bdd4e439ff9718eb68
[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  */
16
17 package org.openecomp.sdcrests.vsp.rest.services;
18
19 import org.apache.commons.beanutils.BeanUtils;
20 import org.apache.commons.lang3.tuple.Pair;
21 import org.apache.cxf.jaxrs.ext.multipart.Attachment;
22 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
23 import org.openecomp.sdc.activitylog.ActivityLogManager;
24 import org.openecomp.sdc.activitylog.ActivityLogManagerFactory;
25 import org.openecomp.sdc.activitylog.dao.type.ActivityLogEntity;
26 import org.openecomp.sdc.activitylog.dao.type.ActivityType;
27 import org.openecomp.sdc.common.errors.Messages;
28 import org.openecomp.sdc.common.utils.SdcCommon;
29 import org.openecomp.sdc.datatypes.error.ErrorLevel;
30 import org.openecomp.sdc.datatypes.error.ErrorMessage;
31 import org.openecomp.sdc.logging.api.Logger;
32 import org.openecomp.sdc.logging.api.LoggerFactory;
33 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManager;
34 import org.openecomp.sdc.vendorsoftwareproduct.OrchestrationTemplateCandidateManagerFactory;
35 import org.openecomp.sdc.vendorsoftwareproduct.VendorSoftwareProductManager;
36 import org.openecomp.sdc.vendorsoftwareproduct.VspManagerFactory;
37 import org.openecomp.sdc.vendorsoftwareproduct.security.SecurityManagerException;
38 import org.openecomp.sdc.vendorsoftwareproduct.types.OrchestrationTemplateActionResponse;
39 import org.openecomp.sdc.vendorsoftwareproduct.types.UploadFileResponse;
40 import org.openecomp.sdc.vendorsoftwareproduct.types.ValidationResponse;
41 import org.openecomp.sdc.vendorsoftwareproduct.types.candidateheat.FilesDataStructure;
42 import org.openecomp.sdc.versioning.dao.types.Version;
43 import org.openecomp.sdcrests.vendorsoftwareproducts.types.FileDataStructureDto;
44 import org.openecomp.sdcrests.vendorsoftwareproducts.types.OrchestrationTemplateActionResponseDto;
45 import org.openecomp.sdcrests.vendorsoftwareproducts.types.UploadFileResponseDto;
46 import org.openecomp.sdcrests.vendorsoftwareproducts.types.ValidationResponseDto;
47 import org.openecomp.sdcrests.vsp.rest.OrchestrationTemplateCandidate;
48 import org.openecomp.sdcrests.vsp.rest.data.PackageArchive;
49 import org.openecomp.sdcrests.vsp.rest.mapping.MapFilesDataStructureToDto;
50 import org.openecomp.sdcrests.vsp.rest.mapping.MapUploadFileResponseToUploadFileResponseDto;
51 import org.openecomp.sdcrests.vsp.rest.mapping.MapValidationResponseToDto;
52 import org.springframework.context.annotation.Scope;
53 import org.springframework.stereotype.Service;
54
55 import javax.inject.Named;
56 import javax.ws.rs.core.Response;
57 import java.io.ByteArrayInputStream;
58 import java.io.IOException;
59 import java.lang.reflect.InvocationTargetException;
60 import java.util.ArrayList;
61 import java.util.HashMap;
62 import java.util.List;
63 import java.util.Map;
64 import java.util.Optional;
65
66 import static org.openecomp.core.utilities.file.FileUtils.getFileExtension;
67 import static org.openecomp.core.utilities.file.FileUtils.getNetworkPackageName;
68 import static org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder.getErrorWithParameters;
69
70 @Named
71 @Service("orchestrationTemplateCandidate")
72 @Scope(value = "prototype")
73 public class OrchestrationTemplateCandidateImpl implements OrchestrationTemplateCandidate {
74   private static final Logger LOGGER =
75       LoggerFactory.getLogger(OrchestrationTemplateCandidateImpl.class);
76   private OrchestrationTemplateCandidateManager candidateManager =
77       OrchestrationTemplateCandidateManagerFactory.getInstance().createInterface();
78   private VendorSoftwareProductManager vendorSoftwareProductManager = VspManagerFactory
79       .getInstance().createInterface();
80   private ActivityLogManager activityLogManager =
81           ActivityLogManagerFactory.getInstance().createInterface();
82
83   @Override
84   public Response upload(String vspId, String versionId, Attachment fileToUpload, String user) {
85     PackageArchive archive = new PackageArchive(fileToUpload.getObject(byte[].class));
86     UploadFileResponseDto uploadFileResponseDto;
87     try {
88       if (archive.isSigned() && !archive.isSignatureValid()) {
89         ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
90                 getErrorWithParameters(Messages.FAILED_TO_VERIFY_SIGNATURE.getErrorMessage(), ""));
91         LOGGER.error(errorMessage.getMessage());
92         uploadFileResponseDto = buildUploadResponseWithError(errorMessage);
93         //returning OK as SDC UI won't show error message if NOT OK error code.
94         return Response.ok(uploadFileResponseDto).build();
95       }
96
97       String filename = archive.getArchiveFileName().orElse(fileToUpload.getContentDisposition().getFilename());
98       UploadFileResponse uploadFileResponse = candidateManager
99               .upload(vspId, new Version(versionId), new ByteArrayInputStream(archive.getPackageFileContents()),
100                       getFileExtension(filename), getNetworkPackageName(filename));
101
102       uploadFileResponseDto = new MapUploadFileResponseToUploadFileResponseDto()
103               .applyMapping(uploadFileResponse, UploadFileResponseDto.class);
104     } catch (SecurityManagerException e) {
105       ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
106               getErrorWithParameters(e.getMessage(), ""));
107       LOGGER.error(errorMessage.getMessage(), e);
108       uploadFileResponseDto = buildUploadResponseWithError(errorMessage);
109       //returning OK as SDC UI won't show error message if NOT OK error code.
110       return Response.ok(uploadFileResponseDto).build();
111     }
112     return Response.ok(uploadFileResponseDto).build();
113   }
114
115   private UploadFileResponseDto buildUploadResponseWithError(ErrorMessage errorMessage) {
116     UploadFileResponseDto uploadFileResponseDto = new UploadFileResponseDto();
117     Map<String, List<ErrorMessage>> errorMap = new HashMap<>();
118     List<ErrorMessage> errorMessages = new ArrayList<>();
119     errorMessages.add(errorMessage);
120     errorMap.put(SdcCommon.UPLOAD_FILE, errorMessages);
121     uploadFileResponseDto.setErrors(errorMap);
122     return uploadFileResponseDto;
123   }
124
125   @Override
126   public Response get(String vspId, String versionId, String user) throws IOException {
127     Optional<Pair<String, byte[]>> zipFile = candidateManager.get(vspId, new Version(versionId));
128     String fileName = null;
129     if (zipFile.isPresent()) {
130       fileName = "Candidate." + zipFile.get().getLeft();
131     } else {
132       zipFile = vendorSoftwareProductManager.get(vspId, new Version((versionId)));
133
134       if (!zipFile.isPresent()) {
135         ErrorMessage errorMessage = new ErrorMessage(ErrorLevel.ERROR,
136             getErrorWithParameters(
137                 Messages.NO_FILE_WAS_UPLOADED_OR_FILE_NOT_EXIST.getErrorMessage(),
138                 ""));
139         LOGGER.error(errorMessage.getMessage());
140         return Response.status(Response.Status.NOT_FOUND).build();
141       }
142       fileName = "Processed." + zipFile.get().getLeft();
143     }
144     Response.ResponseBuilder response = Response.ok(zipFile.get().getRight());
145     response.header("Content-Disposition", "attachment; filename=" + fileName);
146     return response.build();
147   }
148
149   @Override
150   public Response abort(String vspId, String versionId) throws Exception {
151     candidateManager.abort(vspId, new Version(versionId));
152     return Response.ok().build();
153   }
154
155   @Override
156   public Response process(String vspId, String versionId, String user)
157       throws InvocationTargetException, IllegalAccessException {
158
159     Version version = new Version(versionId);
160     OrchestrationTemplateActionResponse response = candidateManager.process(vspId, version);
161
162     activityLogManager.logActivity(new ActivityLogEntity(vspId, version,
163             ActivityType.Upload_Network_Package, user, true, "", ""));
164
165     OrchestrationTemplateActionResponseDto responseDto =
166         new OrchestrationTemplateActionResponseDto();
167     BeanUtils.copyProperties(responseDto, response);
168
169     return Response.ok(responseDto).build();
170   }
171
172   @Override
173   public Response updateFilesDataStructure(
174       String vspId, String versionId, FileDataStructureDto fileDataStructureDto, String user)
175       throws Exception {
176
177     FilesDataStructure fileDataStructure = new FilesDataStructure();
178     try {
179       BeanUtils.copyProperties(fileDataStructure, fileDataStructureDto);
180     } catch (IllegalAccessException | InvocationTargetException exception) {
181       String errorWithParameters = ErrorMessagesFormatBuilder
182           .getErrorWithParameters(Messages.MAPPING_OBJECTS_FAILURE.getErrorMessage(),
183               fileDataStructureDto.toString(), fileDataStructure.toString());
184       throw new OrchestrationTemplateCandidateException(errorWithParameters, exception);
185     }
186     ValidationResponse response = candidateManager
187         .updateFilesDataStructure(vspId, new Version(versionId), fileDataStructure);
188
189     if (!response.isValid()) {
190       return Response.status(Response.Status.EXPECTATION_FAILED).entity(
191           new MapValidationResponseToDto()
192               .applyMapping(response, ValidationResponseDto.class)).build();
193     }
194     return Response.ok(fileDataStructureDto).build();
195   }
196
197   @Override
198   public Response getFilesDataStructure(String vspId, String versionId, String user)
199       throws Exception {
200     Optional<FilesDataStructure> filesDataStructure =
201         candidateManager.getFilesDataStructure(vspId, new Version(versionId));
202     if (!filesDataStructure.isPresent()) {
203       filesDataStructure = vendorSoftwareProductManager.getOrchestrationTemplateStructure(vspId,
204           new Version(versionId));
205     }
206
207     FileDataStructureDto fileDataStructureDto =
208         filesDataStructure.map(dataStructure -> new MapFilesDataStructureToDto()
209             .applyMapping(dataStructure, FileDataStructureDto.class))
210             .orElse(new FileDataStructureDto());
211     return Response.ok(fileDataStructureDto).build();
212   }
213
214 }