22 October 2010

Getting started with Vaadin

A couple of weeks ago I made myself a promise that I would look into a new technology every month and write something about it here. I've been looking around for technologies unknown to me and perhaps to some of you, so I will start out with a RIA framework called Vaadin.


About Vaadin


Before I started my journey with Vaadin, I have to say that I had never heard of it before. I was quite surprised that they were at version 6.4.6 already. That must mean something right? Let's find out.
My first impression is that for an open source framework their documentation is excellent. It's something you don't see everyday with open source frameworks and I've seen quite a few over the past years.
Vaadin really impressed with that and there even is a free (e-)book called 'The book of Vaadin', which will get you started and gives you a lot of information about the history of Vaadin, the architecture, the different components bundled with Vaadin and much more.

The architecture


I don't want to go into to much detail here, since you can find all this information on the Vaadin website, but from an architectural point of view I think these are the key concepts you need to know about Vaadin:

  • Everything is written in plain Java (no need for HTML templates, like with for instance Wicket)
  • All request processing happens on the server-side
  • GWT is used for the client-side rendering
  • Vaadin is more application than page oriented
  • Vaadin applications are state-full applications. Everything is stored in the user session.
  • You can program with Vaadin, like you would program with Swing or AWT.
Now let's try to actually start with a small application.

Getting started


There are several ways to get started with Vaadin. Vaadin has it's own plugin for Eclipse, NetBeans and a nice DZone refcard, but since I don't use either of those IDE's, I went for the Maven2 way. There are several Maven 2 archetypes available, which you can use from the command line or use from your favorite IDE (IntelliJ in my case).

Now let's create a clean Vaadin application by calling the archetype:

mvn archetype:generate \
-DarchetypeGroupId=com.vaadin \
-DarchetypeArtifactId=vaadin-archetype-clean \
-DarchetypeVersion=LATEST \
-DgroupId=com.jeroenreijn \
-DartifactId=vaadin-demo \
-Dversion=1.0-SNAPSHOT \
-Dpackaging=war

This will result in a new folder called 'vaadin-demo' and all this folder contains is a pom.xml, a web.xml and a simple HelloWorld Vaadin application. There is nothing more to it than that.

The application class is really small and simple. It just contains some components to get you going. This is what it looks like:

package com.jeroenreijn;

import com.vaadin.Application;
import com.vaadin.ui.Button;
import com.vaadin.ui.Window;

public class MyVaadinApplication extends Application
{
    private Window window;

    @Override
    public void init()
    {
        window = new Window("My Vaadin Application");
        setMainWindow(window);
        window.addComponent(new Button("Click Me"));
    }
}

Now that is nice and small right? The only thing this application does for now is that it creates a Window to put elements on with a default layout. Next to that a button with the label "Click me" is added to this window. It does not do much, but it's enough to get you going.

What's next?

I don't want to go into a full application in this post, but even after playing around with some more complex things, I have the feeling that I only scratched the surface. I think Vaadin is really interesting if you have to write rich web applications. The framework itself also has an addon directory filled with interesting and mature add-ons. I have some ideas I want to work out so I will keep you posted with my progress.

21 October 2010

Unit testing your HST2 components with EasyMock

Quality is an important aspect of every software development project. Writing unit tests is just one part of keeping an eye on quality. In this post I will try to explain how you can unit test your Hippo Site Toolkit (HST2) components, so you can be sure that the component still behaves as expected even after multiple maintenance cycles.

A mocking framework

Unit testing is the testing of software units (for instance HST2 components) in isolation. However, most units do not work alone, but they collaborate with other units, like the HST2 does for instance with a running JCR repository and a live HttpServletRequest (wrapped inside an HstRequest). To test a unit in isolation, we have to simulate these collaborations in our tests.
One way of working around such collaborations is by using Mock objects. A Mock Object is a test-oriented replacement for such a collaborator. It is configured to simulate the object that it replaces in a simple way. For this post I use EasyMock, but there are other mocking frameworks out there.

Setting up your environment

If you are regular reader, you might have noticed that I've been using Maven2 in most of my posts, so this time will not be different. To be able to test your HST components, you will need to add the following dependencies to your project/module pom.xml.

<dependency>
  <groupId>junit</groupId>
  <artifactId>junit</artifactId>
  <version>4.5</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymock</artifactId>
  <version>2.5.2</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.easymock</groupId>
  <artifactId>easymockclassextension</artifactId>
  <version>2.5.2</version>
  <scope>test</scope>
  <exclusions>
    <exclusion>
      <groupId>cglib</groupId>
      <artifactId>cglib-nodep</artifactId>
    </exclusion>
  </exclusions>
</dependency>

