03 December 2012

dotJS: a 'not' so JS conference?

Last Friday I traveled to the wonderful city of Paris together with some Hippo colleagues for the dotJS conference. It was going to be my first tech conference in France and I was really excited. dotJS is a new conference and promoted itself as: "The largest JavaScript conference in France", which raised my expectations. The list of speakers looked promising with for instance Jeremy Ashkenas (creator of Backbone.js) and Jacob Thornton (one of the creators of Twitters Bootstrap). It was a two day conference of which I only attended the first day (second day were workshops). The rest of this post will be about how I experienced the conference.

The venue

dotJS was held in the beautiful Théâtre des Variétés in the hart of Paris. The venue really looked amazing and the conference covered all floors and rooms of the building. With a sharp looking screen it was really easy to read any code that presented itself on-screen. The seats however were quite small for people like me (or people above 1.70m in general). For those of you that ever flew with EasyJet it was sort of a similar experience. The conference attracted about 500-600 people and the room was packed.

Conference view from above
Photo taken by @mauriz http://svay.com/photos/2012-11-30_dotjs/


The lunch in the middle of the day was good and there was some real tasty quality food, but making fresh food with about 250-300 people waiting can become quite a logistical problem. Even though the total amount of attendees were divided in groups the lines were long and everybody had to be in the same room to be able to get some food. I liked the freshly cooked food, but I guess this could be a bit improved with prepackaged lunch boxes or serving food in multiple rooms.

Talks and speakers

These days Javascript is not only used on the client/browser, but also on the server side with for instance Node.js. Therefor the list of speakers was a mix of both and in my opinion contained a lot of knowledgeable individuals. To name a few:
In total there were about eleven talks, so the day was packed. All speakers had about 20 minutes to talk about their topic which was a nice pace. It helped to stay focused on the talks at hand.
There were even some lightning talks at the end of the day, which added a nice change to the conference. The overall quality of the talks and speakers was good and I really enjoyed some of them. However for a Javascript conference there were only just 3 or 4 talks that actually went into technical details and unfortunately most topics were more pointed towards general topics like open source and communities. I thought that was a shame, since there was so much knowledge on stage. The highlights for me were: Jeremy Ashkenas ("Symbiotic languages") , Brian Leroux ("How the Javascript language can lead to unexpected results") and Jacob Thornton ("The history of Open Source").

Summary


The conference was nice and had attracted quality speakers. Sylvain Zimmer and Thomas Bassetto did a really good job in making dotJS happen. Unfortunately the conference had just a couple of in-depth Javascript talks and therefor did not really meet my expectations. Even though there was no real schedule up front my advice to the organizers would be to make a good balance between general talks and in-depth talks next year. I personally would have expected a lot more in depth Javascript talk at at Javascript conference.

13 November 2012

Hippo CMS, Servlet 3 and WebJars

Besides my work at Hippo I'm quite a fan of Play framework. My first introduction to Play framework was back in 2011 just around the time I was about to attend Devoxx. Because of this I attended a talk at Devoxx by James Ward about Deploying Java & Play Framework Apps to the Cloud. I've been following James on Twitter since that day because he was playing around with quite some interesting technologies. Recently I noticed James introduced an interesting project called WebJars.

What are WebJars?

In most Java projects a dependency management system is used like Maven, Ivy or Gradle. Having  dependency management setup for server-side dependencies is quite natural, but what about client-side dependencies? This is where WebJars can help out.

WebJars are client-side web libraries packaged into JAR files. This is very useful for maintaining a web application. By using dependency management also for client-side libraries helps you find out easily which version of a dependency is being used in a project. This can be really helpful since not all web libraries have versions in their file names.

Another advantage of using dependency management is that you will get transitive dependencies for free. For instance if you want to use Twitter Bootstrap 2.2.1 as a WebJar you will also get jQuery 1.8.2. That's really helpful!

So let's see what we need to do if we want to use WebJars in for instance a Hippo CMS project.

Getting started with  Hippo CMS and WebJars.

Let's first generate a new Hippo project. The following maven command will generate a Hippo CMS 7.7.6 project from the Hippo Archetype.

