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();
}
}
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;
}
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);
}
};
}
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;
}
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;
}
Aggregations