<dependency>
  <groupId>org.onehippo.cms7.hst</groupId>
  <artifactId>hst-mock</artifactId>
  <scope>test</scope>
</dependency>


Now that we have setup all the needed dependencies let's create an HST component to get started.

Basic HST2 Component


So let's start of with a simple/basic HST2 component. Here we have a simple component that tries to get a HippoBean wrapping a JCR node for the current request and puts the bean as an attribute on the request.

import org.hippoecm.hst.component.support.bean.BaseHstComponent;
import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.core.component.HstComponentException;
import org.hippoecm.hst.core.component.HstRequest;
import org.hippoecm.hst.core.component.HstResponse;

public class AbstractBaseHstComponent extends BaseHstComponent{

    @Override
    public void doBeforeRender(HstRequest request, HstResponse response) 
        throws HstComponentException {

        HippoBean bean = getContentBean(request);
        if(bean!=null) {
            request.setAttribute("document",bean);
        }
    }
}

Looks quite simple right? Now let's move on to the test.

The actual test

Now that we've seen what our component looks like, let's take a look at how we can test this class. The component doesn't do a lot, but there are a couple of things that we want to test:

  • that the getContentBean method is called
  • when the bean is not null the bean is set as an attribute on the request
  • there is an attribute on the request with the name document
  • the document from the request attribute is the same as the one put on the request

So now let's translate that into some code.

Before we can actually test our doBeforeRender method we need to do some setup before we can continue.

MockHstRequest fakeRequest;
MockHstResponse fakeResponse;
AbstractBaseHstComponent component;

@Before
public void setUp() throws Exception {
    fakeRequest = new MockHstRequest();
    fakeResponse = new MockHstResponse();
    component = createMockBuilder(AbstractBaseHstComponent.class).
                addMockedMethod("getContentBean", HstRequest.class).
                createMock();
}

Now looking at this setUp() method, you will notice that at first we create mocked versions of a request and response. These objects are necessary because they are parameters for our method under test. In a normal environment these objects will be created by the servlet container, but since we're unit testing we have to create these ourselves.

Next to that we create a mocked version of our AbstractBaseHstComponent. We do this because we need to mock the getContentBean method, which in a normal live environment performs interaction to a live JCR repository. The logic for getting the bean based on repository configuration is not useful for our test, so we mock the method and create a partial mock of the class.

Now let's have a look at the total test case and the actual test method.

import org.hippoecm.hst.content.beans.standard.HippoBean;
import org.hippoecm.hst.content.beans.standard.HippoDocument;
import org.hippoecm.hst.core.component.HstRequest;
import org.junit.Before;
import org.junit.Test;
import org.hippoecm.hst.mock.core.component.MockHstRequest;
import org.hippoecm.hst.mock.core.component.MockHstResponse;
import static org.easymock.classextension.EasyMock.*;
import static org.junit.Assert.*;

/**
 * Test for {@link com.jeroenreijn.site.components.AbstractBaseHstComponent}
 */
public class AbstractBaseHstComponentTest {

    MockHstRequest fakeRequest;
    MockHstResponse fakeResponse;
    AbstractBaseHstComponent component;

    @Before
    public void setUp() throws Exception {
        fakeRequest = new MockHstRequest();
        fakeResponse = new MockHstResponse();
        component = createMockBuilder(AbstractBaseHstComponent.class).
                addMockedMethod("getContentBean", HstRequest.class).
                createMock();
    }

    @Test
    public void testDocumentOnRequestAfterDoBeforeRender() throws Exception {

        HippoBean bean = new HippoDocument();

        //record the expected behavior
        expect(component.getContentBean(fakeRequest)).andReturn(bean);

        //stop recording and switch the mocked Object to replay state.
        replay(component);

        component.doBeforeRender(fakeRequest,fakeResponse);

        //verify the specified behavior has been used
        verify(component);

        assertSame(fakeRequest.getAttribute("document"),bean);
    }
}


As you might notice, the testDocumentOnRequestAfterDoBeforeRender() method tests the doBeforeRender method and checks all of the above requirements.

The next step


Even though you can create a mock of most objects quite easily, it's much better to have some native support/provided mock objects for most HST2 classes. Therefore I've added a patch to JIRA, which adds more mocked classes that can be used for testing, so you do not have to mock explicit methods. Next to that it will create test maven artifact, which you can use when testing your HST component without having to mock explicit methods or objects yourself.
Let me know if you run into any issues or have some ideas on improvement. It can make all our lives better.

Note/Update: This post was written at a time when the mock classes were not part of Hippo core (version 7.4). In the meantime this has changed and the classes can now be found in hst-mock artifact.


ps. I've just noticed that Shane Smith of iProfs created a similar post with using Mockito.

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!