mvn archetype:generate \
-DarchetypeRepository=http://maven.onehippo.com/maven2 \
-DarchetypeGroupId=org.onehippo.cms7 \
-DarchetypeArtifactId=hippo-archetype-website \
-DarchetypeVersion=1.05.08


Once this is finished you should have a project that looks similar to this:

drwxr-xr-x 11 jreijn staff 374 9 nov 13:47 .
drwxr-xr-x 46 jreijn staff 1564 9 nov 11:30 ..
drwxr-xr-x 16 jreijn staff 544 9 nov 13:42 .idea
-rw-r--r-- 1 jreijn staff 1677 9 nov 11:30 README.txt
drwxr-xr-x 6 jreijn staff 204 9 nov 13:47 cms
drwxr-xr-x 6 jreijn staff 204 9 nov 11:30 conf
drwxr-xr-x 5 jreijn staff 170 9 nov 13:47 content
-rw-r--r-- 1 jreijn staff 9006 9 nov 11:57 pom.xml
drwxr-xr-x 5 jreijn staff 170 9 nov 13:47 site
drwxr-xr-x 3 jreijn staff 102 9 nov 11:30 src
-rw-r--r-- 1 jreijn staff 2819 9 nov 11:35 webjars.iml


Before we proceed there is one little catch. To be able to use WebJars within a Hippo project we need to run on a Servlet 3 container. By default the Hippo archetype packages Apache Tomcat 6, but Tomcat 6 supports Servlet 2.5 and not Servlet 3. Tomcat 7 however  does support Servlet 3, so with some minimal changes we can run our Hippo project with Tomcat 7 for our local development environment.

The reason why we need a Servlet 3 container is that with any Servlet 3 compatible container anything in a META-INF/resources directory in a JAR file located in the WEB-INF/lib directory is automatically exposed as a static resource.

The Hippo archetype runs with the maven cargo plugin. By default the cargo configuration is handled by the parent pom, which is out of the projects code, but it's easy to change this by just adding some additional properties in the <properties> section of our projects pom.xml file.

<properties>
  <cargo.tomcat.major.version>7</cargo.tomcat.major.version> 
  <cargo.tomcat.full.version>7.0.32</cargo.tomcat.full.version>
</properties>

Now to be able to use for instance the Twitter Bootstrap WebJar all we need to do is add the following dependency to our site/pom.xml file within the dependencies section. 

<dependency>
  <groupId>org.webjars</groupId>
  <artifactId>bootstrap</artifactId>
  <version>2.2.1</version>
</dependency>

As I've mentioned before jQuery will also be fetched since it's a transitive dependency of Bootstrap.
Now if we want to use it all we need to do is change for instance the webpage.jsp that gets bundled with the default archetype. So all we need to do is insert the following snippet:

<hst:link var="bootstrapCssLink" path="/webjars/bootstrap/2.2.1/css/bootstrap.min.css"/>
<link rel="stylesheet" href="${bootstrapCssLink}" type="text/css"/>

And that's it. Now let's package our project and start the Hippo CMS instance:

$ mvn clean package && mvn -Pcargo.run


Now all we need to do is open up a browser and point it to the website: http://localhost:8080/site/ and you should see the Bootstrap CSS theme kicking in.

Of course Bootstrap and jQuery are not the only available frameworks. The WebJars website already counts about 40 different WebJars. For more information and documentation make sure to check out the official WebJars website.

07 May 2012

Introducing the Hippo CMS Groovy add-on

A while back I was playing around on some pet project with Groovy. For those of you that are not familiar with Groovy: Groovy is a dynamic language for the Java Virtual Machine. In other words you can write Groovy (scripts) and keep writing without having to recompile / deploy.  Groovy can integrate with any framework or library out there, so I tried it on Hippo CMS as well.

A little background


