Is it possible to reroute a Jersey JSP template response to an InputStream?
All,
I am using Java/Jersey 1.9 to create a web service that generates XML. I'm generating XML using a JSP template (explicitly via the Viewable class). Is there any way to reroute the JSP results to a local InputStream for further processing? At the moment I'm actually calling my own XML web service as an http loopback (localhost) from a different method.
Thanks for any insights,
Ian
@GET @Path("kml")
@Produces("application/vnd.google-earth.kml+xml")
public Viewable getKml(
@QueryParam("lat") double lat,
@QueryParam("lon") double lon,
@QueryParam("alt") double alt) {
overflights = new SatelliteOverflightModel(
context, new SatelliteOverflightModel.Params(lat, lon, alt)
).getOverflights();
return new Viewable("kml", this);
}
@GET @Path("kmz")
@Produces("application/vnd.google-earth.kmz")
public InputStream getKmz(@Context UriInfo uriInfo,
@QueryParam("lat") double lat,
@QueryParam("lon") double lon,
@QueryParam("alt") double alt)
throws IOException {
Client client = Client.create();
WebResource webr =
client.resource(uriInfo.getBaseUri()+"overflights/kml");
InputStream result =
webr.queryParams(uriInfo.getQueryParameters()).get(InputStream.class);
// Do something with result; e.g., add to ZIP开发者_如何学Python archive and return
return result;
}
You can consider using a ContainerResponseFilter for this instead of a resource - see e.g. the Gzip filter Jersey provides. The difference would be that your filter would depend on Accept and Content-Type headers instead of Accept-Encoding and Content-Encoding headers (like the gzip filter does).
If you insist on using the resource, you can inject Providers interface on your resource, find the right MessageBodyWritter and call the write method on it:
@GET @Path("kmz")
@Produces("application/vnd.google-earth.kmz")
public InputStream getKmz(@Context UriInfo uriInfo,
@QueryParam("lat") double lat,
@QueryParam("lon") double lon,
@QueryParam("alt") double alt,
@Context Providers providers,
@Context HttpHeaders headers)
throws IOException {
Viewable v = getKml(lat, lon, alt);
MessageBodyWriter<Viewable> w = providers.getMessageBodyWriter(Viewable.class, Viewable.class, new Annotation[0], "application/xml");
OutputStream os = //create the stream you want to write the viewable to (ByteArrayOutputStream?)
InputStream result = //create the stream you want to return
try {
w.writeTo(v, v.getClass(), v.getClass(), new Annotation[0], headers, os);
// Do something with result; e.g., add to ZIP archive and return
} catch (IOException e) {
// handle
}
return result;
}
DISCLAIMER: This is off the top of my head - untested :)
精彩评论