5. Forester client
While you can work with a Pinetree vanilla instance using any tool capable of communicating via HTTP, the pinetree-forester offers a convenient alternative for Java projects. A packaged version of this component can be imported into any project and used to abstract HTTP requests via simple function calls. Let me show you how it works through some simple examples taken from the unit tests.
5.1 Example: Create a thing
...
@Test
public void createTest() {
try {
// Set the Pinetree URL as constructor argument
Repository r = new SimpleRepository("http://localhost:" + TEST_PORT);
// Instantiate the Forester Thing DAO. Here I use a Spring context to do this.
ForesterDAOThing dao = (ForesterDAOThing) ctx.getBean("daoThing");
// Set the repository to operate on
dao.setRepository(r);
// Instantiate a data transfer object of Thing..
Thing t = r.getModelFactory().createThing("hey");
// ..and create it!
dao.create(t);
Assert.assertTrue(dao.exists(t));
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
...
5.2 Example: Get all things
...
@Test
public void getAllTest() {
// Add some things (static function for the sake of the test)
createThing("hey");
createThing("ho");
try {
Repository r = new SimpleRepository("http://localhost:" + TEST_PORT);
ForesterDAOThing dao = (ForesterDAOThing) ctx.getBean("daoThing");
dao.setRepository(r);
Collection things = dao.getAll();
Assert.assertTrue(things.size() == 2);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
...
5.3 Example: Do a SPARQL query
...
@Test
public void describeQueryTest() {
try {
Repository r = new SimpleRepository("http://localhost:" + TEST_PORT);
ForesterDAOSparqlQuery dao = (ForesterDAOSparqlQuery) ctx.getBean("daoQuery");
dao.setRepository(r);
Collection statements = dao.query(
new SimpleDescribeQuery("describe <http://localhost:7357/resource/collection/main>")
);
Assert.assertTrue(statements.size() == 0);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
...
5.4 Example: Update a thing
...
@Test
public void updateTest() {
// Add a thing
Thing t = createThing("hey");
Collection add = new ArrayList();
try {
Repository r = new SimpleRepository("http://localhost:" + TEST_PORT);
ForesterDAOThing dao = (ForesterDAOThing) ctx.getBean("daoThing");
dao.setRepository(r);
add.add(
new SimpleStatement(
t.getURI(),
new SimpleURI("http://some.domain/love/to"),
new SimpleURI("http://some.domain/sing/loud"),
new SimpleURI(r.getBindingResolver().decode("pinetree:context:boo:resource"))
)
);
dao.update(t, add, null);
// Check if it's okay
Collection statements = dao.getStatements(t);
Assert.assertTrue(statements.size() == 2);
} catch (Exception e) {
e.printStackTrace();
Assert.fail(e.getMessage());
}
}
...