Showing posts with label hippo. Show all posts
Showing posts with label hippo. Show all posts

19 February 2014

Using Markdown with the Maven site plugin

I find that generating Maven project documentation is always a bit cumbersome with the default XDOC or APT ("Almost Plain Text") syntaxes. This probably has to do with getting accustomed to using Markdown while doing my thing on GitHub, which is sort of the de facto standard there.

While writing some documentation for a new Hippo CMS plugin the other day I noticed that the maven site plugin already supports the Markdown syntax and it's actually quite easy to setup, but the markdown-doxia-module documentation is a bit limited. With this post I hope shed some more light and help you get going with using Markdown for writing documentation.

First up we need to define the maven-site-plugin in our project pom.xml file. If you start with version 3.3 the markdown-doxia-module will already be included. However for this post I will use the latest version ( at this moment 1.5 ), so I have to define it explicitly in my POM file.

<plugins>
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-site-plugin</artifactId>
    <version>3.3</version>
    <dependencies>
      <dependency>
        <groupId>org.apache.maven.doxia</groupId>
        <artifactId>doxia-module-markdown</artifactId>
        <version>1.5</version>
      </dependency>
    </dependencies>
  </plugin>
</plugins>

Next, we will need to create the directory  src/site/markdown which will hold our Markdown files. Make sure the files have the .md extension.

Now let's start with a simple file called index.md that needs to go into the markdown folder. To prove that it will render markdown syntax we can use the following snippet as content.

A First Level Header
====================

A Second Level Header
---------------------

Now is the time for all good men to come to
the aid of their country. This is just a
regular paragraph.

The quick brown fox jumped over the lazy
dog's back.

### Header 3

> This is a blockquote.
> 
> This is the second paragraph in the blockquote.
>
> ## This is an H2 in a blockquote 
 
Now start the maven-site-plugin from the command-line:

$ mvn site:run

and point your browser to http://localhost:8080/ and see the beautiful result!

A concrete implementation can be found on the Hippo forge.



05 September 2013

The mystery of the Bootstrap application during a Maven build on Mac OS

In my day to day job I'm a Java coder working on a MacBook Pro running OS X (Mountain Lion) and recently one thing started to really annoy me. While performing an Apache Maven build cycle occasionally an application pops up in my OS X dock and while browsing the web or composing an e-mail the focus is lost and moves to the just started application. In my case these applcations are most of the time called Bootstrap or ForkedBooter.

I asked around a little if any of my fellow coders experienced this as well and it seems so, but nobody took the time to figure out what was going on. The answers are out there on the web, but you really need to know what to search for before finding a proper answer.

ForkedBooter

If you see the ForkedBooter application pop up in your dock this is most likely due to the maven-surefire-plugin which is being executed during the test phase of the Maven build lifecycle.

It's actually quite easy to get rid of this application popping up in the OS X dock by telling Maven to run Java in headless mode. To do so I've added the following line to my .bash_profile file stored in my users home directory. In my case this is located in /Users/jreijn.

export MAVEN_OPTS="-Xms256m -Xmx512m -XX:PermSize=64m -XX:MaxPermSize=256m -Djava.awt.headless=true"

By adding the headless directive it will tell Maven and the plugins (which embrace the MAVEN_OPTS) to run Java in headless mode.

This should resolve the ForkedBooter popping up in the OS X dock.

Bootstrap

The Bootstrap application showing up in the dock is actually quite specific and originates from starting up Apache Tomcat somewhere during the Maven build. In my specific case this was because at Hippo we use the cargo-maven2-plugin to fire up Apache Tomcat to run the CMS and site web application inside a Tomcat instance.

There are several ways of solving this. One of the possible options I found was to change Tomcats  conf/catalina.properties file and add the following line at the end of the file.

java.awt.headless=true

When using a standalone Tomcat instance this way of solving is fine, but you could also add this to the catalina.sh or the startup.sh scripts.

Now in the scenario of using the Maven cargo plugin the container might be reinstalled on every build and this will overwrite your changes. There are two (or more) approaches again to solve this problem.

The first approach would be to add the catalina.properties file to your local project and copy it over when cargo installs the container.

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.cargo</groupId>
      <artifactId>cargo-maven2-plugin</artifactId>
      <configuration>
        <configuration>
          <configfiles>
            <configfile>
              <file>${project.basedir}/conf/catalina.properties</file>
              <todir>conf/</todir>
              <tofile>catalina.properties</tofile>
            </configfile>
          </configfiles>
        </configuration>
      </configuration>
    </plugin>
  </plugins>
