Search in sources :

Example 96 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project stanbol by apache.

the class JobsResource method get.

/**
     * To read a /reasoners job output.
     * 
     * @param id
     * @return
     */
@GET
@Path("/{jid}")
public Response get(@PathParam("jid") String id, @Context HttpHeaders headers) {
    log.info("Pinging job {}", id);
    // No id
    if (id == null || id.equals("")) {
        ResponseBuilder rb = Response.status(Status.BAD_REQUEST);
        return rb.build();
    }
    JobManager m = getJobManager();
    // If the job exists
    if (m.hasJob(id)) {
        log.info("Found job with id {}", id);
        Future<?> f = m.ping(id);
        if (f.isDone() && (!f.isCancelled())) {
            /**
                 * We return OK with the result
                 */
            Object o;
            try {
                o = f.get();
                if (o instanceof ReasoningServiceResult) {
                    log.debug("Is a ReasoningServiceResult");
                    ReasoningServiceResult<?> result = (ReasoningServiceResult<?>) o;
                    return new ResponseTaskBuilder(new JobResultResource(uriInfo, headers)).build(result);
                } else {
                    log.error("Job {} does not belong to reasoners", id);
                    throw new WebApplicationException(Response.Status.NOT_FOUND);
                }
            } catch (InterruptedException e) {
                log.error("Error: ", e);
                throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
            } catch (ExecutionException e) {
                log.error("Error: ", e);
                throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR);
            }
        } else {
            /**
                 * We return 404 with additional info
                 */
            String jobService = new StringBuilder().append(getPublicBaseUri()).append("jobs/").append(id).toString();
            this.jobLocation = jobService;
            Viewable viewable = new Viewable("404.ftl", this);
            ResponseBuilder rb = Response.status(Status.NOT_FOUND);
            rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML + "; charset=utf-8");
            rb.entity(viewable);
            return rb.build();
        }
    } else {
        log.info("No job found with id {}", id);
        ResponseBuilder rb = Response.status(Status.NOT_FOUND);
        rb.header(HttpHeaders.CONTENT_TYPE, MediaType.TEXT_HTML + "; charset=utf-8");
        return rb.build();
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ReasoningServiceResult(org.apache.stanbol.reasoners.web.utils.ReasoningServiceResult) JobManager(org.apache.stanbol.commons.jobs.api.JobManager) ResponseTaskBuilder(org.apache.stanbol.reasoners.web.utils.ResponseTaskBuilder) Viewable(org.apache.stanbol.commons.web.viewable.Viewable) ResponseBuilder(javax.ws.rs.core.Response.ResponseBuilder) ExecutionException(java.util.concurrent.ExecutionException) Path(javax.ws.rs.Path) GET(javax.ws.rs.GET)

Example 97 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project tika by apache.

the class TikaResource method createParser.

@SuppressWarnings("serial")
public static Parser createParser() {
    final Parser parser = new AutoDetectParser(tikaConfig);
    Map<MediaType, Parser> parsers = ((AutoDetectParser) parser).getParsers();
    parsers.put(MediaType.APPLICATION_XML, new HtmlParser());
    ((AutoDetectParser) parser).setParsers(parsers);
    ((AutoDetectParser) parser).setFallback(new Parser() {

        public Set<MediaType> getSupportedTypes(ParseContext parseContext) {
            return parser.getSupportedTypes(parseContext);
        }

        public void parse(InputStream inputStream, ContentHandler contentHandler, Metadata metadata, ParseContext parseContext) {
            throw new WebApplicationException(Response.Status.UNSUPPORTED_MEDIA_TYPE);
        }
    });
    if (digester != null) {
        return new DigestingParser(parser, digester);
    }
    return parser;
}
Also used : HtmlParser(org.apache.tika.parser.html.HtmlParser) Set(java.util.Set) WebApplicationException(javax.ws.rs.WebApplicationException) InputStream(java.io.InputStream) ParseContext(org.apache.tika.parser.ParseContext) Metadata(org.apache.tika.metadata.Metadata) AutoDetectParser(org.apache.tika.parser.AutoDetectParser) MediaType(org.apache.tika.mime.MediaType) DigestingParser(org.apache.tika.parser.DigestingParser) BoilerpipeContentHandler(org.apache.tika.parser.html.BoilerpipeContentHandler) ExpandedTitleContentHandler(org.apache.tika.sax.ExpandedTitleContentHandler) BodyContentHandler(org.apache.tika.sax.BodyContentHandler) ContentHandler(org.xml.sax.ContentHandler) RichTextContentHandler(org.apache.tika.sax.RichTextContentHandler) Parser(org.apache.tika.parser.Parser) HtmlParser(org.apache.tika.parser.html.HtmlParser) AutoDetectParser(org.apache.tika.parser.AutoDetectParser) DigestingParser(org.apache.tika.parser.DigestingParser)

Example 98 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project tika by apache.

the class TikaResource method produceOutput.

private StreamingOutput produceOutput(final InputStream is, final MultivaluedMap<String, String> httpHeaders, final UriInfo info, final String format) {
    final Parser parser = createParser();
    final Metadata metadata = new Metadata();
    final ParseContext context = new ParseContext();
    fillMetadata(parser, metadata, context, httpHeaders);
    fillParseContext(context, httpHeaders, parser);
    logRequest(LOG, info, metadata);
    return new StreamingOutput() {

        public void write(OutputStream outputStream) throws IOException, WebApplicationException {
            Writer writer = new OutputStreamWriter(outputStream, UTF_8);
            ContentHandler content;
            try {
                SAXTransformerFactory factory = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
                TransformerHandler handler = factory.newTransformerHandler();
                handler.getTransformer().setOutputProperty(OutputKeys.METHOD, format);
                handler.getTransformer().setOutputProperty(OutputKeys.INDENT, "yes");
                handler.getTransformer().setOutputProperty(OutputKeys.ENCODING, UTF_8.name());
                handler.setResult(new StreamResult(writer));
                content = new ExpandedTitleContentHandler(handler);
            } catch (TransformerConfigurationException e) {
                throw new WebApplicationException(e);
            }
            parse(parser, LOG, info.getPath(), is, content, metadata, context);
        }
    };
}
Also used : TransformerHandler(javax.xml.transform.sax.TransformerHandler) StreamResult(javax.xml.transform.stream.StreamResult) TransformerConfigurationException(javax.xml.transform.TransformerConfigurationException) WebApplicationException(javax.ws.rs.WebApplicationException) OutputStream(java.io.OutputStream) Metadata(org.apache.tika.metadata.Metadata) SAXTransformerFactory(javax.xml.transform.sax.SAXTransformerFactory) StreamingOutput(javax.ws.rs.core.StreamingOutput) BoilerpipeContentHandler(org.apache.tika.parser.html.BoilerpipeContentHandler) ExpandedTitleContentHandler(org.apache.tika.sax.ExpandedTitleContentHandler) BodyContentHandler(org.apache.tika.sax.BodyContentHandler) ContentHandler(org.xml.sax.ContentHandler) RichTextContentHandler(org.apache.tika.sax.RichTextContentHandler) ExpandedTitleContentHandler(org.apache.tika.sax.ExpandedTitleContentHandler) Parser(org.apache.tika.parser.Parser) HtmlParser(org.apache.tika.parser.html.HtmlParser) AutoDetectParser(org.apache.tika.parser.AutoDetectParser) DigestingParser(org.apache.tika.parser.DigestingParser) ParseContext(org.apache.tika.parser.ParseContext) OutputStreamWriter(java.io.OutputStreamWriter) Writer(java.io.Writer) OutputStreamWriter(java.io.OutputStreamWriter)

Example 99 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project tika by apache.

the class UnpackerResource method process.

private Map<String, byte[]> process(InputStream is, @Context HttpHeaders httpHeaders, @Context UriInfo info, boolean saveAll) throws Exception {
    Metadata metadata = new Metadata();
    ParseContext pc = new ParseContext();
    Parser parser = TikaResource.createParser();
    if (parser instanceof DigestingParser) {
        //no need to digest for unwrapping
        parser = ((DigestingParser) parser).getWrappedParser();
    }
    TikaResource.fillMetadata(parser, metadata, pc, httpHeaders.getRequestHeaders());
    TikaResource.logRequest(LOG, info, metadata);
    ContentHandler ch;
    ByteArrayOutputStream text = new ByteArrayOutputStream();
    if (saveAll) {
        ch = new BodyContentHandler(new RichTextContentHandler(new OutputStreamWriter(text, UTF_8)));
    } else {
        ch = new DefaultHandler();
    }
    Map<String, byte[]> files = new HashMap<>();
    MutableInt count = new MutableInt();
    pc.set(EmbeddedDocumentExtractor.class, new MyEmbeddedDocumentExtractor(count, files));
    TikaResource.parse(parser, LOG, info.getPath(), is, ch, metadata, pc);
    if (count.intValue() == 0 && !saveAll) {
        throw new WebApplicationException(Response.Status.NO_CONTENT);
    }
    if (saveAll) {
        files.put(TEXT_FILENAME, text.toByteArray());
        ByteArrayOutputStream metaStream = new ByteArrayOutputStream();
        metadataToCsv(metadata, metaStream);
        files.put(META_FILENAME, metaStream.toByteArray());
    }
    return files;
}
Also used : BodyContentHandler(org.apache.tika.sax.BodyContentHandler) WebApplicationException(javax.ws.rs.WebApplicationException) HashMap(java.util.HashMap) Metadata(org.apache.tika.metadata.Metadata) DigestingParser(org.apache.tika.parser.DigestingParser) ByteArrayOutputStream(java.io.ByteArrayOutputStream) BodyContentHandler(org.apache.tika.sax.BodyContentHandler) ContentHandler(org.xml.sax.ContentHandler) RichTextContentHandler(org.apache.tika.sax.RichTextContentHandler) Parser(org.apache.tika.parser.Parser) OfficeParser(org.apache.tika.parser.microsoft.OfficeParser) DigestingParser(org.apache.tika.parser.DigestingParser) DefaultHandler(org.xml.sax.helpers.DefaultHandler) RichTextContentHandler(org.apache.tika.sax.RichTextContentHandler) MutableInt(org.apache.commons.lang.mutable.MutableInt) ParseContext(org.apache.tika.parser.ParseContext) OutputStreamWriter(java.io.OutputStreamWriter)

Example 100 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project stanbol by apache.

the class RepresentationReader method readFrom.

@Override
public Map<String, Representation> readFrom(Class<Map<String, Representation>> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    log.info("Read Representations from Request Data");
    long start = System.currentTimeMillis();
    //(1) get the charset and the acceptedMediaType
    String charset = "UTF-8";
    if (mediaType.getParameters().containsKey("charset")) {
        charset = mediaType.getParameters().get("charset");
    }
    MediaType acceptedMediaType = getAcceptedMediaType(httpHeaders);
    log.info("readFrom: mediaType {} | accepted {} | charset {}", new Object[] { mediaType, acceptedMediaType, charset });
    // (2) read the Content from the request (this needs to deal with  
    //    MediaType.APPLICATION_FORM_URLENCODED_TYPE and 
    //    MediaType.MULTIPART_FORM_DATA_TYPE requests!
    RequestData content;
    if (mediaType.isCompatible(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        try {
            content = MessageBodyReaderUtils.formForm(entityStream, charset, "encoding", Arrays.asList("entity", "content"));
        } catch (IllegalArgumentException e) {
            log.info("Bad Request: {}", e);
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.toString()).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        }
        if (content.getMediaType() == null) {
            String message = String.format("Missing parameter %s used to specify the media type" + "(supported values: %s", "encoding", supportedMediaTypes);
            log.info("Bad Request: {}", message);
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        }
        if (!isSupported(content.getMediaType())) {
            String message = String.format("Unsupported Content-Type specified by parameter " + "encoding=%s (supported: %s)", content.getMediaType().toString(), supportedMediaTypes);
            log.info("Bad Request: {}", message);
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        }
    } else if (mediaType.isCompatible(MediaType.MULTIPART_FORM_DATA_TYPE)) {
        log.info("read from MimeMultipart");
        List<RequestData> contents;
        try {
            contents = MessageBodyReaderUtils.fromMultipart(entityStream, mediaType);
        } catch (IllegalArgumentException e) {
            log.info("Bad Request: {}", e.toString());
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(e.toString()).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        }
        if (contents.isEmpty()) {
            String message = "Request does not contain any Mime BodyParts.";
            log.info("Bad Request: {}", message);
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        } else if (contents.size() > 1) {
            //print warnings about ignored parts
            log.warn("{} Request contains more than one Parts: others than " + "the first will be ignored", MediaType.MULTIPART_FORM_DATA_TYPE);
            for (int i = 1; i < contents.size(); i++) {
                RequestData ignored = contents.get(i);
                log.warn("  ignore Content {}: Name {}| MediaType {}", new Object[] { i + 1, ignored.getName(), ignored.getMediaType() });
            }
        }
        content = contents.get(0);
        if (content.getMediaType() == null) {
            String message = String.format("MediaType not specified for mime body part for file %s. " + "The media type must be one of the supported values: %s", content.getName(), supportedMediaTypes);
            log.info("Bad Request: {}", message);
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        }
        if (!isSupported(content.getMediaType())) {
            String message = String.format("Unsupported Content-Type %s specified for mime body part " + "for file %s (supported: %s)", content.getMediaType(), content.getName(), supportedMediaTypes);
            log.info("Bad Request: {}", message);
            throw new WebApplicationException(Response.status(Status.BAD_REQUEST).entity(message).header(HttpHeaders.ACCEPT, acceptedMediaType).build());
        }
    } else {
        content = new RequestData(mediaType, null, entityStream);
    }
    long readingCompleted = System.currentTimeMillis();
    log.info("   ... reading request data {}ms", readingCompleted - start);
    Map<String, Representation> parsed = parseFromContent(content, acceptedMediaType);
    long parsingCompleted = System.currentTimeMillis();
    log.info("   ... parsing data {}ms", parsingCompleted - readingCompleted);
    return parsed;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) RequestData(org.apache.stanbol.entityhub.jersey.utils.MessageBodyReaderUtils.RequestData) MediaType(javax.ws.rs.core.MediaType) List(java.util.List) Representation(org.apache.stanbol.entityhub.servicesapi.model.Representation)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)276 Produces (javax.ws.rs.Produces)77 GET (javax.ws.rs.GET)71 Path (javax.ws.rs.Path)69 IOException (java.io.IOException)47 POST (javax.ws.rs.POST)47 Consumes (javax.ws.rs.Consumes)44 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)43 Response (javax.ws.rs.core.Response)30 MediaType (javax.ws.rs.core.MediaType)26 URI (java.net.URI)25 HashMap (java.util.HashMap)20 JSONObject (org.codehaus.jettison.json.JSONObject)20 Test (org.junit.Test)19 JSONException (org.codehaus.jettison.json.JSONException)18 ApiOperation (io.swagger.annotations.ApiOperation)17 ArrayList (java.util.ArrayList)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)15 List (java.util.List)14