use of de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport in project webanno by webanno.
the class LegacyRemoteApiController method annotationDocumentRead.
/**
* Download annotation document with requested parameters
*
* Test when running in Eclipse: Open your browser, paste following URL with appropriate values:
*
* http://USERNAME:PASSWORD@localhost:8080/webanno-webapp/api/projects/{aProjectId}/sourcedocs/{
* aSourceDocumentId}/annos/{annotatorName}?format="text"
*
* @param response
* HttpServletResponse.
* @param aProjectId
* {@link Project} ID.
* @param aSourceDocumentId
* {@link SourceDocument} ID.
* @param annotatorName
* {@link User} name.
* @param aFormatId
* Export format.
* @throws Exception
* if there was an error.
*/
@RequestMapping(value = "/" + PROJECTS + "/{" + PARAM_PROJECT_ID + "}/" + DOCUMENTS + "/{" + PARAM_DOCUMENT_ID + "}/" + ANNOTATIONS + "/{" + PARAM_USERNAME + "}", method = RequestMethod.GET)
public void annotationDocumentRead(HttpServletResponse response, @PathVariable(PARAM_PROJECT_ID) long aProjectId, @PathVariable(PARAM_DOCUMENT_ID) long aSourceDocumentId, @PathVariable(PARAM_USERNAME) String annotatorName, @RequestParam(value = PARAM_FORMAT, required = false) String aFormatId) throws Exception {
// Get current user
String username = SecurityContextHolder.getContext().getAuthentication().getName();
User user = userRepository.get(username);
if (user == null) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "User [" + username + "] not found.");
return;
}
// Get project
Project project;
try {
project = projectRepository.getProject(aProjectId);
} catch (NoResultException e) {
response.sendError(HttpStatus.NOT_FOUND.value(), "Project" + aProjectId + "] not found.");
return;
}
// Check for the access
boolean hasAccess = projectRepository.isManager(project, user) || userRepository.isAdministrator(user);
if (!hasAccess) {
response.sendError(HttpStatus.FORBIDDEN.value(), "User [" + username + "] is not allowed to access project [" + aProjectId + "]");
return;
}
// Get annotator user
User annotator = userRepository.get(annotatorName);
if (annotator == null) {
response.sendError(HttpStatus.BAD_REQUEST.value(), "Annotator user [" + annotatorName + "] not found.");
return;
}
// Get source document
SourceDocument srcDoc;
try {
srcDoc = documentRepository.getSourceDocument(aProjectId, aSourceDocumentId);
} catch (NoResultException e) {
response.sendError(HttpStatus.NOT_FOUND.value(), "Document [" + aSourceDocumentId + "] not found in project [" + aProjectId + "].");
return;
}
// Get annotation document
AnnotationDocument annDoc;
try {
annDoc = documentRepository.getAnnotationDocument(srcDoc, annotator);
} catch (NoResultException e) {
response.sendError(HttpStatus.NOT_FOUND.value(), "Annotations for user [" + annotatorName + "] not found on document [" + aSourceDocumentId + "] in project [" + aProjectId + "].");
return;
}
String formatId;
if (aFormatId == null) {
formatId = srcDoc.getFormat();
} else {
formatId = aFormatId;
}
// Determine the format
FormatSupport format = importExportService.getWritableFormatById(formatId).orElseGet(() -> {
LOG.info("[{}] Format [{}] is not writable - exporting as WebAnno TSV3 instead.", srcDoc.getName(), formatId);
return new WebAnnoTsv3FormatSupport();
});
// Temporary file of annotation document
File downloadableFile = importExportService.exportAnnotationDocument(srcDoc, annotatorName, format, annDoc.getName(), Mode.ANNOTATION);
try {
// Set mime type
String mimeType = URLConnection.guessContentTypeFromName(downloadableFile.getName());
if (mimeType == null) {
LOG.info("mimetype is not detectable, will take default");
mimeType = "application/octet-stream";
}
// Set response
response.setContentType(mimeType);
response.setContentType("application/force-download");
response.setHeader("Content-Disposition", "inline; filename=\"" + downloadableFile.getName() + "\"");
response.setContentLength((int) downloadableFile.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(downloadableFile));
FileCopyUtils.copy(inputStream, response.getOutputStream());
} catch (Exception e) {
LOG.info("Exception occured" + e.getMessage());
} finally {
if (downloadableFile.exists()) {
downloadableFile.delete();
}
}
}
use of de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport in project webanno by webanno.
the class AeroRemoteApiController method readAnnotation.
private ResponseEntity<byte[]> readAnnotation(long aProjectId, long aDocumentId, String aAnnotatorId, Mode aMode, Optional<String> aFormat) throws RemoteApiException, ClassNotFoundException, IOException, UIMAException {
// Get project (this also ensures that it exists and that the current user can access it
Project project = getProject(aProjectId);
SourceDocument doc = getDocument(project, aDocumentId);
// Check format
String formatId;
if (aFormat.isPresent()) {
if (VAL_ORIGINAL.equals(aFormat.get())) {
formatId = doc.getFormat();
} else {
formatId = aFormat.get();
}
} else {
formatId = doc.getFormat();
}
// Determine the format
FormatSupport format = importExportService.getWritableFormatById(formatId).orElseGet(() -> {
LOG.info("[{}] Format [{}] is not writable - exporting as WebAnno TSV3 instead.", doc.getName(), formatId);
return new WebAnnoTsv3FormatSupport();
});
// annotation document entry is actually properly set up in the database.
if (Mode.ANNOTATION.equals(aMode)) {
getAnnotation(doc, aAnnotatorId, false);
}
// Create a temporary export file from the annotations
File exportedAnnoFile = null;
byte[] resource;
try {
exportedAnnoFile = importExportService.exportAnnotationDocument(doc, aAnnotatorId, format, doc.getName(), Mode.ANNOTATION);
resource = FileUtils.readFileToByteArray(exportedAnnoFile);
} finally {
if (exportedAnnoFile != null) {
FileUtils.forceDelete(exportedAnnoFile);
}
}
String filename = FilenameUtils.removeExtension(doc.getName());
filename += "-" + aAnnotatorId;
// Actually, exportedAnnoFile cannot be null here - the warning can be ignored.
filename += "." + FilenameUtils.getExtension(exportedAnnoFile.getName());
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(resource.length);
httpHeaders.set("Content-Disposition", "attachment; filename=\"" + filename + "\"");
return new ResponseEntity<>(resource, httpHeaders, OK);
}
use of de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport in project webanno by webanno.
the class AeroRemoteApiController method documentRead.
@ApiOperation(value = "Get a document from a project", response = byte[].class)
@RequestMapping(value = "/" + PROJECTS + "/{" + PARAM_PROJECT_ID + "}/" + DOCUMENTS + "/{" + PARAM_DOCUMENT_ID + "}", method = RequestMethod.GET, produces = { APPLICATION_OCTET_STREAM_VALUE, APPLICATION_JSON_UTF8_VALUE })
public ResponseEntity documentRead(@PathVariable(PARAM_PROJECT_ID) long aProjectId, @PathVariable(PARAM_DOCUMENT_ID) long aDocumentId, @RequestParam(value = PARAM_FORMAT) Optional<String> aFormat) throws Exception {
// Get project (this also ensures that it exists and that the current user can access it
Project project = getProject(aProjectId);
SourceDocument doc = getDocument(project, aDocumentId);
boolean originalFile;
String formatId;
if (aFormat.isPresent()) {
if (VAL_ORIGINAL.equals(aFormat.get())) {
formatId = doc.getFormat();
originalFile = true;
} else {
formatId = aFormat.get();
originalFile = doc.getFormat().equals(formatId);
}
} else {
formatId = doc.getFormat();
originalFile = true;
}
if (originalFile) {
// Export the original file - no temporary file created here, we export directly from
// the file system
File docFile = documentService.getSourceDocumentFile(doc);
FileSystemResource resource = new FileSystemResource(docFile);
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(resource.contentLength());
httpHeaders.set("Content-Disposition", "attachment; filename=\"" + doc.getName() + "\"");
return new ResponseEntity<org.springframework.core.io.Resource>(resource, httpHeaders, OK);
} else {
// Export a converted file - here we first export to a local temporary file and then
// send that back to the client
// Check if the format is supported
FormatSupport format = importExportService.getWritableFormatById(formatId).orElseThrow(() -> new UnsupportedFormatException("Format [%s] cannot be exported. Exportable formats are %s.", aFormat, importExportService.getWritableFormats().stream().map(FormatSupport::getId).sorted().collect(Collectors.toList()).toString()));
// Create a temporary export file from the annotations
CAS cas = documentService.createOrReadInitialCas(doc);
File exportedFile = null;
try {
// Load the converted file into memory
exportedFile = importExportService.exportCasToFile(cas, doc, doc.getName(), format, true);
byte[] resource = FileUtils.readFileToByteArray(exportedFile);
// Send it back to the client
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentLength(resource.length);
httpHeaders.set("Content-Disposition", "attachment; filename=\"" + exportedFile.getName() + "\"");
return new ResponseEntity<>(resource, httpHeaders, OK);
} finally {
if (exportedFile != null) {
FileUtils.forceDelete(exportedFile);
}
}
}
}
Aggregations