Book Image

Tapestry 5: Building Web Applications

Book Image

Tapestry 5: Building Web Applications

Overview of this book

Table of Contents (17 chapters)
Tapestry 5
Credits
About the Author
About the Reviewers
Preface
Foreword
Where to Go Next

The Final Strokes


Finally, here is the complete source code of the new ObjectDataSource:

package com.packtpub.celebrities.data;
import com.db4o.Db4o;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.query.Predicate;
import java.util.List;
import org.example.myapp.model.Celebrity;
import org.example.myapp.model.Occupation;
import org.example.myapp.util.Formats;
public class ObjectDataSource implements IDataSource
{
private ObjectContainer db;
public ObjectDataSource()
{
db = Db4o.openFile("C:\\t5\\data\\celebrities.dat");
addCelebrity(new Celebrity("Britney", "Spearce",
Formats.parseDate("12/02/1981"), Occupation.SINGER));
addCelebrity(new Celebrity("Bill", "Clinton",
Formats.parseDate("08/19/1946"),
Occupation.POLITICIAN));
}
public List<Celebrity> getAllCelebrities()
{
return db.query(Celebrity.class);
}
public Celebrity getCelebrityById(long id)
{
Celebrity proto = new Celebrity();
proto.setId(id);
ObjectSet result = db.get(proto);
if (result.hasNext()) return (Celebrity)result.next();
return null;
}
public void addCelebrity(Celebrity c)
{
ObjectSet result = db.get(c);
if (!result.hasNext())
{
db.set(c);
}
}
public List<Celebrity> getRange(final int indexFrom,
final int indexTo)
{
List<Celebrity> result = db.query(
new Predicate<Celebrity>()
{
public boolean match(Celebrity celebrity)
{
return celebrity.getId() >= indexFrom &&
celebrity.getId() <= indexTo;
}
});
return result;
}
}

To make sure our application uses the new data source, not the mock one, we need to modify the AppModule class like this:

public void contributeApplicationStateManager(
MappedConfiguration<Class, ApplicationStateContribution>
configuration)
{
ApplicationStateCreator<IDataSource> creator =
new ApplicationStateCreator<IDataSource>()
{
public IDataSource create()
{
return new ObjectDataSource();
}
};
configuration.add(IDataSource.class,
new ApplicationStateContribution("session", creator));
}

The new data source is ready, and now the newly added celebrities will not disappear after the application's restart—this is a proper database, after all!

Of course, such a brief demonstration could not cover all, or even the most significant features of db4o. This database, with its transactions management and client/server mode of operation, is perfectly able to serve the needs of a real-life, enterprise-scale application. I encourage you to read the documentation that comes with db4o.

I am not sure how quickly db4o will find its place in the world that's got used to Oracle and SQL Server, but as for me, I am going to use this fantastic database for all my personal projects from now on.