10 June 2010

An introduction to Hippo CMS 7 updater modules

Once your Hippo CMS project is in production, there is always the case that you or your customer wants to add extra features to the website or portal. This might mean that the data model has to change.
The data model for a piece of content in Hippo CMS is stored based on a JCR nodetype definition.
As you might know the editor templates, which are related to the data model, can be edited live in the CMS. When you're done editing the editor templates, you can use the 'Update all content' button to persist the changes in your existing content model.
This might be a nice way of doing things during development, but performing such an operation on a live clustered environment can be quite tricky and you might want to do it in a more controlled and tested way.
As of Hippo CMS 7.2 it's possible to perform these changes by writing updater modules in plain Java. In this post I will try to explain the concept of updater modules and will show you how to write these updater modules and use them for updating your data model.

Note: For those of you reading this post and are using Hippo CMS version 7.8+ this mechanism has changed. From version 7.8 onwards you can use the Updater Editor to create Groovy based scripts within the CMS to perform these kind of operations. See the official Hippo CMS documentation page for further information.

Writing an Updater module


When you start writing an updater module you can start out with the following simple class file:

import org.hippoecm.repository.ext.UpdaterModule;
import org.hippoecm.repository.ext.UpdaterContext;

public class MyProjectUpdater implements UpdaterModule {

    public void register(final UpdaterContext context) {
       .....
    }

}

As you can see in the above code snippet the MyProjectUpdater extends the UpdaterModule interface, which requires you to implement the register() method. On your classpath you will need the hippo-ecm-api library, which comes with the Hippo CMS 7 war package or you can get it from the maven 2 repository.

Updaters and versioning


Performing such an update on your data model is most of the time specific for the current release of your project. The engine behind the updater modules can be instructed to only trigger certain updater modules if certain requirements (like the version of your project) are met. You can instruct the updater engine to trigger a specific updater module by registering a start tag on the UpdaterContext. In the following example we will:

  • register a unique name for our updater module
  • register a start tag for which this updater module should be triggered
  • register an end tag to which this version should change once the update was successful

import org.hippoecm.repository.ext.UpdaterModule;
import org.hippoecm.repository.ext.UpdaterContext;

public class MyProjectUpdater implements UpdaterModule {

    public void register(final UpdaterContext context) {
        context.registerName("myproject-updater-v1-to-v1_1");
        context.registerStartTag("myproject-v1");
        context.registerEndTag("myproject-v1_1");
   }
  
}

In the above updater module we will update our project from version 1 to version 1.1.
Our updater module does not do any radical changes so far. It will only change the start version in the repository for our project. You can find the current registered version(s) inside the Hippo repository with the Hippo CMS Console view on the path:

/hippo:configuration/hippo:initialize/@hippo:version.

If you don't have a project specific version yet, I would recommend creating one, because it will help you with using these updater modules.

Now let's continue with some more interesting stuff.

Visitors


You might want to change the data model with some simple operations like: adding a field, removing a field or introducing some new nodetypes. The hippo repository provides several visitors for doing changes inside the repository while performing an update. By default Hippo CMS 7.3 comes with 4 types of visitors. The following diagram shows you the class hierarchy for the ItemVisitor interface.


As you can see the following visitors are available:
  • NodeTypeVisitor - visits nodes of a specific primary type
  • PathVisitor - visits nodes based on their path in the repository
  • QueryVisitor - visits nodes found based on a JCR query
  • NamespaceVisitor - visits specified namespaces

Of course you can also write your own visitor if you want, but I guess the provided visitors are the most commonly used.

Note: The NamespaceVisitor is a special case and is not supposed to be used in a clustered Hippo setup. If you really need to use it make sure you run the updater on a non-clustered repository node.

How to use a visitor in your module

Now that we've seen the available visitors, let's see how we can use them. I think the most common use for updaters is when you need to update your data model without any extra processing involved. Let's say our current datamodel (cnd) version 1.0 looks like this:

<hippo='http://www.onehippo.org/jcr/hippo/nt/2.0'>
<hippostd='http://www.onehippo.org/jcr/hippostd/nt/2.0'>
<hippostdpubwf='http://www.onehippo.org/jcr/hippostdpubwf/nt/1.0'>
<myproject='http://www.myproject.org/jcr/nt/1.0'>

[myproject:basedocument] > hippo:document, hippostdpubwf:document, hippostd:publishableSummary

[myproject:news] > myproject:basedocument
- myproject:title (string)
+ myproject:text (hippostd:html)

We want to move to version 1.1, where we added a new subtitle field. The new nodetype defintion now looks like this:

<hippo='http://www.onehippo.org/jcr/hippo/nt/2.0'>
<hippostd='http://www.onehippo.org/jcr/hippostd/nt/2.0'>
<hippostdpubwf='http://www.onehippo.org/jcr/hippostdpubwf/nt/1.0'>
<myproject='http://www.myproject.org/jcr/nt/1.1'>

[myproject:basedocument] > hippo:document, hippostdpubwf:document, hippostd:publishableSummary

[myproject:news] > myproject:basedocument
- myproject:title (string)
- myproject:subtitle (string)
+ myproject:text (hippostd:html)


Now if we want to update our namespace with an updater module our actual code will look like this:

import java.io.InputStreamReader;

import org.hippoecm.repository.ext.UpdaterItemVisitor;
import org.hippoecm.repository.ext.UpdaterModule;
import org.hippoecm.repository.ext.UpdaterContext;

public class MyProjectUpdater implements UpdaterModule {

    public void register(final UpdaterContext context) {
        context.registerName("myproject-updater-v1-to-v1_1");
        context.registerStartTag("myproject-v1");
        context.registerEndTag("myproject-v1_1");
        
        context.registerVisitor(new UpdaterItemVisitor.NamespaceVisitor(context, "myproject", "-",
        new InputStreamReader(getClass().getClassLoader().getResourceAsStream("myproject.cnd"))));

   }
  
}

The updater module above registers a namespace visitor on the UpdaterContext and the visitor reloads the content nodetype definition (cnd in short) from the classpath and updates the namespace to the new version. This is all you have to do to just bump a namespace from version 1.0 to 1.1.

Now if you actually want to change something during the update we can make use of one of the other visitors like the NodeTypeVisitor. Let's say we want to change a certain property of all documents of type 'myproject:news', then this is what the updater might look like:

import java.io.InputStreamReader;

import javax.jcr.Node;
import javax.jcr.RepositoryException;
import javax.jcr.Value;

import org.hippoecm.repository.ext.UpdaterItemVisitor;
import org.hippoecm.repository.ext.UpdaterModule;
import org.hippoecm.repository.ext.UpdaterContext;

public class MyProjectUpdater implements UpdaterModule {

    public void register(final UpdaterContext context) {
        context.registerName("myproject-updater-v1-to-v1_1");
        context.registerStartTag("myproject-v1");
        context.registerEndTag("myproject-v1_1");
        
        context.registerVisitor(new UpdaterItemVisitor.NodeTypeVisitor("myproject:news") {
            @Override
            protected void leaving(Node node, int level) throws RepositoryException {
               if (node.hasProperty("myproject:property")) {
                   node.setProperty("myproject:property", "new value");
               }
            } 
        });
   }
  
}

The important part of the updater in this case is that we override the leaving() method, which will be called before the visitor leaves this node and moves on to the next. It will then change the value of a certain property and move on.

If you want to see more examples of how to use certain types of visitors please let me know, but I hope that the two examples above can help you get started with writing updater modules. Now let's see how to get the repository to run your updater module.

Adding the updater module to your deployment


Now that we've seen how to write an updater module, the next step is to get the repository to run your updater module. The Hippo CMS 7 repository knows about the existence of these updater modules, but you will need to instruct the repository on where they can be found. Making an updater module available to repository is done in the similar fashion as adding a daemon module to the repository. The location of the updater module needs to be added to the MANIFEST.MF, which will end up in your jar. Maven 2 can help you with achieving this by means of the maven-jar-plugin. See the following plugin configuration from my pom.xml file.

<plugin>
  <groupid>org.apache.maven.plugins</groupid>
  <artifactid>maven-jar-plugin</artifactid>
  <configuration>
    <archive>
      <manifest>
        <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
      </manifest>
      <manifestEntries>
        <Hippo-Modules>com.myproject.repository.update.MyProjectUpdater</Hippo-Modules>
      </manifestEntries>
    </archive>
  </configuration>
</plugin>

Now when you add the jar with our updater module to the CMS web application archive and start the CMS, the repository will scan all manifest files for implementations of the UpdaterModule interface. The updater modules will be registered and triggered when needed.

The updater modules are quite powerful and it's great that you can test them on your test environment, so you can make sure that when you perform an update in production it will succeed.

References

24 May 2010

Giving Hippo CMS 7 some WebDAV support

A while ago a user on the Hippo CMS 7 forum donated a patch, which provided a servlet for simple WebDAV support. He donated his code as a proof of concept and hoped that somebody with some deeper knowledge of Hippo and it's nodetypes could pick this up and continue to work on it. Since the patch was left alone for quite some time I picked it up and turned it into a Hippo Forge project and called it: 'Hippo CMS 7 WebDAV Support'.

Now and then I find some time to work on this project and the current status now is that I have a working quickstart, which you can check out. I personally think it's far from finished, because there is still a lot of work remaining, but it is already usable. In this post I will explain how the WebDAV plugin works, the current status of the project and some future plans. Let's start with some of the basics.

What is WebDAV?


WebDAV is short for Web-based Distributed Authoring and Versioning. In short WebDAV is an extension on top of the default HTTP protocol and it allows computer users to edit and store files on a remote server. All the major operating systems provide support for WebDAV and will allow you to easily store and edit files on a remote server as if they were on your own computer.

Enable WebDAV support for your Hippo CMS 7 project


Using WebDAV in combination with Hippo CMS 7 is quite easy actually. All you need to do for now is do four things to enable the WebDAV support for your project.

1. Add the WebDAV support maven dependency to your project

<dependency>
  <groupId>org.onehippo.forge.addon.webdav</groupId>
  <artifactId>webdav-addon</artifactId>
  <version>${webdav.addon.version}</version>
</dependency>

2. Add the WebDAV support servlet definition to your web.xml

<servlet>
 <servlet-name>WebDAVServlet</servlet-name>
 <servlet-class>org.onehippo.forge.addon.webdav.HippoWebdavServlet</servlet-class>
 <init-param>
  <param-name>repository-address</param-name>
  <param-value>vm://</param-value>
 </init-param>
 <init-param>
  <param-name>resource-path-prefix</param-name>
  <param-value>/webdav</param-value>
  <description>defines the prefix for spooling resources out of the repository.</description>
 </init-param>
 <init-param>
  <param-name>resource-config</param-name>
  <param-value>/WEB-INF/config.xml</param-value>
  <description>
   Defines various dav-resource configuration parameters.
  </description>
 </init-param>        
 <load-on-startup>5</load-on-startup>
</servlet>