</build>

The problem with this approach is that you will have a local copy inside your project which you have to recheck when upgrading the cargo plugin or the container instance or it might not work when switching to a different container then Tomcat.

The other more simple approach which will work across multiple containers is by adding a system property to the cargo plugin.

<build>
  <plugins>
    <plugin>
      <groupId>org.codehaus.cargo</groupId>
      <artifactId>cargo-maven2-plugin</artifactId>
      <configuration>
        <container>
          <systemProperties>
            <java.awt.headless>true</java.awt.headless>
          </systemProperties>
        </container>
      </configuration>
    </plugin>
  </plugins>
</build>

This way the system property is added to the Java run-time when starting up Tomcat from cargo and the Bootstrap application does not pop up anymore inside the OS X dock.

I hope this post will help those of you in search for the same answers and could not find it.

References


Stack overflow: Any idea why org.apache.catalina.startup.Bootstrap pops up in dock on Mac?
Jenkins JIRA: on OSX a java icon jump on dock for all starting maven build and takes focus

22 July 2013

Real-time visitor analysis with Couchbase, Elasticsearch and Kibana

At Hippo we recently started using Couchbase as the storage solution for our targeting/relevance module. Couchbase is a really high performant NoSQL database, which since version 2.0 can be used as a (JSON) document database. Couchbase is really fast when it comes to simple CRUD operations, but does lack some search capabilities like Geo-spatial search (still 'experimental' mode) and free text search, which you might find in other document oriented NoSQL databases like MongoDB.

However the lack of these search capabilities can be overcome quite easily by combining Couchbase with Elasticsearch by using the Couchbase-Elasticsearch transport plugin. The plugin uses the Couchbase built-in cross data center replication mechanism (XDCR), which can be used for replicating data between Couchbase clusters. It sort of makes Elasticsearch act just like another Couchbase cluster.

In this post we will go through all the necessary steps to setup Couchbase, Elasticsearch and Kibana for doing 'real-time' visitor analysis.

If you are familiar with LogStash you might wonder why we use Couchbase as an additional storage for our request data. Well it's because with Hippo CMS we store more than just the request log information. We also store information about a visitor over multiple requests with regards to (content) characteristics and persona based matching. We need a cluster-wide high performance database for that and that's why we use Couchbase as a first layer of storage.

Setting up Couchbase

As I've said before at Hippo we use Couchbase as our storage solution. For installation instructions please see the official Couchbase download page. Couchbase uses data buckets for storage. There are two kind of buckets available; 'couchbase' buckets and 'memcached' buckets. For this specific use-case you will need to create a bucket of type 'couchbase' called 'targeting'. Buckets of type 'couchbase' allow you to store JSON documents and perform for instance map-reduce functions on the available data in a bucket.

In this bucket we will be storing request data. An example of a request document could look similar to this:

{
  "visitorId": "7a1c7e75-8539-40",
  "pageUrl": "http://www.mydomain.com/news",
  "pathInfo": "/news",
  "remoteAddr": "127.0.0.1",
  "referer": "http://www.mydomain.com/",
  "timestamp": 1371419505909,
  "collectorData": {
    "geo": {
      "country": "",
      "city": "",
      "latitude": 0,
      "longitude": 0
    },
    "returningvisitor": false,
    "channel": "English Website"
  },
  "personaIdScores": [],
  "globalPersonaIdScores": []
}

The above snippet is taken from the requestlog of our documentation website. As you can see our relevance/targeting module is collecting data about visitors (like geo data, type of channel a user is visiting, etc) and this data is stored in Couchbase as a JSON document.
Now that we have this data inside our database we would like to slice this data and see what our visitors are doing over time.

Elasticsearch

Elasticsearch is probably one of the most rapidly adopted technologies. It has adoption by companies like Github, StackOverflow and Foursquare. For those of you not yet familiar with Elasticsearch; it's a distributed (JSON based) document storage solution with advanced query capabilities and often used for distributed search and analytics.

