05 April 2010

Metadata extraction with Apache Tika

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

Content metadata


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

What is Apache Tika?


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

Getting started


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

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

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

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

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

The actual code


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

public class ImageMetaDataTest {

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

    private Tika tika;
    private InputStream stream;

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

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

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

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

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

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

}


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

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

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

The output of this method can be like:


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


It's as easy as that.

Looking ahead


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

04 February 2010

Jboss ModeShape: A federating JCR repository

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

What's ModeShape?

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

Connectors

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


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

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

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

Sequencers

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


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

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

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

Conclusion

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

30 January 2010

Creating an IntelliJ launcher on Ubuntu 9.10

Over the last couple of months I've slowly switched from Eclipse to IntelliJ 9 as my main IDE for Java development. After having used Eclipse for more then 5 years I got pointed to IntelliJ by friends from JTEAM, that I'm working with at one of my projects. They challenged me to start using IntelliJ, because I would eventually be impressed and would never want to switch back.

As I'm working on my Dell/Linux laptop, I used to start IntelliJ from the command line as instructed in the readme. Starting it from the command line started bugging me after a while, so I wanted to create a launcher for it. Creating a launcher seemed quite simple at first, but getting it to work was something else.

After a while I figured it out that by using the following line in my application launcher:


/bin/sh -c "export JDK_HOME=/path/to/java&&/path/to/intellij/bin/idea.sh"


I was able to get my IntelliJ launcher to work. As you might notice, you will still have to change the path to your JDK_HOME and IntelliJ installation directory, because they might be different on your own system.
I hope this post can help all of you out there trying to do the same thing.

17 December 2009

Content mangement and the semantic web

I came across the term 'semantic web' a couple of years ago, when one of the original creators of Apache Cocoon went of to work on the SIMILE Project at MIT. I didn't pay much attention to the concept of 'semantic web' back then, because I just started learning Apache Cocoon and still had a lot to learn.
But over the last couple of months I've been doing some research on the currently available standards for providing semantic data on the web with a strong focus on RDFa.

Content management

Working at Hippo, a CMS vendor based in the Netherlands & USA, makes me think in content and publishing strategies. Publishing information to the web is one of our core businesses, but I've learned over the last couple of month we can enrich our publishing platform even more by providing semantic data. I started my journey by looking around if other CMS vendors are paying attention to semantic web standards. I noticed that only a few of the enormous amount of  content management vendors actually put effort in providing semantic web functionalities for their end-users. I think that's a shame, because enrich your pages a lot.
This post should give you an insight on how you could create a website with embedded meta data (with Hippo), but let's first start with some basics.


What's the idea behind the semantic web?

The current web is very well suited for being read by people like you and me. Computers however can only analyze the words on a page, but can not see the semantics of a piece of information on that specific page, that we as people do see.
If you would allow the information on you page to be machine-readable, the computer would be able to analyze your page and extract much more information from it then just being a piece of text. That's where semantic web standards can help out.
Standards for providing semantic data on the web are not new and some of them have already been available for quite some time. Probably the two most well known are: RDF and Microformats. However recently RDFa has been getting a lot of attention by Google, Yahoo and now also the UK government.


What is RDFa?


RDFa is short for “Resource Description Framework in attributes”. This sounds a bit descriptive, but it means that RDFa provides a set of XHTML attributes, which in their turn provide a way of translating visual data on a page into machine-readable hints. So let's take a look at an example of how a simple web page is currently structured.



<html>
  <body>
    <h1>Content management and the semantic web</h1>
    <h2>Jeroen Reijn</h2>
    <p>some information</p>
  </body>
</html> 

As you can see in the above XHTML fragment, we have a page with a title, a subtitle and a small snippet of text inside the body of the page. By rendering this HTML fragment in the browser the visitor of this page will recognize this piece of text as being the title and author of the current article on the page. A machine however would need a bit more information to be sure the content can be identified as a title and author. That's where RDFa can help out. By using vocabularies, you can give meaning to specific pieces of content on a page.
Let's see what the above XHTML fragment would look like if we would use RDFa.


<html>
  <body xmlns:dc="http://purl.org/dc/elements/1.1/"> 
    <h1 property="dc:title">Content management and the semantic web</h1>
    <h2 property="dc:creator">Jeroen Reijn</h2>
    <p>some information</p>
  </body>
</html>

As shown in the example, the Dublin Core vocabulary is added to the page first. This is important to be able to use the properties inside the vocabulary later on. Once the vocabulary is in place, we can give meaning to fragments on the page. In the HTML fragment above the h1 is marked as the Dublin Core title attribute and the h2 as the Dublin Core creator attribute. With these properties in place a machine, like a search engine crawler, can now also store this as additional meta data of the page.
One of the main advantages of RDFa is that your content can processed in a more efficient way, which in turn can make your page rank higher then it might have been before.
Big search engines like Google and Yahoo already scan your website for RDFa embedded information, so why not use it?

