-
Notifications
You must be signed in to change notification settings - Fork 28
java_one_minute
This is a one minute guide to get you going with Restfulie Java. As soon as you finish this example you are up to the next guide and then move on to the features you want to explore more.
Download VRaptor blank application, so that you have the server application with all jars configured and ready to start. After importing the application you have to add an context-param configuration at the web.xml so that hypermedia support is enabled.
br.com.caelum.vraptor.packages br.com.caelum.vraptor.restfulie ## Server Controller First we will create a VRaptor controller, on it we will say which uri we may respond, and how will the items be returned. At this example we will use an class to simulate the database, you can have it at Database.java.@Resource public class ItemsController {private final Result result; private final Database database; public ItemsController(Result result){ this.result = result; this.database = new Database(); } @Get @Path("/items") public void list(){ result.use(xml()).from(database.getItems()).serialize(); } @Get @Path("/items/{id}") public void show(Integer id){ //because list are zero-baed Item item = database.getItem(id); result.use(xml()).from(item).serialize(); }
}
Although the controller would generate our xml, it is not aware about the hypermedia links the resource contains. So we must configure our item object, for it to genereate which hypermedia links must be returned.
public class Item implements HypermediaResource { private Integer id; private String name; private Double price; public Item(Integer id, String name, Double price){ this.id = id; this.name = name; this.price = price; } public void configureRelations(RelationBuilder builder) { builder.relation("self").uses(ItemsController.class).show(id); } }
Try requesting the /items uri on your browser. You'll see an xml like this:
1 restfulie-book 25.0 2 restf in practice 35.0Download the Restfulie's jars and add to your classpath.
As restulie uses XStream to marshall and unmarshall objects, we need to annotate informing an alias that will be matched on the xml.
@XStreamAlias("item") public class Item { private Integer id; private String name; private Double price; //getters and setters }
#Hypermedia navigation Here we are, ready to hypermdia navigation.
RestClient restfulie = Restfulie.custom(); restfulie.getMediaTypes().register(new XmlMediaType().withTypes(Item.class)); Response response = restfulie.at("http://localhost:8080/mystore/items").accept("application/xml").get(); // retrieving our resource List items = response.getResource(); // following the hypermedia link, the resource() method is statically response = resource(items.get(0)).getLink("self").follow().get(); System.out.println(response.getContent());