First Class
Now that we have a working people service, let's create a new Java class that subclasses ActiveResource, and add getters and setters for each data element coming from the remote resource. This is a bit different than in the Ruby version of ActiveResource, because Java can't dynamically create the methods at run time. Here's a Java Person class:
public class Person extends ActiveResource {
private String id;
private String name;
private Date birthdate;
private Date createdOn;
private Date updatedOn;
public String getId() {
return id;
}
public void setId( String id ) {
this.id = id;
}
public String getName() {
return name;
}
public void setName( String name ) {
this.name = name;
}
public Date getBirthdate() {
return birthdate;
}
public void setBirthdate( Date birthdate ) {
this.birthdate = birthdate;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn( Date createdOn ) {
this.createdOn = createdOn;
}
public Date getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn( Date updatedOn ) {
this.updatedOn = updatedOn;
}
}
Now create a JUnit 4 test class to use our new Person object.
public class TestPerson {
private ResourceConnection c;
private RailsResourceFactory<Person> f;
private Person p;
@Before
public void setUp() throws Exception {
c = new ResourceConnection("http://localhost:3000");
f = new RailsResourceFactory<Person>(c, Person.class);
}
@Test
public void basicOperations() throws Exception {
p = f.instantiate();
assertNull(p.getId());
p.setName("Monty Python");
Date old = new Date(new Long("-99999999999999"));
p.setBirthdate(old);
p.save();
String id = p.getId();
assertNotNull("No id present", p.getId());
p = pf.find(id);
assertEquals(p.getName(), "Monty Python");
p.setName("Alexander the Great");
p.save();
p = pf.find(id);
assertEquals(p.getName(), "Alexander the Great");
assertTrue(f.exists(id));
p.delete();
assertFalse(f.exists(id));
}
}
Notice how we create a new Connection object with the URL of our remote service. We then create a RailsResourceFactory (because we are talking to rails) from the connection and our Person class.
Now we can create, update, and delete Person objects from our people service as shown in the basic tests above.
When we created Monty Python, you'll note we used f.instantiate(); instead of new Person();. Either will work, but the former creates a new Person object that knows how to save and create using our factory. This snippet creates and saves Monty Python as well, but we have to use the save method on the ResourceFactory object instead of on our Person object:
p = new Person();
assertNull(p.getId());
p.setName("Monty Python");
Date old = new Date(new Long("-99999999999999"));
p.setBirthdate(old);
f.save(p);
Once our Person object has touched the server, jactiveresource remembers where it came from, and the methods like p.delete(); will now work fine.
