ROME in a Day: Parse and Publish Feeds in Java
by Mark Woodman
|
Pages: 1, 2, 3, 4, 5, 6
The warmFeed() Method
This is the heart of the FeedWarmer program. The inputs to this method are the URL of the feed we wish to "warm," and a String indicating the desired output format.
Our first order of business is to use our instance of the SyndFeedInput to build a SyndFeed bean from an input stream of the syndicated feed. The ROME library provides an XmlReader class to fetch the feed over HTTP, determine the character encoding, and provide the input stream we need.
/**
* Add FeedWarmer footer to all items of any feed,
* then republish as format specified in OUTPUT.
* @param url The feed URL to input
* @param outFormat The feed type to output. Can be:
* rss_0.9, rss_0.91, rss_0.92, rss_0.93,
* rss_0.94, rss_1.0, rss_2.0, atom_0.3,
* or atom_1.0
* @throws IOException
* @throws FeedException
*/
public String warmFeed(URL url, String outFormat)
throws IOException, FeedException
{
// Load the feed, regardless of RSS or Atom type
SyndFeed feed = input.build(new XmlReader(url));
Now that we have a populated SyndFeed bean, we can set the feed type of the output format we desire. This does not effect the structure or contents of the bean itself, but it will instruct the SyndFeedOutput on the desired XML output at the end of the method.
// Set the output format of the feed
feed.setFeedType(outFormat);
This is where the simplicity of ROME becomes evident. You don't need to use XPath or understand the structure of the feed, because you have the SyndFeed bean interface. Let's show that this feed has gone through FeedWarmer by altering the feed's title with a getter and setter:
// Modify the feed title
String newTitle = feed.getTitle() + " (Warmed)";
feed.setTitle(newTitle);
Moving beyond the trivial, we need to grab and modify each RSS item (or Atom entry) and add a footer to it. The SyndFeed bean has a getEntries() method for just that purpose. We'll use that List of SyndEntry beans to get the job done. We haven't fleshed out the addFooter() method yet, but we'll put in the call here anyway:
// Iterate through feed items, adding a footer each item
Iterator entryIter = feed.getEntries().iterator();
while (entryIter.hasNext())
{
SyndEntry entry = (SyndEntry) entryIter.next();
addFooter(entry);
}
To finish up this method, we need to output the modified feed in the format passed in as an argument. This is a job for SyndFeedOutput, which takes a SyndFeed and a Writer. We'll use a StringWriter since the method signature for warmFeed() has us returning a String:
// Generate XML in output format, regardless of original
StringWriter writer = new StringWriter();
output.output(feed, writer);
return writer.toString();
}
Now that we have the basic control structure of the FeedWarmer, we need to write the internals of the addFooter() method we referenced.