PhotosResource

The PhotosResource class shows examples of the following:

- How to define custom serializers and parsers at the method level. In this case, you define a serializer and parser to handle images.

The resource consists of a simple registry of images with integer IDs.

http://localhost:10000/photos

It is initialized with a single entry, which can be accessed through a GET request.

http://localhost:10000/photos/cat

##### PhotosResource.java

/** * Sample resource that allows images to be uploaded and retrieved. */ @RestResource( path="/photos", messages="nls/PhotosResource", title="Photo REST service", description="Sample resource that allows images to be uploaded and retrieved.", htmldoc=@HtmlDoc( navlinks={ "up: request:/..", "options: servlet:/?method=OPTIONS", "source: $C{Source/gitHub}/org/apache/juneau/examples/rest/$R{servletClassSimple}.java" }, aside={ "<div style='max-width:400px;min-width:200px' class='text'>", " <p>Shows an example of using custom serializers and parsers to create REST interfaces over binary resources.</p>", " <p>In this case, our resources are marshalled jpeg and png binary streams and are stored in an in-memory 'database' (also known as a <code>TreeMap</code>).</p>", "</div>" } ), properties={ // Make the anchor text on URLs be just the path relative to the servlet. @Property(name=HTML_uriAnchorText, value="SERVLET_RELATIVE") } ) public class PhotosResource extends BasicRestServlet { // Our cache of photos private Map<String,Photo> photos = new TreeMap<>(); @Override /* Servlet */ public void init() { try (InputStream is = getClass().getResourceAsStream("averycutecat.jpg")) { BufferedImage image = ImageIO.read(is); Photo photo = new Photo("cat", image); photos.put(photo.id, photo); } catch (IOException e) { throw new RuntimeException(e); } } /** Bean class for storing photos */ public static class Photo { private String id; BufferedImage image; Photo(String id, BufferedImage image) { this.id = id; this.image = image; } public URI getURI() throws URISyntaxException { return new URI("servlet:/" + id); } } /** GET request handler for list of all photos */ @RestMethod(name=GET, path="/", summary="Show the list of all currently loaded photos") public Collection<Photo> getAllPhotos() throws Exception { return photos.values(); } /** GET request handler for single photo */ @RestMethod(name=GET, path="/{id}", serializers=ImageSerializer.class, summary="Get a photo by ID") public BufferedImage getPhoto(@Path("id") String id) throws Exception { Photo p = photos.get(id); if (p == null) throw new RestException(SC_NOT_FOUND, "Photo not found"); return p.image; } /** PUT request handler */ @RestMethod(name=PUT, path="/{id}", parsers=ImageParser.class, summary="Add or overwrite a photo") public String addPhoto(@Path("id") String id, @Body BufferedImage image) throws Exception { photos.put(id, new Photo(id, image)); return "OK"; } /** POST request handler */ @RestMethod(name=POST, path="/", parsers=ImageParser.class, summary="Add a photo") public Photo setPhoto(@Body BufferedImage image) throws Exception { Photo p = new Photo(UUID.randomUUID().toString(), image); photos.put(p.id, p); return p; } /** DELETE request handler */ @RestMethod(name=DELETE, path="/{id}", summary="Delete a photo by ID") public String deletePhoto(@Path("id") String id) throws Exception { Photo p = photos.remove(id); if (p == null) throw new RestException(SC_NOT_FOUND, "Photo not found"); return "OK"; } /** Serializer for converting images to byte streams */ public static class ImageSerializer extends OutputStreamSerializer { /** * Constructor. * @param ps The property store containing all the settings for this object. */ public ImageSerializer(PropertyStore ps) { super(ps, null, "image/png", "image/jpeg"); } @Override /* Serializer */ public OutputStreamSerializerSession createSession(SerializerSessionArgs args) { return new OutputStreamSerializerSession(args) { @Override /* SerializerSession */ protected void doSerialize(SerializerPipe out, Object o) throws Exception { RenderedImage image = (RenderedImage)o; String mediaType = getProperty("mediaType", String.class, (String)null); ImageIO.write(image, mediaType.substring(mediaType.indexOf('/')+1), out.getOutputStream()); } }; } } /** Parser for converting byte streams to images */ public static class ImageParser extends InputStreamParser { /** * Constructor. * @param ps The property store containing all the settings for this object. */ public ImageParser(PropertyStore ps) { super(ps, "image/png", "image/jpeg"); } @Override /* Parser */ public InputStreamParserSession createSession(final ParserSessionArgs args) { return new InputStreamParserSession(args) { @Override /* ParserSession */ @SuppressWarnings("unchecked") protected <T> T doParse(ParserPipe pipe, ClassMeta<T> type) throws Exception { return (T)ImageIO.read(pipe.getInputStream()); } }; } } }