Showing posts with label cocoon. Show all posts
Showing posts with label cocoon. Show all posts

27 March 2011

Simple XML processing with Apache Cocoon 3

It's been a while since I've last used Apache Cocoon. I can still remember the day that I was using Cocoon for doing all my web development projects. My first introduction with Cocoon was when I started at Hippo about 8 years ago. In comparison to other frameworks, I sometimes miss the simplicity of the Cocoon pipeline concept when I have to work with XML. Especially processing larger XML files is pain in most IDE's.

The Cocoon team has been working on Cocoon 3 for a while now, so I wanted to give it a try. Having worked with both Cocoon 2.1 and 2.2, version 3 is created with two new goals in mind:
  • slim down the framework
  • make it easier to use/combine with other frameworks

From what I've seen so far, this results in that you can now do a lot more with just plain Java. Where you would need to use a sitemap XML file before, you can now do a lot with just a few lines of Java. Even though Cocoon 3 is still in alpha stage, it already looks quite promising.

Getting started

To be able to process XML with Cocoon 3, all we need are the following two maven dependencies.

<dependencies>
  <dependency>
    <groupId>org.apache.cocoon.pipeline</groupId>
    <artifactId>cocoon-pipeline</artifactId>
    <version>3.0.0-alpha-2</version>
  </dependency>

  <dependency>
    <groupId>org.apache.cocoon.sax</groupId>
    <artifactId>cocoon-sax</artifactId>
    <version>3.0.0-alpha-2</version>
  </dependency>
</dependencies>

