Monday, September 29, 2008

Use Java and Rome to Get an RSS Feed as Plain Old Java Objects

Use Rome to get an RSS feed/entries as POJOs (Plain Old Java Objects). Just thought I'd be the umpteenth person to post a solution to this:
import java.net.URL;
import java.net.MalformedURLException;
import java.io.IOException;

import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.sun.syndication.io.FeedException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
...
    private Log log = LogFactory.getLog(this.getClass());
    ...
    private SyndFeed getSyndFeed(String feedUrl) {
        SyndFeed feed = null;
        try {
            SyndFeedInput sfin = new SyndFeedInput();
            URL url = new URL(feedUrl);
            feed = sfin.build(new XmlReader(url.openStream(), "application/xml", false));
        }
        catch (MalformedURLException mue) {
            log.warn("Bad url: '" + feedUrl + "'", mue);
        }
        catch (IOException ioe) {
            log.warn("Problem getting data at url: '" + feedUrl + "'", ioe);
        }
        catch (FeedException fe) {
            log.warn("Problem getting/parsing feed at url: '" + fe + "'", fe);
        }

        return feed;
    }
    ...

No comments: