Refactors Single DMP Enpoint to support different formats (JSON, XML, DOCX)

This commit is contained in:
Diamantis Tziotzios 2019-02-06 12:46:14 +02:00
parent 86ae8e5eda
commit 2ebd3f1cb8
4 changed files with 62 additions and 36 deletions

View File

@ -4,6 +4,7 @@ package eu.eudat.controllers;
import eu.eudat.configurations.dynamicproject.DynamicProjectConfiguration; import eu.eudat.configurations.dynamicproject.DynamicProjectConfiguration;
import eu.eudat.data.dao.criteria.DynamicFieldsCriteria; import eu.eudat.data.dao.criteria.DynamicFieldsCriteria;
import eu.eudat.data.dao.criteria.RequestItem; import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.dao.entities.DMPDao;
import eu.eudat.data.entities.DMP; import eu.eudat.data.entities.DMP;
import eu.eudat.data.query.items.item.dmp.DataManagementPlanCriteriaRequest; import eu.eudat.data.query.items.item.dmp.DataManagementPlanCriteriaRequest;
import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest; import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest;
@ -11,6 +12,7 @@ import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException;
import eu.eudat.logic.managers.DataManagementPlanManager; import eu.eudat.logic.managers.DataManagementPlanManager;
import eu.eudat.logic.managers.DatasetManager; import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.services.ApiContext; import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.forms.VisibilityRuleService;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope; import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.models.data.dmp.DataManagementPlan; import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.helpermodels.Tuple; import eu.eudat.models.data.helpermodels.Tuple;
@ -71,11 +73,19 @@ public class DMPs extends BaseController {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
} }
@RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json") @RequestMapping(method = RequestMethod.GET, value = {"{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity<ResponseItem<DataManagementPlan>> getSingle(@PathVariable String id, Principal principal) throws IllegalAccessException, InstantiationException { ResponseEntity getSingle(@PathVariable String id,@RequestHeader("Content-Type") String contentType, Principal principal) throws IllegalAccessException, InstantiationException, IOException {
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, principal, this.dynamicProjectConfiguration); if(contentType.equals("application/xml") || contentType.equals("application/msword")){
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan)); DMPDao dmpDao = this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao();
VisibilityRuleService visibilityRuleService = this.getApiContext().getUtilitiesService().getVisibilityRuleService();
ResponseEntity<byte[]> document = this.dataManagementPlanManager.getDocument(this.environment, dmpDao, id, visibilityRuleService, contentType);
return document;
}
else{
eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, principal, this.dynamicProjectConfiguration);
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
}
} }
@Transactional @Transactional
@ -110,7 +120,6 @@ public class DMPs extends BaseController {
}catch (DMPWithDatasetsDeleteException exception){ }catch (DMPWithDatasetsDeleteException exception){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage())); return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
} }
} }
@RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json") @RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json")
@ -120,27 +129,7 @@ public class DMPs extends BaseController {
return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tuple<String, String>>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable)); return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tuple<String, String>>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
} }
@RequestMapping(method = RequestMethod.GET, value = {"/getXml/{id}"}) /*@RequestMapping(method = RequestMethod.GET, value = {"/getWord/{id}"})
public @ResponseBody
ResponseEntity<byte[]> getXml(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException {
FileEnvelope envelope = this.dataManagementPlanManager.getXmlDocument(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
InputStream resource = new FileInputStream(envelope.getFile());
System.out.println("Mime Type of " + envelope.getFilename() + " is " +
new MimetypesFileTypeMap().getContentType(envelope.getFile()));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(envelope.getFile().length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + envelope.getFilename() + ".xml");
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = IOUtils.toByteArray(resource);
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
@RequestMapping(method = RequestMethod.GET, value = {"/getWord/{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity<byte[]> getWordDocument(@PathVariable String id) throws IOException, IllegalAccessException, InstantiationException { ResponseEntity<byte[]> getWordDocument(@PathVariable String id) throws IOException, IllegalAccessException, InstantiationException {
File file = this.dataManagementPlanManager.getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService()); File file = this.dataManagementPlanManager.getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
@ -158,11 +147,12 @@ public class DMPs extends BaseController {
return new ResponseEntity<>(content, return new ResponseEntity<>(content,
responseHeaders, responseHeaders,
HttpStatus.OK); HttpStatus.OK);
} }*/
@RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"}) @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
public @ResponseBody public @ResponseBody
ResponseEntity<byte[]> getPDFDocument(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException, InterruptedException { ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
System.out.println(contentType);
File file = this.dataManagementPlanManager.getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService()); File file = this.dataManagementPlanManager.getWordDocument(this.environment, this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
File pdffile = new DatasetManager().convertToPDF(file, environment, file.getName()); File pdffile = new DatasetManager().convertToPDF(file, environment, file.getName());
InputStream resource = new FileInputStream(pdffile); InputStream resource = new FileInputStream(pdffile);

View File

@ -41,9 +41,11 @@ import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document; import org.w3c.dom.Document;
import org.w3c.dom.Element; import org.w3c.dom.Element;
import javax.activation.MimetypesFileTypeMap;
import java.io.*; import java.io.*;
import java.math.BigInteger; import java.math.BigInteger;
import java.net.URL; import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.util.*; import java.util.*;
import java.util.concurrent.CompletableFuture; import java.util.concurrent.CompletableFuture;
@ -385,7 +387,7 @@ public class DataManagementPlanManager {
ExportXmlBuilder xmlBuilder = new ExportXmlBuilder(); ExportXmlBuilder xmlBuilder = new ExportXmlBuilder();
eu.eudat.data.entities.DMP dmp = dmpRepository.find(UUID.fromString(id)); eu.eudat.data.entities.DMP dmp = dmpRepository.find(UUID.fromString(id));
List<Dataset> datasets = dmp.getDataset().stream().collect(Collectors.toList()); List<Dataset> datasets = dmp.getDataset().stream().collect(Collectors.toList());
File xmlFile = new File(UUID.randomUUID() + ".xml"); File xmlFile = new File(dmp.getLabel() + ".xml");
BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true)); BufferedWriter writer = new BufferedWriter(new FileWriter(xmlFile, true));
Document xmlDoc = XmlBuilder.getDocument(); Document xmlDoc = XmlBuilder.getDocument();
Element root = xmlDoc.createElement("root"); Element root = xmlDoc.createElement("root");
@ -439,7 +441,37 @@ public class DataManagementPlanManager {
FileEnvelope fileEnvelope = new FileEnvelope(); FileEnvelope fileEnvelope = new FileEnvelope();
fileEnvelope.setFile(xmlFile); fileEnvelope.setFile(xmlFile);
fileEnvelope.setFilename(dmp.getLabel()); fileEnvelope.setFilename(dmp.getLabel());
return fileEnvelope; return fileEnvelope;
} }
public ResponseEntity<byte[]> getDocument(Environment environment, DMPDao dmpDao, String id, VisibilityRuleService visibilityRuleService, String contentType) throws InstantiationException, IllegalAccessException, IOException{
File file;
switch (contentType){
case "application/xml":
file = getXmlDocument(dmpDao, id, visibilityRuleService).getFile();
break;
case "application/msword":
file = getWordDocument(environment, dmpDao, id, visibilityRuleService);
break;
default:
file = getXmlDocument(dmpDao, id, visibilityRuleService).getFile();
}
InputStream resource = new FileInputStream(file);
System.out.println("Mime Type of " + file.getName() + " is " +
new MimetypesFileTypeMap().getContentType(file));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.setContentLength(file.length());
responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getName());
responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");
byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource);
resource.close();
Files.deleteIfExists(file.toPath());
return new ResponseEntity<>(content,
responseHeaders,
HttpStatus.OK);
}
} }

View File

@ -17,10 +17,11 @@ import { BaseHttpService } from '../http/base-http.service';
export class DmpService { export class DmpService {
private actionUrl: string; private actionUrl: string;
private headers: HttpHeaders; private headers = new HttpHeaders();
constructor(private http: BaseHttpService, private httpClient: HttpClient) { constructor(private http: BaseHttpService, private httpClient: HttpClient) {
this.actionUrl = environment.Server + 'dmps/'; this.actionUrl = environment.Server + 'dmps/';
} }
getPaged(dataTableRequest: DataTableRequest<DmpCriteria>, fieldsGroup?: string): Observable<DataTableData<DmpListingModel>> { getPaged(dataTableRequest: DataTableRequest<DmpCriteria>, fieldsGroup?: string): Observable<DataTableData<DmpListingModel>> {
@ -41,7 +42,7 @@ export class DmpService {
return this.http.get<DmpModel>(this.actionUrl + id + '/unlock', { headers: this.headers }); return this.http.get<DmpModel>(this.actionUrl + id + '/unlock', { headers: this.headers });
} }
createDmp(dataManagementPlanModel: DmpModel): Observable<DmpModel> { createDmp(dataManagementPlanModel: DmpModel): Observable<DmpModel> {
return this.http.post<DmpModel>(this.actionUrl , dataManagementPlanModel, { headers: this.headers }); return this.http.post<DmpModel>(this.actionUrl, dataManagementPlanModel, { headers: this.headers });
} }
inactivate(id: String): Observable<DmpModel> { inactivate(id: String): Observable<DmpModel> {
@ -69,14 +70,17 @@ export class DmpService {
} }
public downloadXML(id: string): Observable<HttpResponse<Blob>> { public downloadXML(id: string): Observable<HttpResponse<Blob>> {
return this.httpClient.get(this.actionUrl + 'getXml/' + id, { responseType: 'blob', observe: 'response' }); let headerXml: HttpHeaders = this.headers.set('Content-Type', 'application/xml')
return this.httpClient.get(this.actionUrl + id, { responseType: 'blob', observe: 'response', headers: headerXml }); //+ "/getXml/"
} }
public downloadDocx(id: string): Observable<HttpResponse<Blob>> { public downloadDocx(id: string): Observable<HttpResponse<Blob>> {
return this.httpClient.get(this.actionUrl + 'getWord/' + id, { responseType: 'blob', observe: 'response' }); let headerDoc: HttpHeaders = this.headers.set('Content-Type', 'application/msword')
return this.httpClient.get(this.actionUrl + id, { responseType: 'blob', observe: 'response', headers: headerDoc });
} }
public downloadPDF(id: string): Observable<HttpResponse<Blob>> { public downloadPDF(id: string): Observable<HttpResponse<Blob>> {
return this.httpClient.get(this.actionUrl + 'getPDF/' + id, { responseType: 'blob', observe: 'response' }); let headerPdf: HttpHeaders = this.headers.set('Content-Type', 'application/pdf')
return this.httpClient.get(this.actionUrl + 'getPDF/' + id, { responseType: 'blob', observe: 'response', headers: headerPdf });
} }
} }

View File

@ -358,7 +358,7 @@ export class DmpEditorComponent extends BaseComponent implements OnInit, IBreadC
this.dmpService.downloadDocx(id) this.dmpService.downloadDocx(id)
.pipe(takeUntil(this._destroyed)) .pipe(takeUntil(this._destroyed))
.subscribe(response => { .subscribe(response => {
const blob = new Blob([response.body], { type: 'application/octet-stream' }); const blob = new Blob([response.body], { type: 'application/msword' });
const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition')); const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
FileSaver.saveAs(blob, filename); FileSaver.saveAs(blob, filename);
@ -369,7 +369,7 @@ export class DmpEditorComponent extends BaseComponent implements OnInit, IBreadC
this.dmpService.downloadPDF(id) this.dmpService.downloadPDF(id)
.pipe(takeUntil(this._destroyed)) .pipe(takeUntil(this._destroyed))
.subscribe(response => { .subscribe(response => {
const blob = new Blob([response.body], { type: 'application/octet-stream' }); const blob = new Blob([response.body], { type: 'application/pdf' });
const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition')); const filename = this.getFilenameFromContentDispositionHeader(response.headers.get('Content-Disposition'));
FileSaver.saveAs(blob, filename); FileSaver.saveAs(blob, filename);