These dependencies drag in just two more dependencies (commons-logging and cocoon-xml, so the end result will be quite small, which is really nice compared to for instance Cocoon 2.1, which came with quite some baggage.

The code

Now let's have a look at some Java code. To play around with Cocoon 3, I'm going to use the RSS feed of this blog. Let's see how Cocoon's new Java based coding works. To be able to process the XML result of the RSS feed, I've created the RSSFeedInfoGenerator. The RSSFeedInfoGenerator is a simple class that will parse a provided RSS feed url.

/**
 * RSS Feed info generator
 */
public class RSSFeedInfoGenerator {

  private static final String DEFAULT_RSS_URL = "http://blog.jeroenreijn.com/feeds/posts/default?alt=rss";

  public static void main(String[] args) {
    RSSParser parser = new RSSParser();
    if(args!=null && args.length > 0) {
      parser.setFeedURL(args[0]);
    } else {
      parser.setFeedURL(DEFAULT_RSS_URL);
    }
    parser.parse();
  }
}

So now there is a start from which we can actually build the RSS parser and use Cocoon for processing the XML. Now let's take a look at the actual RSSParser.

/**
 * Rss parser that uses Cocoon 3 pipelines for generating
 * and transforming the RSS feed to a simple XML response.
 */
public class RSSParser {

  private static final Log LOG = LogFactory.getLog(RSSParser.class);
  private String feedURL;

  /**
   * Parse the provided feed URL and generate the Feed INFO.
   */
  public void parse() {
    try {
       Pipeline<SAXPipelineComponent> pipeline = new NonCachingPipeline<SAXPipelineComponent>();
       XSLTTransformer xsltTransformer = new XSLTTransformer(this.getClass().getResource("simplify-rss.xsl"));

       pipeline.addComponent(new XMLGenerator(new URL(getFeedURL())));
       pipeline.addComponent(new CleaningTransformer());
       pipeline.addComponent(xsltTransformer);
       pipeline.addComponent(new XMLSerializer().setIndent(true));
       pipeline.setup(System.out);
       pipeline.execute();

    } catch (MalformedURLException e) {
       LOG.error("An exception occurred while parsing the RSS URL: " + e.getMessage());
    } catch (FileNotFoundException e) {
       LOG.error("An exception occurred while parsing the RSS URL: " + e.getMessage());
    } catch (Exception e) {
       LOG.error("An exception occurred trying to parse the RSS feed: " + e.getMessage());
    }
  }

  public String getFeedURL() {
    return feedURL;
  }

  public void setFeedURL(final String feedURL) {
    this.feedURL = feedURL;
  }
}


As you can see I first created a Pipeline, which in this case is SAX based. In a Cocoon pipeline you can add multiple components, so we add a Generator, two Transformers and a Serializer. The normal XML version of the RSS feed is quite large, so to make the XML result for this example quite small, we use an XSL template to remove all but the title and lastBuildDate from the RSS feed. Let's have a look at the XSL template.

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
  <xsl:output indent="yes"/>

  <xsl:template match="rss">
    <info>
      <xsl:copy-of select="channel/title"/>
      <xsl:copy-of select="channel/lastBuildDate"/>
    </info>
  </xsl:template>

  <xsl:template match="@*|node()|text()|comment()|processing-instruction()" priority="-1">
    <xsl:copy>
      <xsl:apply-templates select="@*|node()|text()|comment()|processing-instruction()" />
    </xsl:copy>
  </xsl:template>

</xsl:stylesheet>

Looks quite simple right? Now when we run the above code, the RSSParser will output an XML snippet to the terminal/console which looks like this:

<?xml version="1.0" encoding="UTF-8"?>
<info>
  <title>Jeroen Reijn</title>
  <lastBuildDate>Mon, 21 Mar 2011 22:54:06 +0000</lastBuildDate>
</info>

Final thoughts

I was able to put this example together in about 20 minutes. That's quite fast if you compare this to the old styled processing of Cocoon.
I think the Cocoon team is really far with reaching their goals. Because you are now able to write the processing logic with just some Java, this makes it easy to integrate with any existing Java based framework.
I'm curious what else will get into the first official Cocoon 3 release, because it's already quite powerful. From now on I will be using Cocoon 3, when I need to process large (and small) XML files. With the new Java based model it's easy to create a small but powerful processor.

For those interested in the source code, you can find the code on GitHub.

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.

21 October 2008

Call for papers - ApacheCon Europe 2009

Bertrand reminded me today that the submission deadline is this Friday! I probably won't sent in an submission this year, because I've not been very active within any Apache community these past months. For those of you reading this blog and thinking about sending in a proposal, be sure to send it in before this Friday!

More information about submitting a proposal for the ApacheCon EU 2009 can be found here.

07 May 2007

Looking back at the ApacheCon EU 2007


ApacheCon EU Logo Last week I had to finish up some work just before being able to leave for the ApacheCon EU 2007. I wanted to go there on Wednesday, to see Stefano's No-Nonsense Introduction to "semantic web" Technologies and some Lucene talks, but I got held up until late in the afternoon.


After my arrival at the Moevenpick Hotel I teamed up with Jasha to do some preparations for our presentation on Friday. We moved some slides and made some additions to the demo. I was pleased with the ApacheCon being held at the Moevenpick. The hotel was nice and food was good and plenty of drinks during the day time!


On Thursday there were a couple of interesting session which I wanted to attend. I started out with Apache Performance Tuning Part 1, which seemed interesting in the beginning, but in the end I noticed that my knowledge of Apache isn't as outdated as expected. Later that afternoon I visited "Up to Speed with Java Content Repository API and Jackrabbit" by Alexandru Popescu. I found it to be very interesting, since we're looking into Jackrabbit at the moment at Hippo.



Jasha and meAt the end of Thursday the lightning lottery talks took place and as usual this was a big laugh! I always find them very amusing and the speakers have a good sense of humor. Of course the Google sponsored beers helped a lot.


There were two more serious though of which one of them came by Stefano Mazzocchi. It was something he had to tell the 'Cocoon community' as a whole. Stefano invented Butterfly after leaving the message that Cocoon had become too bloated. I agree that Cocoon 2.1 is bloated, but there is a very simple explanation for that: it's lack of dependency management. That's where Cocoon 2.2 does a much better job in combination with Maven 2. I guess I will have to take an even deeper look at Stefano's latest invention, to see what he actually came up with, but it sounds interesting.



Me at the ApacheConFriday was the big day where Jasha and I had to do our presentation. After some more preparations in the morning and afternoon, we went outside to get some rest and enjoy the lovely weather. I have to say that the weather during the ApacheCon was great. We talked the entire presentation through and were ready to go! First we headed for Bertrand who did an excellent talk on XSLT and XPath.


After a short break and some some delicious ice-cream it was up to us. People started coming into the room one by one and I think we had around 35 people attending our talk. For a Friday afternoon at 16.30 pm I think we did pretty well. I noticed a lot of people left early on Friday to catch their early flight or train back home. After the talk Jasha and I both had the same feeling: It went pretty well for a first time presentation together! We both found some places in the presentation where we could improve our next talk, so we'll take that along for the next one.


After attending Andrews talk on Cocoon 2.2 and Web 2.0 we went out to enjoy the weather and some nice cold, well earned beers! I think this year was another successful ApacheCon EU. Next to all the presentations the social happening is one of the great aspects of the ApacheCon. You get to meet all the people you actually only know by name. Make sure you'll be there next year. I heard it's going to be in Amsterdam again in 2008!


For all the people that attended our talk: Thank you and I hope to see you next year!


Some extras:






25 March 2007

It's official

It's official now.
Saturday morning I got an email from the ASF that said my account had been created.

Hurray!

30 January 2007

ApacheCon EU 2007

Well it seems the word is out and our ApacheCon talk has been accepted! We were waiting for a confirmation before spreading the word, but the schedule seems to be final now.

Jasha and I were pretty amazed to hear that our proposal was selected out of all the submissions. Looking at the speakers list it's amazing to see us between all those well known Apache member and committer names. The fun part is though that if you look at the list, it seems that we're almost the only two speakers who are not in some sort affiliated with the Apache Foundation other then using one of it's great products: Apache Cocoon.

It seems that us rookies will have to compete with two big shots for audience. It's too bad that Ate Douma is speaking at the same time, since I was curious about his talk on "JSR-286: Portlet Specification 2.0 for Portal and Portlet Developers". I've been working closely with Ate lately on a new and exciting Hippo project, so the portal subject really interests me.

It seems Apache Cocoon is closing the ApacheCon Friday with Andrew coming right after us with "Web 2.0 with Cocoon 2.2". I think the order is great, because you can go from a novice to an experienced session. We hope to get your Cocoon knowledge up to date for Andrews session later that day.

If you're interested in what Apache Cocoon is all about, be sure to come and visit our session! Remember: "Basic web application development with Apache Cocoon" is where you have to be! ;-) We're more then willing to answer all your questions and hope you will enjoy our talk.

See you on the 4th of May!

13 January 2007

ApacheCon Europe 2007 proposal

The ApacheCon EU 2007 is coming up and the deadline for proposals ended last night. I've seen several ApacheCon proposals come by over the past weeks and was thinking together was Jasha that we had to do something ourselves this year.
We've both worked on a lot of projects build with Apache Cocoon for a couple of years now and know most of the pains when starting with Cocoon, so we decided to submit a proposal ourselves: "Basic web application development with Apache Cocoon".

If the proposal gets approved the session will be very low level. As less code as possible, but more of an explanation about what can be done with Cocoon, how Cocoon handles itself in the web 2.0 hype these days and why Cocoon could be useful for you.
Cocoon can do so much more then most people think. You can create really powerful applications, high performance websites and multi-publishing platforms.

We'll just see what happens next!

12 October 2006

CocoonGT: The week after

It has been a week since the CocoonGT2006. Time really flies, but now it's time for a quick flashback of all the things that happened during those days.

The GT Hackathon started for me on tuesday, since I was tied up at the office with still a lot of work to do before the big day. I was glad to be there for a couple of hours at the hackthon, so I was able to join Jeremy's talk about CForms and Dojo. I think we both came to the conclusion that Dojo is great and Cocoon should try to embrace Dojo even more, but the question remains: "What's the best way of integrating Dojo in Cocoon?".
After this interesting talk I had to head back to the Hippo office to finish up some unfinished work.

Wednesday was the big CocoonGT conference day. It started out early at 9am and kicked off with Arje's opening speech. I've seen several interesting talks about LDAP, Daisy, Hippo CMS and a very funy talk from Andrew, but there was one talk which showed something really new and exciting. Simone Gianni was talking about Cocoon blueprint. The demonstration by Simone was very interesting and Blueprint gives you a completely different perspective on building Cocoon websites. I hope he continues working on blueprint and there will be a release soon.

There are some photos available of the GT at Flickr, so be sure to check them out.

Well that's it for now. If you want to know more about the GT, be sure to attend it next year. There have been rumours going on, that it might be in Rome next year!

01 July 2006

ApacheCon Europe 2006 part 2

I'm sitting outside now in sunny Amsterdam, after catching up some sleep, rethinking the ApacheCon Europe 2006 in Dublin. Arthur, Dennis and myself arrived on wednesday evening, so we had all thursday to attend sessions. Most of them were about AJAX, but there were some other interesting sessions that I really wanted to attend as well.



The day started late for me, since I had to attend some other business first, which I will tell you about in a couple weeks or so. In the morning I had planned to attend the "The WebWork and Struts merger" session and the "Introduction to Apache MyFaces", but I was not able to join them due to the above. Arje did attend the session about Apache MyFaces and you can read-up on what happened during that session.
The next session was "MyFaces and Ajax" which was more about AJAX, then it was about MyFaces. I was interested in the AJAX part anyway, but afterwards I can't really think of what I was trying to get to know about this particular subject. It's just another way of implementing AJAX within a framework. What I did find interesting was that you hear a lot of projects switching from Prototype to the Dojo toolkit libraries. What really is there to learn about AJAX? In most cases it's just a couple of libraries for some fancy effects, XMLHTTPRequest handling or DOM processing.
In the afternoon I attended a session about "Building Highly Available Apps" which I found the be very interesting. The session was about how to build end-to-end highly available multi-tier web applications using Sequoia (http://sequoia.continuent.org) with Apache HTTP web server, Tomcat, Geronimo and Derby. The main focus in the talk was about using Sequoia.
The great thing about Sequoia is, that you do not have to change your application in order to use it, but you will just have to change the way you application connects with JDBC or ODBC. It also features high availability through an advanced RAIDb technology. I really need to give this prodcut try!
The last real session that I attended in the afternoon was about Cocoon and REST by Gianugo Rabellino. Gianugo is always fun to listen to. He's serious but has a nice way of presenting a certain subject. The talk was nothing new, but I never heard the term REST before. I learned REST (Representational State Transfer) is an architecture style of networked systems.
When all sessions ended, the Lighting Lottery Talks started. It was my first time, but it was very serious, but also very funny! Johan also did a small serious 5 minutes talk about SAnt (Shared Ant). One of the funniest session was: "What's on Kens belt". It was hilarious.
Well so far for my first ApacheCon EU experience. It was great and I hope to see everybody next year!