Chapter�5.�Flexibility through BeanShell Scripting

Trivial Persist provides a very simple but incredibly powerful scripting interface through integration with BeanShell (http://www.beanshell.org). If a file called tablename.bsh is located in the store directory (alongside a corresponding tablename.schema), the script will be run upon Store initialization. This is very useful for defining and saving RecordFilters, Comparators, and RecordInitializers for your tables.

Before the script is run, a variable called table, referencing the script's corresponding Table object, is placed in the script's namespace. All of the Table object's functionality is available through this table variable.

Here's a simple example of a table script that uses some included helper classes:

import com.martiansoftware.trivialpersist.*;
import com.martiansoftware.trivialpersist.helpers.*;

// remember that the "table" variable is provided
System.out.println("Initializing " + table.getName());
System.out.println("By the way, it currently has " + table.size() + " Records.");

// create a new anonymous initializer that sets the "name"
// field of any new records to "Unknown"
i = new RecordInitializer() {
    void init(Record record) throws TrivialPersistException {
        record.setString("name", "Unknown");
    }
};
table.setRecordInitializer(i);

// create an anonymous filter that accepts all records
// with non-null birthdates.  store the filter in the
// table for future use
f = new RecordFilter() {
        boolean accept(Record r) {
                return (r.hasValue("birthdate"));
        }
};
table.storeFilter("hasbirthdate", f);

// do the same thing for the name field, but use a
// built-in helper class
table.storeFilter("hasname", new NullFieldFilter("name", true));

// create and store a comparator that sorts by the "birthdate"
// field.  use another built-in helper to create the comparator.
table.storeComparator("bybirthdate", new FieldComparator("birthdate"));

Table scripts are interpreted by BeanShell; modifications to a table script only require that the Store be reinitialized (or the program restarted). No recompilation is necessary.