Wednesday, November 26, 2008

Instant custom-formatted feeds with ROME, Velocity

It's nice when technologies blend well. ROME is a free, open-source, Java-based feed (Atom/RSS) parser and publishing library from Sun. And it works oh so well with Velocity templates.

Java/Servlet code:

import java.net.*;
import com.sun.syndication.feed.synd.*;
import com.sun.syndication.io.*;

...

URL feedUrl = new
URL("http://codewandering.blogspot.com/feeds/posts/default");
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(feedUrl));

List entries = feed.getEntries();

context.put("entries",entries);

StringWriter body = new StringWriter();
Velocity.mergeTemplate("Feed.vtl",context,body);
out.print(body.toString());


Velocity code:

#foreach($entry in $entries)
<a href="$entry.link">$entry.title</a><br/>
#{end}

Sample output:

Bruce Schneier as national CTO?

Regression testing for any web application with TeamCity, Selenium, and JUnit

The future of portable gaming

Summary

Because Velocity accesses beans and nested beans via a simple property interface, and ROME parses feed XML into bean structures, you can easily extract exactly the parts of the feeds that you want. The above just does titles and links, but a full list of properties supported by ROME (as getter methods) is given here. Now you have the view flexibility of Velocity matched with feed data ideally structured for it.

And since you're doing the parsing on the server side, you won't risk that nasty "Access to restricted URI denied" code: "1012" error or related security risk.

No comments:

Copyright 2011 by William Cain