One of the reasons I tried Groovy for Hippo CMS was that I was looking for a different way of executing code against the Hippo repository. There are different options for executing code against the repository. As you might know you have the option to use UpdaterModules. I've written about these modules a while back in an older blog post. In short an UpdaterModule allows you to run a piece of Java code at start-up time (when the repository starts) and can execute any command on the low-level JCR API. This is quite a nice concept, but when you run these updaters the CMS is not usable for users and if you have a large updater it can be down for quite a while. There is a good reason why this is so and it's very useful for a couple of use-cases.
Next to the UpdaterModules Hippo CMS also has the concept of JCR runners. These runners connect through RMI and can be run from the same server to perform large batch operations against a running CMS/Repository. They are really handy, but the downside is that you need to have physical access or SSH access to the machine itself, which you sometimes/mostly do not have.

The reason for creating the Hippo Groovy plugin


First of all I like Groovy as a language. It's simple, intuitive for Java developers, reduces scaffolding code and you can easily integrate it with your current framework.
My primary objective with creating the Hippo Groovy add-on was creating a CMS plugin that allowed you as a Hippo 'admin' user to for instance:
  • run a dynamic script against the Hippo repository that might get some information
  • update a set of documents
  • query for data and call for instance a the publication workflow for all documents that match this criteria.
  • what ever comes to mind...
And I wanted to be able to do it all from within the CMS interface.

Note: Of course giving scripting access to users that have 'admin' permissions within the Hippo system can also be quite dangerous, because for instance they can throw away all data if they are not careful with their scripts. I do however believe that the type of users that run these scripts take extra care before executing these scripts.


Current status


The Hippo CMS Groovy add-on is now a project on Github and is almost ready for it's first release. The first release will contain a CMS add-on that is only shown to users that have the 'admin' role within the CMS. The features implemented right now are:
  • Script execution from the CMS UI
  • Uploading a script before execution
  • Feedback of the script by providing a CMS Wicket model as the 'output' for the script
  • Exposing the entire JCR api to scripts based on the current user session
  • Syntax highlighting for the Groovy scripts with the CodeMirror javascript library

 Future plans

 

 For the next couple of releases I have a few plans like:
  • Groovy script storing inside the repository  (done)
  • Scheduled execution of stored scripts
  • Perhaps support Groovy syntax in HST (GSP) templates (like for instance Play framework does with Play version 1.2.x)

Contribute

 

If you like the concept then please fork the project on Github and send in pull requests.

09 February 2012

Get in control with Spring Insight!

Ever wondered what your application was doing? Why that specific page was so slow? I've asked myself this question numerous times and always had to change some log level or attach a profiler to get actual feedback on what was going on inside my application.

The other day while commuting from home to work, I discovered the Spring Insight project. From what I've seen so far Spring Insight is a set of inspections (plugins) which are visually displayed in a web application. To get an idea of what Spring Insight can do for you, be sure to check out the introduction screencast.

tc Server Developer Edition Screencast


By default Spring Insight comes with a default set of plugins/inspections for different kinds of frameworks/libraries like:
  • Spring Web, Spring core
  • JDBC
  • Servlets
  • Hibernate
  • Grails
There are more plugins available and it's even quite easy to create some of your own and that's what the rest of this post is about.

Writing your own Spring Insight plugin

Working with Hippo CMS driven web applications every day I had the idea of creating a Spring Insight plugin for the Hippo Site Toolkit (HST in short). The HST consists of a set of components that interact with the Hippo content repository. During a single request multiple components can be called and for each component there are multiple processing phases. So my initial idea for the Spring Insight plugin was to show:
  1. The amount of time taken for each processing phase of an HST component
  2. The time it takes to perform an HstQuery to the repository
Because the default Spring Insight plugins are open source I was able to write my first plugin in about 30 minutes or so. A large part of those 30 minutes were taken up with learning AspectsJ, because I'd never used that before.

Getting started

For this post we will now focus on creating an inspection on performing HST queries. From the Insight web application view I would like to see the information  of an HstQuery and time it took to perform the actual query.
With AspectJ you can pick a join point and inspect for instance the execution of that join point. In our case I would like to inspect the HstQuery.execute() method. By putting the join point on the HstQuery interface, we've made sure that any object extending the HstQuery will be able to represent it's data within the Insight web application.

Let's first take a look at the what such an inspection looks like.


package com.jeroenreijn.insight.hst;

