06 October 2010

Large heap dump analysis with Eclipse Memory Analyzer

Most developers working with Java hardly have to think about the memory footprint of their application that they wrote. The garbage collector inside the JVM will remove most waste, but what happens when not all waste can be removed or something is wrong inside the application? This may result in an exception that probably a lot of developers and system administrators have seen before: java.lang.OutOfMemoryError (OOME).
There are several causes for such an exception, but the most obvious is that there is memory leak somewhere in the application.

The situation

At one of my recent projects we were having some memory related issues on one of the production machines. The web application was running in Tomcat 6 and it appeared that at a certain point in time, the JVM tried to allocate twice the average memory it was using. Let's say from 2 Gb the memory footprint went up to 4GB. You might have guessed it, because only a couple of minutes later we were represented with the OOME message in the server log. It turned out that this was related to the amount and type of requests being handled by the application server. I was glad to find out it was not a memory leak, but more a warning that the total size of requests could allocate a lot of memory. If your application is running, it's hard to see what objects allocate memory. To get an insight on what the application was doing at the moment the OOME occurred, we configured the JVM to create a memory(heap) dump/snapshot at the moment that the OOME was thrown.

Generating a heap dump

Most of my clients run on the Sun(Oracle) JVM, so I will try to keep this post focussed on the instructions for the Sun JVM. In case your application server runs out of memory you can instruct the JVM to generate a heap dump when an OOME occurs. This heap dump will be generated in the HPROF binary format.

You can do this in by:

  1. Manually: by using 'jmap', which is available since JDK 1.5.
  2. Automatically by providing the following JVM command line parameter:
    -XX:+HeapDumpOnOutOfMemoryError

The size of the heap dump is around the same size as the configured max heap size JVM parameter.
So if you have set your max heap size to -Xmx512m , your heap dump will be around that size.

Analyzing the heap dump

Now you have the heap dump and want to figure out what was inside the heap at the moment the OOME occurred. There are several Java heap dump analyzers out there, where most of them can do more then just heap analysis. The products range from commercial to open source and these are the ones that I tried with my 4Gb .hprof file:


I was surprised to see that most of the above applications were unable to handle a file of this size. Eclipse Memory Analyzer was actually the only heap dump analyzer that was able to handle a heap dump of this size on my MacBookPro. All the other analyzers were unable to handle a file of this size. Apparently some of these tools tried to load the entire file into memory. On a laptop with only 4 Gb this will not fit.  Eclipse MAT was able to analyze this file within 5-10 minutes.

About Eclipse Memory Analyzer


One of the great things about Eclipse Memory Analyzer is that it starts indexing the heapdumps on first load. This makes the processing of the heapdump very fast and once you've parsed the entire heapdump, reopening it is a piece of cake, because it does not have to process it all over again.

Once you have the heapdump on your screen the dominator tree view is the most useful view and can give you a very good insight on what was loaded when the server ran out of memory.

Next to the statistical views there is also an automatic leak hunter available to help you figure out the problem as fast as possible.

Summary


If you ever have to analyze a heap dump I would recommend to use Eclipse Memory Analyzer. It's fast, easy to use and free.

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.