RESTful Web Services Developer's Guide

Web Resources for Bookstore Application

The Bookstore resource returns a list of items, either CDs or books. The resource dynamically references a Book or CD resource using the getItem method that is annotated with @Path. Both the Book and CD resources inherit from the Item class, therefore, the item can be managed polymorphically.

The following snippet of code from com.sun.jersey.samples.bookstore.resources.Bookstore.java adds some items to the bookstore application and, using a URI path template to pass in the item ID, provides a method for retrieving the item.

@Path("/")
@Singleton
public class Bookstore {    
    private final Map<String, Item> items = new TreeMap<String, Item>();
    
    private String name;
    
    public Bookstore() {
        setName("Czech Bookstore");
        getItems().put("1", new Book("Svejk", "Jaroslav Hasek"));
        getItems().put("2", new Book("Krakatit", "Karel Capek"));
        getItems().put("3", new CD("Ma Vlast 1", "Bedrich Smetana", new Track[]{
            new Track("Vysehrad",180),
            new Track("Vltava",172),
            new Track("Sarka",32)}));
    }
    
    @Path("items/{itemid}/")
    public Item getItem(@PathParam("itemid") String itemid) {
        Item i = getItems().get(itemid);
        if (i == null)
            throw new NotFoundException("Item, " + itemid + ", is not found");
        
        return i;
    }
   . . . 
  }

Both the Book and the CD resources inherit from the Item class. This allows the resources to be managed polymorphically. The Book resource has a title and an author. The CD resource has a title, author, and list of tracks. The Track resource has a name and a track length.

The following code snippet from the CD resource dynamically references the Track resource using the getTrack method that is annotated with @Path.

public class CD extends Item {
    
    private final Track[] tracks;
    
    public CD(final String title, final String author, final Track[] tracks) {
        super(title, author);
        this.tracks = tracks;
    }
    
    public Track[] getTracks() {
        return tracks;
    }
    
    @Path("tracks/{num}/")
    public Track getTrack(@PathParam("num") int num) {
        if (num >= tracks.length)
            throw new NotFoundException("Track, " + num + ", 
            of CD, " + getTitle() + ", is not found");
        return tracks[num];
    }    
}