wiki:Examples/FindingResources

Finding Resources

Find One

If you know the identifier of your resource, it's easy to retrieve it:

ResourceConnection c = new ResourceConnection("http://localhost:3000");
RailsResourceFactory<Person> f = new RailsResourceFactory<Person>(c, Person.class);
try {
  Person p = f.find("17");
} catch (ResourceNotFound e) {
  // do something else
}

This will get  http://localhost:3000/people/17.xml and make a person object out of it. As you can see a ResourceNotFound exception will be thrown if the resource does not exist. The ResourceNotFound exception is thrown when the server returns an HTTP status code of 404.

Get 'um all

You can get all the resources available using the findAll() method:

ResourceConnection c = new ResourceConnection("http://localhost:3000");
RailsResourceFactory<Person> f = new RailsResourceFactory<Person>(c, Person.class);
ArrayList<Person> people = f.findAll();

This gets  http://localhost:3000/people.xml and give you back a list of people.

Finding with custom methods and queries

Just like ActiveResource, you can find resources using custom methods. Say there is a custom method at  http://localhost:3000/people/developers.xml with returns only people who are developers. To get the list of objects do:

ResourceConnection c = new ResourceConnection("http://localhost:3000");
RailsResourceFactory<Person> f = new RailsResourceFactory<Person>(c, Person.class);
ArrayList<Person> people = f.findAll("developers");

You can also add query parameters to your custom methods. To get the ruby developers from  http://localhost:3000/people/developers.xml?language=ruby, you can use:

ResourceConnection c = new ResourceConnection("http://localhost:3000");
RailsResourceFactory<Person> f = new RailsResourceFactory<Person>(c, Person.class);
HashMap<String, String> params = new HashMap<String, String>();
params.put("language", "ruby");
ArrayList<Person> people = f.findAll("developers", params);

If you prefer to use the URLBuilder class instead of a Map, try:

ResourceConnection c = new ResourceConnection("http://localhost:3000");
RailsResourceFactory<Person> f = new RailsResourceFactory<Person>(c, Person.class);
URLBuilder params = new URLBuilder();
params.addQuery("language", "ruby");
ArrayList<Person> people = f.findAll("developers", params);

You can also use query parameters without a custom method. To find all the managers from  http://localhost:3000/people.xml?position=manager just do:

ResourceConnection c = new ResourceConnection("http://localhost:3000");
RailsResourceFactory<Person> f = new RailsResourceFactory<Person>(c, Person.class);
HashMap<String, String> params = new HashMap<String, String>();
params.put("position", "manager");
ArrayList<Person> people = f.findAll(params);