import com.springsource.insight.collection.AbstractOperationCollectionAspect;
import com.springsource.insight.intercept.operation.Operation;
import com.springsource.insight.intercept.operation.OperationType;

import org.aspectj.lang.JoinPoint;
import org.hippoecm.hst.content.beans.query.HstQuery;
import org.hippoecm.hst.content.beans.query.HstQueryResult;
import org.hippoecm.hst.content.beans.query.exceptions.QueryException;

/**
 * Aspect for collecting HstQuery executions.
 */
public aspect HstQueryOperationAspect extends AbstractOperationCollectionAspect {

    private static final OperationType TYPE = OperationType.valueOf("query_execute");

    public pointcut collectionPoint(): execution(HstQueryResult HstQuery.execute());

    public Operation createOperation(JoinPoint jp) {
        HstQuery query = (HstQuery) jp.getTarget();
        Operation op = new Operation()
                .type(TYPE)
                .label("HstQuery");
        op.sourceCodeLocation(getSourceCodeLocation(jp));
        try {
            op.put("query", query.getQueryAsString(false));
            op.put("limit", query.getLimit());
            op.put("offset", query.getOffset());
        } catch (QueryException e) {
            // ignore for now
        }
        return op;
    }

}

The more important part of the above collection aspect is the collectionPoint poincut, where we define what kind of operation we would like to collect information from. In this case we define an inspection on the HstQuery.execute() method.
Next to the collection point you will also see the createOperation()  method. which allows you to collect certain information from the current state of the collection point. In the above code snippet we collect the actually HstQuery object and get some information from it like the actual JCR XPath query, the limit set on the query and the offset.  That's all for the information collection part of our plugin.

Now that we've created the aspect for the HstQuery, let's create a view for this inspection. You can create a freemarker template for each inspection if you want. For the HstQuery I've created the following template.

<#ftl strip_whitespace=true>
<#import "/insight-1.0.ftl" as insight />

<@insight.group label="HST Query">
    <@insight.entry name="Query" value=operation.query />
    <@insight.entry name="Limit" value=operation.limit />
    <@insight.entry name="Offset" value=operation.offset/>
</@insight.group>

In the above template we define the values that we've put as attributes on our Operation object. All we have to do now is wire the operation and the view together inside the plugin configuration.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:insight="http://www.springframework.org/schema/insight-idk"
 xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  http://www.springframework.org/schema/insight-idk http://www.springframework.org/schema/insight-idk/insight-idk-1.0.xsd">

<insight:plugin name="hst" version="${project.version}" publisher="Jeroen Reijn" />

  <insight:operation-view operation="query_execute" template="com/jeroenreijn/insight/hst/query.ftl" />

  <insight:operation-group group="Hippo" operation="query_execute" />

</beans>


So now that we've finished our plugin, we package it and drop it inside the collection-plugins folder of our Spring Insight instance. Next we fire up the VMware vFabric TM tc Server and do some requests on the web application that we would like to get some information from. Once that's done switch the URL in the browser to '/insight' and there is the information collected by Spring Insight. The image below show exactly the information that we tried to show.




In this example request you can see from the top of the call stack, the chain of filters that the request went through and all of the HST components. For each component you can now see the class, the window name (as you can also see in the CMS console) and the render path ( the JSP or Freemarker template) used for rendering the information of the component. You can also expand an HST component when it contains an HstQuery.

The advantage of having such a plugin might help us identify some slow pages that might have slow JCR queries or components that do extensive (unnecessary) processing.

Summary

Spring Insight is a very interesting project. Doing a quick scan for troublesome code is relatively fast, but can for now only be done with the VMware vFabric TM tc Server, so you cannot run it in your personal preferred application container like Tomcat, Jetty or JBoss. I've personally added Spring Insight to my default set of tools for figuring out performance issues when I need to do a review of a project.

All of the above code and how to install this HST Spring Insight plugin can be found on the plugin project page on Github.

12 December 2011

Make your date range queries in Jackrabbit go faster!

As you might know Hippo CMS uses Apache Jackrabbit as the core for it's content repository. One of Jackrabbits features is 'search' and the execution of most queries are delegated to Apache Lucene. If you want to keep the queries as fast as possible you sometimes have to analyze how your repository is behaving with the content in your project.