If you already have Elasticsearch installed on your machine you can skip this step, but if you don't then let's first start with installing Elasticsearch. For ease of use I've written down all the manual command-line steps, so this is easy to reproduce.
$ curl -O https://download.elasticsearch.org/elasticsearch/elasticsearch/elasticsearch-0.90.2.tar.gz
This will download Elasticsearch 0.90.2 to your local directory. Now let's unzip it and move move on to installing the Couchbase plugin.
$ tar xzvf elasticsearch-0.90.2.tar.gz 

Adding the Couchbase transport plugin

Since we're using the latest version of Elasticsearch we need to manually build the Couchbase transport plugin from Github. This part is a little more tricky, but still quite easy to do. Let's first do a checkout of the transport plugin from Github.
$ git clone https://github.com/couchbaselabs/elasticsearch-transport-couchbase.git
Since the transport plugin depends on a SNAPSHOT of the couchbase-capi-server module we will need to build that locally as well.
$ git clone https://github.com/couchbaselabs/couchbase-capi-server.git
Now let's build the capi server first.
$ cd couchbase-capi-server/ && mvn clean install
This installs the dependency into your local maven repository for later usage.
Now we need to switch back to the transport plugin directory and we need to create the plugin package:
$ cd ../elasticsearch-transport-couchbase/
$ mvn clean package
Now that both dependencies have been build we can continue to installing the plugin into Elasticsearch. Let's first switch back to our Elasticsearch install directory.
$ cd ../elasticsearch-0.90.2/
Due to an issue with the elasticsearch 0.90.2 plugin manager we need to install the plugin without the Elasticsearch plugin manager. Let's first manually create the transport-couchbase plugin directory.
$ mkdir plugins/transport-couchbase
$ cd plugins/transport-couchbase
Next we need to unzip the plugin archive we just created.
$ unzip [/path/to/your/githubcheckout/]elasticsearch-transport-couchbase/target/releases/elasticsearch-transport-couchbase-1.0.1-SNAPSHOT.zip
Now we also need to set a proper username and password for the connection from Couchbase (needed for replication).
$ cd ../../ 
$ echo "couchbase.password: password" >> config/elasticsearch.yml
$ echo "couchbase.username: Administrator" >> config/elasticsearch.yml 
Now that everything is in place we can fire up elasticsearch. 
$ ./bin/elasticsearch -f
During startup you should see something  similar to:
[2013-07-22 10:57:43,940][INFO ][transport.couchbase] [Toro] bound_address {inet[0.0.0.0/0.0.0.0:9091]}, publish_address {inet[/10.10.100.156:9091]} 
With transport.couchbase in the start up log it means the Couchbase transport plugin started correctly and is running on port 9091 (you will need this later on).
So far for getting the connection up and running. For more information about configuring the transport plugin please read the official documentation.

Storing data in Elasticsearch

Let's first create a new index to hold our data.
$ curl -XPUT 'http://localhost:9200/targeting'
If you follow the official Couchbase transport plugin documentation you will also need to import the Couchbase mapping file, so that elasticsearch knows how to index (or not) certain fields. The transport plugin comes with a mapping for Couchbase documents which marks all documents coming from Couchbase to be indexed and not stored within Elasticsearch. This default is there because Couchbase itself is really fast in getting the document and it does not need elasticsearch to store the document. That's fine for most use cases, but in our case we would like use our data later on to view it in Kibana, so we will need to create our own simple mapping for documents coming from Couchbase.

