Search in sources :

Example 6 with FormatSupport

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();
        }
    }
}
Also used : WebAnnoTsv3FormatSupport(de.tudarmstadt.ukp.clarin.webanno.tsv.WebAnnoTsv3FormatSupport) FormatSupport(de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport) User(de.tudarmstadt.ukp.clarin.webanno.security.model.User) BufferedInputStream(java.io.BufferedInputStream) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) SourceDocument(de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument) AnnotationDocument(de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument) WebAnnoTsv3FormatSupport(de.tudarmstadt.ukp.clarin.webanno.tsv.WebAnnoTsv3FormatSupport) NoResultException(javax.persistence.NoResultException) FileInputStream(java.io.FileInputStream) NoResultException(javax.persistence.NoResultException) UIMAException(org.apache.uima.UIMAException) IOException(java.io.IOException) Project(de.tudarmstadt.ukp.clarin.webanno.model.Project) BufferedInputStream(java.io.BufferedInputStream) ZipFile(java.util.zip.ZipFile) File(java.io.File) MultipartFile(org.springframework.web.multipart.MultipartFile) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Example 7 with FormatSupport

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);
}
Also used : WebAnnoTsv3FormatSupport(de.tudarmstadt.ukp.clarin.webanno.tsv.WebAnnoTsv3FormatSupport) FormatSupport(de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport) RProject(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.aero.model.RProject) Project(de.tudarmstadt.ukp.clarin.webanno.model.Project) HttpHeaders(org.springframework.http.HttpHeaders) ResponseEntity(org.springframework.http.ResponseEntity) SourceDocument(de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument) WebAnnoTsv3FormatSupport(de.tudarmstadt.ukp.clarin.webanno.tsv.WebAnnoTsv3FormatSupport) File(java.io.File) ZipFile(java.util.zip.ZipFile) MultipartFile(org.springframework.web.multipart.MultipartFile)

Example 8 with FormatSupport

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);
            }
        }
    }
}
Also used : WebAnnoTsv3FormatSupport(de.tudarmstadt.ukp.clarin.webanno.tsv.WebAnnoTsv3FormatSupport) FormatSupport(de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport) HttpHeaders(org.springframework.http.HttpHeaders) SourceDocument(de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument) FileSystemResource(org.springframework.core.io.FileSystemResource) RProject(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.aero.model.RProject) Project(de.tudarmstadt.ukp.clarin.webanno.model.Project) ResponseEntity(org.springframework.http.ResponseEntity) UnsupportedFormatException(de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.aero.exception.UnsupportedFormatException) CAS(org.apache.uima.cas.CAS) File(java.io.File) ZipFile(java.util.zip.ZipFile) MultipartFile(org.springframework.web.multipart.MultipartFile) ApiOperation(io.swagger.annotations.ApiOperation) RequestMapping(org.springframework.web.bind.annotation.RequestMapping)

Aggregations

FormatSupport (de.tudarmstadt.ukp.clarin.webanno.api.format.FormatSupport)8 Project (de.tudarmstadt.ukp.clarin.webanno.model.Project)7 WebAnnoTsv3FormatSupport (de.tudarmstadt.ukp.clarin.webanno.tsv.WebAnnoTsv3FormatSupport)7 File (java.io.File)7 SourceDocument (de.tudarmstadt.ukp.clarin.webanno.model.SourceDocument)6 IOException (java.io.IOException)6 ZipFile (java.util.zip.ZipFile)6 MultipartFile (org.springframework.web.multipart.MultipartFile)4 User (de.tudarmstadt.ukp.clarin.webanno.security.model.User)3 RequestMapping (org.springframework.web.bind.annotation.RequestMapping)3 ProjectExportException (de.tudarmstadt.ukp.clarin.webanno.api.export.ProjectExportException)2 ExportedProject (de.tudarmstadt.ukp.clarin.webanno.export.model.ExportedProject)2 AnnotationDocument (de.tudarmstadt.ukp.clarin.webanno.model.AnnotationDocument)2 RProject (de.tudarmstadt.ukp.clarin.webanno.webapp.remoteapi.aero.model.RProject)2 BufferedInputStream (java.io.BufferedInputStream)2 FileInputStream (java.io.FileInputStream)2 InputStream (java.io.InputStream)2 HashMap (java.util.HashMap)2 NoResultException (javax.persistence.NoResultException)2 Pair (org.apache.commons.lang3.tuple.Pair)2