Saturday, July 26, 2008

Manage content with Java Content Repository

Very useful technology for Java developers, and not only

Technology specification

http://jcp.org/en/jsr/detail?id=170

Implementations
Usage

It's similar to a File System we use everyday. But has more features and advantages.

You have to obtain a Repository instance to start. It's implementation specific and simple for most JCRs.

Each Repository presents a list of workspaces. Let us imagine it's drives in file system.

To begin the work with a content you have to login into Repository with selected Workspace.

InitialContext ctx = ...
Repository repository = (Repository)ctx.lookup("myrepo");
// Get a Credentials object
Credentials credentials = new SimpleCredentials("MyName", "MyPassword".toCharArray());
// Get a Session
Session mySession = repository.login(credentials, "MyWorkspace");

After the login you have the Session. So, you have a tool which gives access to a content storage.

Add 'file'

Node myFile = mySession.getRootNode().addNode("my-first-file");

Node it's only object which handles 'file' entity... say handler. Node may contains Property(es). The Property it's a content. String, Integer, Float, Binary, Path etc.

You will use Property to read/write data.

Write
myFile.setProperty("creator_name", "John");
myFile.setProperty("create_date", Calendar.getInstance());
myFile.setProperty("file_content", source.getInputStream());
Read
myFile.getProperty("creator_name").getSTring();
myFile.getProperty("create_date").getDate();
myFile.getProperty("file_content").getStream();

So, not so complicated.

Node can include sub-nodes also. It's only managed by NodeType (like file type, but richer).
myFile.addNode("sub-file");

You may get Node or Property by path, relative from other Node or Property or via Session.

// relative
Node ssFile = myFile.getNode("sub-file/sub-sub-file");
// or by abs path
Node ssFile = (
Node) mySession.getItem("/my-first-file/sub-file/sub-sub-file");

Simple? I hope - yes.

It's a good alternative to a databases in content-oriented applications and makes development process close to a task. A developer should know at least the specification, but it's simple than JDBC anyway.