How to use RDFa in your (hippo) website?

Hippo CMS is a content (centered) management system and it differs from other CMS's in such a way that the information inside the Hippo CMS content repository is not stored or identified as pages, but rather as content. In most cases even reusable content. To be more precise: information stored inside the content repository is stored as JCR nodes and/or properties.
Since the data is just content and not bound to any front-end technology, you can either publish it as XML, (X)HTML with some help from the Hippo Site Toolkit (HST) or any other format you might like.
Now let's take the above HTML fragment as an example and let's see what this would look like on a content level. One of the most important things to mention here is that a JCR repository has the concept of nodetype definitions in which you can configure what your data model looks like. You could compare it with for instance a XML Schema or DTD for a piece of XML, but then for the nodes and properties available in a JCR repository.


Let's first start with our content definition or in content management terms the document type. We will need three fields:

  • Title
  • Author
  • Body (rich-text field)
If you would create a document type with the Hippo CMS template editor, the resulting nodetype definition will end up looking like this:


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

[myproject:text] > hippostd:publishable, hippostd:publishableSummary, hippo:document
- myproject:title (string)
- myproject:author (string)
+ myproject:body (hippostd:html)

As you can see all three fields are available and can be used later on by any client that can read from the Java content repository. To be able to render this type of information as XHTML, we will be using the Hippo Site Toolkit. The Hippo Site Toolkit uses the concept of mapping  JCR nodes to simple Java beans, to be able to have an easier development cycle without having to learn the entire JCR API.

A Java bean representation of the JCR 'myproject:text' nodetype will look like this:

import org.hippoecm.hst.content.beans.Node; 

import org.hippoecm.hst.content.beans.standard.HippoDocument;
import org.hippoecm.hst.content.beans.standard.HippoHtml;


@Node(jcrType="myproject:text")
public class TextBean extends HippoDocument{

    public String getTitle() {
        return getProperty("myproject:title");
    }
    
    public String getAuthor() {
        return getProperty("myproject:author");
    }

    public HippoHtml getBody(){
        return getHippoHtml("myproject:body");
    }

}

As you can see the Java bean is quite straight forward and easy to read.
Now if we want to render the information on a webpage, we can use for instance JSP's with expression language to get the information from the Java bean. The JSP needed for outputting the RDFa enabled webpage can be as simple as this:

<%@ page language="java" %>
<%@ taglib uri="http://www.hippoecm.org/jsp/hst/core" prefix='hst'%>
<html>
  <body xmlns:dc="http://purl.org/dc/elements/1.1/"> 
    <h1 property="dc:title">${document.title}</h1>
    <h2 property="dc:creator">${document.author}</h2>
    <hst:html hippohtml="${document.body}"/>
  </body>
</html>
As you can see it's that easy to use RDFa inside your website if you have a template independent CMS like Hippo.

It gets even better

Using RDFa for simple text can already be a great improvement for you website, but support for other RDFa vocabularies is added on a regular basis. Google recently announced support for RDFa enabled pages with videos (or media) on them. You can provide extra information for your media files to the Google crawler, like the url to the thumbnail that belongs to your video, which can be presented when your video is found as one of the results in a search performed at Google. The possibilities are enormous, so I can see a lot of good things coming from using RDFa in the near future.

I think the role that content management systems can have for RDFa should not be underestimated, since most website these days are backed by some sort of content management system.

For more information on RDFa see:

15 September 2009

Apache Cocoon and Javascript minification

A couple of days ago somebody on the Apache Cocoon user list send a message to the mailing-list about on the fly minification of for instance Javascript files. This topic has been quite popular over the past years, since web application have become richer and Javascript files have become larger.

The ideal situation would be to compres your static files (CSS or Javascript) at build time, so this will not cost you any processing power, when your application is already running. I myself quite often use the Maven 2 YUI compressor plugin while building my projects, but in case you can't use this plugin you could think about a different solution. Since I've been using Cocoon for over more then 5 years, I thought I gave it another try and write a nice Cocoon reader that does this minification for you.

There are multiple minification and obfuscation frameworks out there. One has a greater compression ratio then the other, but for me the most well know ones are probably:
  1. Dojo Shrinksafe - Rhino based compressor from the Dojo Toolkit
  2. YUI Compressor - Rhino based compressor by Yahoo
  3. JSMin - a whitespace compressor by Douglas Crockford
Since Apache Cocoon comes with a version of Rhino and both #1 and #2 have their own version of Rhino included, this could end up having nasty conflicts because of two different versions of the library on the same classpath. Therefore I chose to write a reader based on JSMin, which does a lot of whitespace compression for you.

The implementation of this reader was quite simple and if you're interested, you can get the source here. Do keep in mind that you will have to have the JSMin.java file also on the classpath, otherwise it wil not work.