Tuesday, September 18, 2012

Programmatic roles in Mondrian

I often get asked how to use custom programmatic roles in Mondrian. It is actually very simple to get started. All you need is Mondrian and its dependencies, along with the following code.

It happens in three parts.

First you need to create a MondrianServer instance.
MondrianServer server =
    MondrianServer.createWithRepository(
        new DynamicContentFinder("path/to/datasources.xml"),
        new IdentityCatalogLocator());
The first argument must implement RepositoryContentFinder and provides a "piece of XML" to the Mondrian server. This tells it which datasources, catalogs and schemas to use. You can either take a look at some examples or refer directly to our DTD.

The second argument is used to translate the catalog URLs provided by the RepositoryContentFinder into actual paths on a file system or HTTP or whatever is required. This allows to decouple the contents of the XML, which can be shared by multiple Mondrian server instances, from the physical paths on actual machines. Notice that behind the scenes, Mondrian uses Apache VFS, so anything is possible here.
Entry roleToken =
    server.getLockBox().register(
        new RoleImpl() {
            // Override whatever here.
            // You could also implement Role directly.
        });
This next part registers the Role implementation to use. You can either override our default implementation, or implement the API directly. Registering an object with a server gives you a token back. You will have to use this token when you create your olap4j connection, like so,
OlapConnection connection =
    server.getConnection(
        "Catalog Name",
        "Schema Name",
        roleToken.getMoniker(),
        new Properties());
 And voilĂ .