Tuesday, June 04, 2013

Basic RSS Reader in Java

Part of my effort to teach myself code is to write programs that I can actually use. Since Google Reader will self-destruct in less than a month, I’ve been looking at how to roll my own RSS Reader.

I found this code at Tully Rankin’s Website. It threw a couple of errors, and I spent the evening squashing the bugs, but in the end, I got it to work. The next step will be taking this and reworking it into something in Objective-C.

Here is the code:

        import java.net.URL;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import java.util.Scanner; //ended up not being used
import java.io.InputStream;

/*
* Basic RSS Reader, 2013-05-26
* based on Java RSS Reader Example by Tully Rankin
* http://www.tullyrankin.com/java-rss-reader-example
*/

public class RSSReader {

/*
* This ended up not being needed, but I might want it in the
* future.
* Code pulled from:
* http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
*/
public static String convertStreamToString(InputStream is) {
Scanner s = new Scanner(is, "UTF-8").useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}

private static RSSReader instance = null;

private URL rssURL;

private RSSReader () {}

public static RSSReader getInstance() {
if (instance == null)
instance = new RSSReader();
return instance;
}

public void setURL(URL url) {
rssURL = url;
}

/*
* Here is where the wicket got sticky.
* The original line opened the rssURL stream and parsed it in the
* same line, which generated an unexpected end of file error. The
* solution was to open the input stream first and then parse it.
*
* Also, Tully's code referred to specific headers in his XML file.
* I modified this to refer to the DF XML file.
*/
public void writeFeed() {
try {
DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
//Document doc = builder.parse(rssURL.openStream());
InputStream is = rssURL.openStream();
//String holder = convertStreamToString(is);
//System.out.println(holder);
Document doc = builder.parse(is);

NodeList items = doc.getElementsByTagName("entry");

for (int i = 0; i < items.getLength(); i++) {
Element item = (Element)items.item(i);
System.out.println(getValue(item, "title"));
System.out.println(getValue(item, "content"));
//System.out.println(getValue(item, "link"));
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}

public String getValue(Element parent, String nodeName) {
return parent.getElementsByTagName(nodeName).item(0).getFirstChild().getNodeValue();
}

public static void main(String[] args) {
try {
RSSReader reader = RSSReader.getInstance();
reader.setURL(new URL("http://dorky.radiofreepirate.org/feeds/posts/default"));
reader.writeFeed();
} catch (Exception e) {
e.printStackTrace();
}
}
}