3. Add the WebDAV servlet mapping to your web.xml
<servlet-mapping>
 <servlet-name>WebDAVServlet</servlet-name>
 <url-pattern>/webdav/*</url-pattern>        
</servlet-mapping>

4. Add the WebDAV support configuration file to your projects WEB-INF directory.

This configuration file can be found on the WebDAV support documentation site. It's quite easy to read and you should put it into your /webapp/WEB-INF/ folder if possible.

In action


The following video will show you how easy it is to upload multiple files into the CMS.


Hippo CMS 7 WebDAV support from Jeroen Reijn on Vimeo.

This video is also available on YouTube.

Current status


The current status is that the WebDAV addon has default support for the Hippo assets folder. This was actually quite easy to develop. This can also be used to copy all assets from a CMS 6 instance directly into a running CMS 7 instance. All other folders are not WebDAV enabled yet, but I have some plans for the other folders in the future.

For the short-term roadmap: 'pretty url support' is the first thing I want to work on. I could have put it in hardcoded, but since I want to make it configurable like in the CMS this will my main focus for the next two weeks. If you have ideas or want to help out, please let me know!

20 May 2010

Photography in Artis


"Hmm delicious", originally uploaded by Jeroen Reijn.
Last sunday some college buddies and I went to Artis (the Amsterdam Zoo) for a day of photography. The last time I went to Artis was probably about 15-20 years ago. It did not change much, but spending a day with exotic creatures is always fun. The weather was great and we shared lots of great photo moments. The photo above is just one in a series of photos taken this day. If you want to see more, I would recommend you take a look at my set on Flickr.

05 April 2010

Metadata extraction with Apache Tika

At Hippo I work with/for customers that have quite a lot of content. The projects I work on have content in the range of 5.000 to 500.000 document gathered in one content repository. This can be just textual content, but most of the time this is a variety of different content types. You might think of images, PDFs and Microsoft office document formats. By default Apache JackRabbit, the layer underneath Hippo Repository, indexes this kind of content by using extractors, so that the information can be found within the Hippo CMS 7 search or from any application connected to the Hippo Repository which is performing a search on the content repository. Being able to search on content found within a file is interesting, but there is so much more that you can do with this kind of information.

Content metadata


Having all this content inside the repository is nice, but a certain piece of content uploaded to the repository can contain much more information than the file itself and sometimes this metadata is ignored in content management systems. As an example you might want to be able to see the number of pages of a PDF document inside your CMS or view the EXIF information of an image stored inside your content repository. There are a number of parser libraries out there that can extract information from a specific file format, but you can get quite lost. Within the ASF there is also a very nice toolkit called Apache Tika, which provides parsers for a lot of different file formats.

What is Apache Tika?


Apache Tika is a subproject of the Apache Lucene project and is a toolkit for extracting content and metadata from different kind of file formats. The content extraction logic is not located inside Tika itself, but Tika defines a standard API and makes use of existing libraries like POI and PDFBox for it's content extraction. While writing this post the current release of Tika is version 0.6 and the following file formats are already supported: 
  • HyperText Markup Language
  • XML and derived formats
  • Microsoft Office document formats
  • OpenDocument Format
  • Portable Document Format
  • Electronic Publication Format
  • Rich Text Format
  • Compression and packaging formats
  • Text formats
  • Audio formats
  • Image formats
  • Video formats
  • Java class files and archives
  • The mbox format
As you can see this is already quite a lot. The team behind Tika is working hard on improving the current parser possibilities and adding more formats for the upcoming releases. Tika is actually already being used by a number of other Apache projects like JackRabbit and Solr. Now let's see how we can use Tika ourselves.

Getting started


I always work with Maven as my build system, so let's start of with a piece of pom.xml. First add the Tika parser dependency to our pom.xml.

<dependency>
  <groupId>org.apache.tika</groupId>
  <artifactId>tika-parsers</artifactId>
  <version>0.6</version>
</dependency>

By depending on tika-parsers Maven will automatically gather the required parser libraries, which are needed to parse certain file formats. Since my Java code example will be based on a unit test, we will also need to add JUnit as a dependency to our pom.xml.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.7</version>
</dependency>

In this post I want to see what kind of EXIF information can be retrieved from an image by using Tika. One of my hobbies is photography and therefor I have tons of images, which contain a lot of metadata about for instance the ISO speed or dimensions of an image. Now let's write some actual code to see how Tika works.

The actual code


As I mentioned before, my example code is written as a JUnit test. If you are not familiar with writing tests or JUnit itself please have a look at the JUnit website.
To be able to run this test, I've added one of my images on the test classpath, so my test class will be able to find the image resource. The following piece of code shows my entire test class.

public class ImageMetaDataTest {

    private static final String fileName = "IMG_2659.JPG";

    private Tika tika;
    private InputStream stream;

    @Before
    public void setUp() {
        tika = new Tika();
        stream = this.getClass().getResourceAsStream(fileName);
    }

    @Test
    public void testImageMetadataCameraModel() throws IOException, SAXException, 
            TikaException {

        Metadata metadata = new Metadata();
        ContentHandler handler = new DefaultHandler();
        Parser parser = new JpegParser();
        ParseContext context = new ParseContext();

        String mimeType = tika.detect(stream);
        metadata.set(Metadata.CONTENT_TYPE, mimeType);

        parser.parse(stream,handler,metadata,context);
        assertTrue("The expected Model is not correct", 
                metadata.get("Model").equals("Canon EOS 350D DIGITAL"));
    }

    @After
    public void close() throws IOException {
        if(stream!=null) {
            stream.close();
        }
    }

}


As you can see the code is quite small. The most important part of the above code example is using the JpegParser to parse the .JPG file and the creation of the Metadata object with the appropriate information.
I think this simple test case shows you how easy to use the Tika API is. Of course in the above test case I only test for the current Camera Model, but the Metadata object holds much more information then just that.

Viewing all the fields found in the metadata of the image can be achieved quite easily by using for instance the following method.

private void listAvailableMetaDataFields(final Metadata metadata) {
  for(int i = 0; i <metadata.names().length; i++) {
    String name = metadata.names()[i];
    System.out.println(name + " : " + metadata.get(name));
  }
}

The output of this method can be like:


Easy Shooting Mode : Manual
Image Type : Canon EOS 350D DIGITAL
Model : Canon EOS 350D DIGITAL
Metering Mode : Evaluative
Quality : Fine
Shutter/Auto Exposure-lock Buttons : AF/AE lock
ISO Speed Ratings : 400


It's as easy as that.

Looking ahead


I'm currently looking for possibilities of integrating Apache Tika into Hippo CMS 7, to enhance the system with much more metadata then there currently is available in the system. I think this can become quite a powerful addition in combination with the facetted navigation feature introduced in Hippo CMS 7.3. I've already started working on some code, which I hope to provide as a patch in the near future.

04 February 2010

Jboss ModeShape: A federating JCR repository

Some interesting stuff is happing in the JCR community. With Apache Jackrabbit 2.0.0 out (with JCR 2.0) and an interesting project called Jboss ModeShape almost reaching it's final 1.0 release. ModeShape recently came to my attention and it seems an interesting project. In this post I will give a short introduction of ModeShape and it's features.

What's ModeShape?

ModeShape is a Java Content Repository implementation which will support both JSR-170 and JSR-283. It's not trying to be just another isolated content repository, but a repository with a strong focus on content federation. In other words: ModeShape's main goal is to provide a single JCR interface for accessing and searching content coming from different back-end systems. These systems can even be of different sorts. You might think of a ModeShape repository containing information from a relation database, a file system and perhaps even another Java content repository like for instance Hippo CMS 7's content repository. You can configure these sources of information with the help of ModeShapes connector framework.

Connectors

One of ModeShape's key concepts is the concept of connectors. A connector will allow you to connect to a certain type of back-end system and transparently expose the information inside the ModeShape repository. In the current 1.0.0 beta release there are already a couple of out of the box connectors available:


  • In-Memory Connector
  • File System Connector
  • JPA Connector
  • Federation Connector
  • Subversion Connector
  • JBoss Cache Connector
  • Infinispan Connector
  • JDBC Metadata Connector 

That's already quite a few, but for the upcoming release they also have plans for expanding the set of connectors with for instance a JCR connector, which I find quite interesting myself, because that would allow you to expose other JCR implementations like Hippo CMS 7 (Apache JackRabbit) in combination with other systems through one JCR interface.

There are many other content solutions out there, so if you can't find a connector that suits your need, you can of course write one yourself and perhaps donate it to the ModeShape project.

Sequencers

One of ModeShapes other interesting features is the concept of sequencers. With sequencers you can gather additional information from a certain item inside the repository and store that extracted information in the repository. ModeShape has quite a few sequencers out of the box:


  • Compact Node Type (CND) Sequencer
  • XML Document Sequencer
  • ZIP File Sequencer
  • Microsoft Office Document Sequencer
  • Java Source File Sequencer
  • Java Class File Sequencer
  • Image Sequencer
  • MP3 Sequencer
  • DDL File Sequencer
  • Text Sequencers

The example below is of the ImageSequencer, which can gather information from certain types of images stored inside the repository. The ImageMetaDataSequencer is used here to extract metadata like size, dimensions and so on from the image if they have one of the specified extensions and the extracted information is stored somewhere else inside the repository.

JcrConfiguration config = ...
config.sequencer("Image Sequencer")
.usingClass("org.modeshape.sequencer.image.ImageMetadataSequencer")
.loadedFromClasspath()
.setDescription("Sequences image files to extract the characteristics of the image")
.sequencingFrom("//(*.(jpg|jpeg|gif|bmp|psd)[*])/jcr:content[@jcr:data]")
.andOutputtingTo("/images/$1");

Conclusion

With other mature JCR implementations out there I think ModeShapes strongest point is it's focus on content federation. Providing a single JCR interface for content stored in different systems is a great initiative, because the JCR API is quite easy to learn and to use. I see a bright future for ModeShape, since companies are sharing more and more in-house information on the web these days. I myself will try to keep a close eye on ModeShape and see how it evolves.