Now that we have our index created we will need to add the mapping for our document of type couchbaseDocument.
$ curl -XPUT 'http://localhost:9200/targeting/couchbaseDocument/_mapping' -d '{
    "couchbaseDocument": {
        "properties": {
            "doc": {
                "properties": {
                    "timestamp": {
                        "type": "date"
                    },
                    "remoteAddr": {
                        "type": "ip"
                    },
                    "collectorData": {
                        "properties": {
                            "channel": {
                                "type": "string",
                                "index": "not_analyzed"
                            },
                            "audience": {
                                "properties": {
                                    "terms": {
                                        "type": "array"
                                    }
                                }
                            },
                            "categories": {
                                "properties": {
                                    "terms": {
                                        "type": "array"
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    } 
}'
You should see:
{"ok":true,"acknowledged":true}
 
The above mapping maps certain fields of our example request log document and tells Elasticsearch how to index those specific fields. With the mapping in place we can go into the Couchbase Admin Console and create a reference to our Elasticsearch cluster. Keep in mind that port 9091 is the port we've seen before when starting Elasticsearch with the couchbase-transport plugin.



Next we need to setup replication from Couchbase to Elasticsearch. The target bucket in this case is the Elasticsearch index called 'targeting' which we created a few minutes ago.


Now when you press replicate Couchbase will start replicating your existing data into the targeting index within Elasticsearch. Now let's move on to our final step: setting up Kibana 3.


Analytics with Kibana 3


Kibana 3 is an open source (ASL 2.0) analytics and search interface, which you can use for any kind of timestamped data sets stored in Elasticsearch. It's really easy to use and gives you a visually attractive representation of the data in graphs, charts and (world)maps. With Kibana you can easily create your own dashboard that represents a nice overview of your dataset.

Kibana 3 is a very easy to install HTML + Javascript application. It only requires a webserver and a connection to Elasticsearch. For more information on how to install Kibana see the introduction page. If you run Elasticsearch on a different port then 9200 you will need to change the config.js file and point it to your Elasticsearch instance. I'll skip the the installation and move on to showing the data in our own dashboard.


Now when the data is in Elasticsearch you can start adding panels to your dashboard. Adding a pie chart is as easy as couple of clicks. Here is an example of how to add a pie chart panel based on the available channels(sites) within Hippo CMS.



Now when you add a set of panels you might and up with entire dashboard with live streaming data. 
One of the nice features of Kibana is that it can load a dashboard configuration from GitHub by using a gist URL. A dashboard I created for Hippo targeting data can be found at: https://gist.github.com/jreijn/5830593
It's is a nice example of a dashboard and it's based on request log information of our online documentation website.
Well that's it. In this post we've seen how to setup Couchbase, Elasticsearch and Kibana to perform real-time visitor analysis for your website / web application. Last month at the Hippo GetTogether 2013 I gave a live demonstration of what I've written here. When the video becomes available I'll do a short update or new post, so you can hear more about our relevance module and the integration with Couchbase. 

References

19 February 2013

Hippo Fridays @ Hippo

At Hippo we have a concept we call 'Hippo Fridays'. Hippo Fridays are monthly Fridays on which all Hippo developers can share knowledge, try out new things, work on improvements or hack on their own pet project. We've been having Hippo Fridays for more then a year and even if it's only one day a month, they are always great fun!

The other day while leaving the office I overheard one of my colleagues ask what the actual outcome is of these Hippo Fridays. Does something end up in the product? Well let me share what has come out of the more recent Hippo Fridays and will end up in the upcoming Hippo CMS 7.8 release.


HTML5 History API in the CMS and Console

With the upcoming Hippo CMS 7.8 release both CMS and Console will make use of the HTML5 history API. This might sounds a bit vague and technical, but it means that the CMS and Console will store the URLs to the documents that you visited in your browsers history. By doing that it will allow you to reach them by using your browsers history or by using a direct URL in the browsers address bar. See the address bar in the picture below.

Multiple Console improvements

The more experienced Hippo users will probably notice some new options in the Console menu bar.
The Console UI was improved with some new features to benefit the user experience:
  • deletion of multiple nodes
  • keyboard shortcuts
  • open a node by path or UUID
  • use the arrow keys to navigate the tree  
The next image shows you all the keyboard-shortcuts that are available in the Console.


Scripting support

With the upcoming 7.8 release we will also have scripting support straight from the CMS UI. This feature will be for 'admin' users only. Scripting support is focused on supporting JCR runner / visitors from the CMS UI and helps you do bulk updates of document or just plain JCR nodes. The scripting support in CMS 7.8 was inspired by the introduction of the Hippo CMS Groovy add-on, which started out as a prototype on a Hippo Friday.

 

SNEAK PREVIEW: Settings management

This next feature is one of my own pet projects. Those of you who are experienced with Hippo CMS know that Hippo CMS is very flexible and you can configure all most everything. However most of the configuration options are done through the CMS Console.

With the settings management add-on there will be a new user friendly interface and you might even discover some options you never knew existed. Since this is still under heavy development it will not end up in the CMS 7.8 release, but I will keep you posted when a first release is made, so you can try it out.



As you can see: What happens on Hippo Fridays does not stay on Hippo Fridays!

22 January 2013

Get involved with the Hippo CMS Community!

Hippo CMS has a rapid growing community, so we want to see our community well organized and connected. With this post I would like to remind you about the available channels to communicate with each other (and the Hippo team) to get information, resolve problems and share experiences.

Twitter

I guess the most popular channel is Twitter. You can read up on all the latest news regarding Hippo CMS while following the @onehippo account. We use this for official announcements, news about Hippo as a company and many other things. For feedback, plugin announcements and other interesting Hippo news please make use of the  #hippocms hash tag or mention @onehippo in your tweet and we will retweet your post to the rest of the community.

Facebook

The Hippo CMS Facebook page contains a lot of community driven content. It's main use is for building up the Hippo timeline and fun (like all the submissions for the Hippo's in the wild competition). Even though the competition ended at the end of 2012 don't hesitate to send us your photos of the lovely orange Hippo giveaways.

Google Plus

Since last month there is also a Hippo CMS Community on Google Plus. This is mainly a communication channel for spreading news, information about Hippo and for bringing together all the Hippo users that use Google Plus as their 'social network'.

LinkedIn

The Hippo CMS user group on LinkedIn with over 241 members is probably the most concentrated group of Hippo minded people out there. The group on LinkedIn is used for different purposes like, discussions, jobs, etc. If you're not yet connected to the user group please do!

Hippo Community Forum

Currently the best resource for getting (technical) feedback or asking questions is probably the Hippo Community Forum.

Stack Overflow

Stack Overflow is becoming the site to find all your development answers these days. If you want to ask questions on Stack Overflow about Hippo CMS, be sure to ask the question with the tag 'hippocms'. By doing so you can get answers by other Stack Overflow users and members of the Hippo team. 

IRC

A community initiative recently started (thanks to Yassine Elassad) to also have a self-help IRC channel available on freenode. The channel can be found at:

irc://chat.freenode.net#hippo-cms

You can find community members and some Hippo developers being present in this channel.

The Hippo blog

Our official Hippo CMS blog is the main place where we post about Hippo CMS and Content management in general. You will be able to get a heads up on insights, upcoming releases and tips & tricks.

If you reached all the way the the end of this post you will see that Hippo is present on different channels. We hope to see and meet you in any or all of them. Let's stay connected! 

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!


16 February 2011

HIPPOs RESTful JAX-RS Component Support and Spring Android

The new Hippo CMS 7.5 release brings some quite interesting features. The most interesting new feature for me was support for RESTful components within the Hippo Site Toolkit (HST-2 v2.20.01). Being able to expose data in a RESTful manner opens up a whole new set of possibilities for external application developers.

As you might have read in my previous post, I'm building a sample application to get acquainted with the Android platform. My previous post was mainly focussed on layouts and ListViews, but this time I will be focussing on information retrieval from an external REST service. That's why I've used the default REST service that comes with the online Hippo GoGreen demo as my source of information.  The GoGreen REST service exposes a list of 'top products' with additional information about the products that can be used nicely for this demo project, but first let's start at the beginning.

Getting started with RESTful HST-2 components

From what I've seen in the documentation and in the GoGreen source code, there are two different methods of exposing data with the RESTful components.
  1. The data can be exposed based on the primary JCR NodeType of a resource inside the Hippo repository. The HST-2 sitemap will determine the URLs of the items based on the relative path of the items inside the repository. This approach can be done with the JaxrsRestContentPipeline.
  2. A sitemap item (or mount) can be configured as a JaxrsRestPlainPipeline. By doing so, the HST will try to match the request within a Jax-RS based resource provider component that handles all the (relative) URL matching from there on.   
    In this example I will use the JaxrsRestPlainPipeline approach, which is also used by the Hippo GoGreen demo to create the 'top products' resource. The response output of a REST pipeline can be in all kinds of different formats. For this example we will use JSON, but you can also use XML instead.

    Configuration


    The first step in the proces of setting up our own REST service is to create an HST mount. The configuration for our mount has to look something similar to :

    <sv:node sv:name="restapi">
      <sv:property sv:name="jcr:primaryType" sv:type="Name">
        <sv:value>hst:mount</sv:value>
      </sv:property>
      <sv:property sv:name="hst:alias" sv:type="String">
        <sv:value>restapi</sv:value>
      </sv:property>
      <sv:property sv:name="hst:authenticated" sv:type="Boolean">
        <sv:value>false</sv:value>
      </sv:property>
      <sv:property sv:name="hst:isSite" sv:type="Boolean">
        <sv:value>false</sv:value>
      </sv:property>
      <sv:property sv:name="hst:mountpoint" sv:type="String">
        <sv:value>/hst:hst/hst:sites/rest-live</sv:value>
      </sv:property>
      <sv:property sv:name="hst:mountsite" sv:type="String">
        <sv:value>site</sv:value>
      </sv:property>
      <sv:property sv:name="hst:namedpipeline" sv:type="String">
        <sv:value>JaxrsRestContentPipeline</sv:value>
      </sv:property>
      <sv:property sv:name="hst:roles" sv:type="String">
        <sv:value>everybody</sv:value>
      </sv:property>
      <sv:property sv:name="hst:showport" sv:type="Boolean">
        <sv:value>true</sv:value>
      </sv:property>
      <sv:property sv:name="hst:subjectbasedsession" sv:type="Boolean">
        <sv:value>true</sv:value>
      </sv:property>
      <sv:property sv:name="hst:types" sv:type="String">
        <sv:value>rest</sv:value>
      </sv:property>
    </sv:node>
    

    As you can see there is lot to configure for a mount, but I don not want to go into much detail. The next step is to setup an HST sitemap for this mount. In the configuration above, our mount uses a default namedpipeline of type  JaxrsRestContentPipeline , since we want to use a  JaxrsRestPlainPipeline, we can override the type of pipeline by specifying the hst:namedpipeline property on an HST sitemap item for this mount, for example for the sitemap item called 'topproducts'.

    <sv:node sv:name="topproducts">
      <sv:property sv:name="jcr:primaryType" sv:type="Name">
        <sv:value>hst:sitemapitem</sv:value>
      </sv:property>
      <sv:property sv:name="hst:namedpipeline" sv:type="String">
        <sv:value>JaxrsRestPlainPipeline</sv:value>
      </sv:property>
    </sv:node>
    

    Spring Configuration

    Now after we stored the HST-2 configuration in the repository, the next step is to register our new component as a plain resource provider in our website Spring configuration. We can do this by creating a file called custom-jaxrs-resources.xml in the src/main/resources/META-INF/hst-assembly/overrides/ folder of our Hippo site project with the following content.

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans" 
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
      
      <import resource="classpath:/org/hippoecm/hst/site/optional/jaxrs/SpringComponentManager-rest-jackson.xml" />
      <import resource="classpath:/org/hippoecm/hst/site/optional/jaxrs/SpringComponentManager-rest-plain-pipeline.xml" />
      <import resource="classpath:/org/hippoecm/hst/site/optional/jaxrs/SpringComponentManager-rest-content-pipeline.xml" />
      
      <!-- Custom JAX-RS REST Plain Resource Providers to be overriden. -->
      <bean id="customRestPlainResourceProviders" class="org.springframework.beans.factory.config.ListFactoryBean">
        <property name="sourceList">
          <list>
            <bean class="org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider">
              <constructor-arg>
                <bean class="com.onehippo.gogreen.jaxrs.services.TopProductsResource" />
              </constructor-arg>
            </bean>
          </list>
        </property>
      </bean>
          
    </beans>
    

    With this configuration in place the HST-2 has knowledge of our custom resource and the TopProductsResource can start creating the response.

    Now let's take a look at our TopProductsResource.

    @Path("/topproducts/") 
    public class TopProductsResource extends AbstractResource {
      @GET
      @Path("/topproducts/")
      public List<ProductLinkRepresentation> getProductResources(@Context HttpServletRequest servletRequest, @Context HttpServletResponse servletResponse, @Context UriInfo uriInfo,
                @QueryParam("sortby") @DefaultValue("hippogogreen:rating") String sortBy, 
                @QueryParam("sortdir") @DefaultValue("descending") String sortDirection,
                @QueryParam("max") @DefaultValue("10") String maxParam) {
            
          List<ProductLinkRepresentation> productRepList = new ArrayList<ProductLinkRepresentation>();
          HstRequestContext requestContext = getRequestContext(servletRequest);
            
          try {
              Node mountContentNode = getNodeFromMount(requestContext);
              HstQueryResult result = getHstQueryResult(sortBy, sortDirection, maxParam, requestContext, mountContentNode);
              HippoBeanIterator iterator = result.getHippoBeans();
    
              while (iterator.hasNext()) {
                  Product productBean = (Product) iterator.nextHippoBean();
                    
                  if (productBean != null) {
                    ProductLinkRepresentation productRep = new ProductLinkRepresentation(requestContext).represent(productBean);
                    productRepList.add(productRep);
                  }
              }
          } catch (Exception e) {
            log.warn("Failed to retrieve top products. {}", e);        
            throw new WebApplicationException(e);
          }
            
          return productRepList;
      }
    }
    

    The TopProductsResource has a @Path("/topproducts/") annotation set on the class level. This is what's making the request to '/topproducts' being handled by this specific resource. As you can see the only other thing the resource does is perform the query from the getProductResources() method. Take a look at the full source code for more details on the TopProductsResource class.

    Response output


    Now that we've setup the configuration and put the component in place, let's take a look at our actual response. You can see what the response of the TopProductsResource is if you go to the following URL:

    http://www.demo.onehippo.com/restapi/topproducts?_type=json

    Note: the URL might not be available at the time you try it, because the GoGreen demo is restarted every 30 minutes with a fresh set of content. If the URL does not work try again in 5 minutes.

    Since we specified the response type as JSON, the actual response should look something like what is shown below. For readability I've removed some properties, but I guess you get the idea.

    [
      {
        productLink: "http://www.demo.onehippo.com/restapi/products/food/2010/07/organic-cotton-reusable-lunch-bag./"
        price: 34
        rating: 5
        smallThumbnail: "http://www.demo.onehippo.com/binaries/smallthumbnail/content/gallery/products/2010/06/organic-lunch-bag.jpg"
        localizedName: "Organic Cotton Reusable Lunch Bag"
        primaryNodeTypeName: "hippogogreen:product"
      },
      {
        productLink: "http://www.demo.onehippo.com/restapi/products/food/2010/07/birch-wood-compostable-cutlery./"
        price: 5
        rating: 4.25
        smallThumbnail: "http://www.demo.onehippo.com/binaries/smallthumbnail/content/gallery/products/2010/07/wooden-cutlery.png"
        localizedName: "Birch Wood Compostable Cutlery"
        primaryNodeTypeName: "hippogogreen:product"
      }
    ]
    

    As you can see the response is quite simple and contains an array of product items with their properties.
    If you want to know more about RESTful Component support there is a nice page on the HST-2 wiki. Now let's move on with the Android part of this post.

    Spring Android

    Android version 2.2 has native support for handling JSON. I tried that, but I recently discovered Spring Android. Spring Android is quite new and gives you an easy to use REST client. The reason I chose to use Spring Android is that it takes less code to handle requests then by doing it the native Android way with the default HttpClient. Now when we combining Spring Android with Jackson it makes working with JSON really easy. All you have to do is create a mapping class, so that Jackson knows how to map the response array.

    To be able to work with the JSON response we will need the following three libraries in our Android project.
    • spring-android-rest-template-1.0.0.M2.jar
    • jackson-core-asl-1.7.1.jar
    • jackson-mapper-asl-1.7.1.jar

    Using Spring Android


    For my Android application I've created a service class called ProductService.

    public class ProductService {
      private static final String RESTAPI_BASE_URI = "http://www.demo.onehippo.com/restapi";
      private static final String RESTAPI_RESPONSE_TYPE = "_type=json";
    
      public static ArrayList<Product> getAllProductsFromHippo() {
        ArrayList<Product> products = new ArrayList<Product>();
        RestTemplate restTemplate = new RestTemplate();
        
        List<HttpMessageConverter<?>> messageConverters = restTemplate.getMessageConverters();
        //add the Jackson mapper for easy mapping of JSON to POJO's
        messageConverters.add(new MappingJacksonHttpMessageConverter());
    
        String url = RESTAPI_BASE_URI + "/topproducts./?" + RESTAPI_RESPONSE_TYPE;
    
        Product[] productsFromHippo = restTemplate.getForObject(url, Product[].class);
        products.addAll(Arrays.asList(productsFromHippo));
        return products;
      }
    }
    

    As you can see the getAllProductsFromHippo method uses the Spring Android RestTemplate in combination with the MappingJacksonHttpMessageConverter to map the JSON response to an array of Product classes. Let's have a closer look at a Product class.

    package org.onehippo.gogreen.android.data;
    
    import org.codehaus.jackson.annotate.JsonIgnoreProperties;
    import org.codehaus.jackson.annotate.JsonProperty;
    
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class Product {
    
      @JsonProperty
      private String localizedName;
    
      public String getLocalizedName() {
          return localizedName;
      }
    
      public void setLocalizedName(final String localizedName) {
          this.localizedName = localizedName;
      }
    }
    

    The Product class is quite simple. It only contains the localized name (for now). To make sure the mapping succeeds, I've also added the annotation JsonIgnoreProperties , so that it will ignore unknown properties during the mapping phase.
    Now if we provide the list of Product items to the Android ArrayAdapter, which is used by our ListView we will see all the items in the list returned by the HST-2 REST service.

    Resources used

    The following resources were used to create this post:

    10 January 2011

    Tip of the day: sharing information between HST components

    If you're working as a web developer with Hippo CMS, I guess you have written quite a few HST components. I presume that by now you will have a basic understanding of what HST components can and can't do.
    I've had the situation myself where I wanted to share some information between components on a single page. I first thought I could simply achieve this by adding an attribute to the request, but that didn't work. To show you what you can do, let's first start of with a bit of background information about what's actually going on inside the HST, when an incoming request is being processed.

    HST request processing


    Let's first have a look at a page definition. In a traditional HST page definition you have a tree of components. The figure below describes a normal page layout defintion.


    As you can see the page definition in the above figure has a root component (the page definition itself) with three child components: component 1, component 2 and component 3. Now the follow flow chart shows what the HST will do when it's handling a request.

    This flow chart of couse does not show all the steps taken by the HST,
    but it should give you a good impression of what's going on.

    At first the HST will lookup the correct page definition based on the HST sitemap. Once the correct page definition has been found the HST will start processing.

    The entire component tree for the current page definition is fetched and once the tree is there, the HST will use the AggregationValve to run down the component tree and invoke the doBeforeRender() methods of all of the available components.

    Once the entire component three has been processed in the 'before render phase', it will start processing the doRender() methods of all the components, so that the output of every single component will be generated and aggregated to end up in the end result.

    Now the important part to know here is that each invoked component will have it's own individual HStRequest object. Now if you want to share any kind of information you cannot simply use the HstRequest, because all the information is gone while processing the next component.
    However there is an object attached to these individual HstRequest objects and that is the HstRequestContext. The HstRequestContext hold some quite useful information, which you help support your components, but you can also add your own information by setting some attribute.


    Enough theory for now. If you would like to have a deeper knowledge of the HST request processing, the proces is described in much more detail on the HST2 wiki.


    Now for some code


    As an example let's take the usage of banners on a page. Let's say we have a boolean flag configured somewhere, which will define if banners should be shown on our page.

    Let's presume that a banner can be shown by multiple components on a page. If we take figure 1, we could say that a banner could appear above component 2 and underneath component 3.

    Now we could let both component 2 and component 3 figure out if the banners should be shown, but we could also share the information if component 2 or 3 is executed first, so that the other component does not have to read the configuration over again. The resulting code is quite simple. Let's have a look.

    @Override
    public void doBeforeRender(HstRequest request, HstResponse response) {
      boolean isBannerEnabled;
      HstRequestContext requestContext = request.getRequestContext();
      //let's see if the flag has been set on the request context
      if(requestContext.getAttribute(IS_BANNER_ENABLED_ATTRIBUTE)!=null){
        isBannerEnabled = (Boolean)requestContext.getAttribute(IS_BANNER_ENABLED_ATTRIBUTE);
      } else {
        //nothing on the request context, so lets figure it out
        isBannerEnabled = isBannerEnabled(request);
        //put the result on the request context so all other components can benefit
        requestContext.setAttribute(IS_BANNER_ENABLED_ATTRIBUTE, isBannerEnabled);
      }
      //put on the request for the current component
      request.setAttribute(IS_BANNER_ENABLED_ATTRIBUTE, isBannerEnabled);
    }
    
    /**
     * Simply return true for this example.
     */
    boolean isBannerEnabled(HstRequest request) {
      return true;
    }
    

    As you will see the actual code is really simple. All you will have to do is store information on the HstRequestContext. That's it. Well these were my 2 cents for today. Go and have fun and try to leverage the power of the HST2.