The problem

One of our customers noticed that they had some unexpected memory peaks and slow response times while their system was running during the day. They were using Jackrabbit 2.2.5 at the time. To get some more insight on what was going on we first started out by looking at the server logs. They were using the Jackrabbit search functionality quite heavily, so we replayed the server request logs on the acceptance environment. During the replay we set the log level of the Query to debug, so we were able to see how long each query took. We soon discovered that the longest queries were 'range queries' and also noticed that during the execution of such a range query the memory usage reached some peaks.

User view of a date range
In this specific case the problamatic queries were date range queries. A date range query is a query that for instance searches for a document between day x and day y.

As an example: Give me all documents that were created between 2007-01-01 and 2011-01-01. This is a very typical search filter, which you will see in all kind of applications.

In plain Jackrabbit a date range query (xpath notation) will look something like this:
//element(*,custom:document)[@custom:date >=xs:dateTime('2007-01-01T00:00:00.000Z') and @custom:date <=xs:dateTime('2010-01-01T00:00:00.000Z')] order by @custom:date descending

Now if you would be using the Hippo HST you would have probably used the Filter.addGreaterOrEqualThan and passed along a Date object as an argument, which automatically is being converted into the above syntax.

The analysis

To get some insight in what was causing this behaviour I created a unit test that performed a variety of range queries on a set of 100.000 simple documents/nodes. For this test I created a very simple nodetype definition that would hold a date/date-time property in different kind of formats. The used nodetype looks like this:

[custom:document]
- custom:date (date) 
- custom:dateasstringwithhoursandminutesandseconds (string)
- custom:dateasstringwithhoursandminutes (string)
- custom:dateasstring (string)

So looking at the above nodetype definition we have a node that contains 4 properties, where we have a normal JCR date (and time) property and next to that there are 3 properties that have a more fine-grained format of the date-time.

Trying to create a real world scenario the unit test generates documents starting from 01-01-2001. With every new document the test adds 1 hour and 3 seconds to the date field. After creating 100.000
nodes it ends up somewhere around 2012-07-03 03:19:57. The test will then sleeps for about 60 seconds (gives lucene time to finish up it's indexing) before it starts doing the range queries.

In finding a solution I created 4 different versions of the range query where I start narrowing down on the date format to get closer to the actual date (without the time). In the test case 4 different kind of queries are peformed and repeated 5 times before moving on to the next type of query. The range queries performed are:
  • Normal range query (with JCR date-time format like mentioned above)
  • Range query with date as string with format yyyyMMddHHmmss
  • Range query with date as string with format yyyyMMddHHmm
  • Range query with date as string with format yyyyMMdd

Queries 1 to 3 took an average of 3500 ms (3.5 seconds) with a large memory footprint usage of about 380MB per query. That's huge and slow for just a simple query! You can imagine this might end up leading to OutOfMemory errors.
Memory usage overtime while performing the queries (graph comes from VisualVM)

However the fourth query is actually quite fast and takes less memory! It's a really significant difference. The fourth query takes about 180 ms on average and uses about 40-50MB. It's still a lot of memory (in my opinion), but since they are a lot faster the total amount of used memory might not be that large, because the amount of memory is freed much earlier in the process.

Looking at the graph on the right you will see there is no difference between query 1 to 3, but option 4 (which is in fact actually what a date range should do) showed a really large improvement on overall performance and memory usage. So in the end it turns out that the 'time' in the default JCR date format was actually giving us the issues. Because the time was added to the date value, the number of unique values for the date property in the lucene index had become larger then needed causing the slowdown.

A solution

Now as a solution we solved this by adding a derived data function that extracts the simplified date property. For range queries we now do the range on the 'yyyyMMdd' formatted date and order the results by the original date property, so that the time is taken into account and the sort order is correct. Using the simple date format will also help when trying to find documents/nodes that belong to a certain date. This has just turned into a simple 'equals' instead of a range from 0:00 till 23:59:59.

If you are currently using Apache Jackrabbit and are using these kind of queries you might want to rethink you current content model. A small change might give you a huge performance boost!