This post originated from an RSS feed registered with Java Buzz
by Nick Lothian.
Original Post: Retrieving GMail Atom feed with Rome
Feed Title: BadMagicNumber
Feed URL: http://feeds.feedburner.com/Badmagicnumber
Feed Description: Java, Development and Me
Those of you with a GMail account might like this. It retrieves the GMail
Atom feed of you inbox status using the Rome Syndication libraries (Grab Rome 0.4 and Rome Fetcher 0.4 from http://rome.dev.java.net). You'll need to edit the BasicAuthenticator
class to set your username and password.
Gmail currently doesn't support conditional-gets or ETags, so unfortunately
it has to retrieve the entire feed each time.
public class Main {
public static void main(String args[] ) throws IllegalArgumentException,
MalformedURLException, IOException, FeedException, FetcherException {
FeedFetcherCache feedInfoCache = HashMapFeedInfoCache.getInstance();
FeedFetcher fetcher = new HttpURLFeedFetcher(feedInfoCache);
java.net.Authenticator.setDefault(new BasicAuthenticator()); // turn on authentication
SyndFeed feed = fetcher.retrieveFeed(new URL("https://gmail.google.com/gmail/feed/atom"));
System.out.println(feed.getTitle());
int feedSize = feed.getEntries().size();
System.out.println("Contains " + feedSize + " items");
for (Iterator iter = feed.getEntries().iterator(); iter.hasNext(); )
{
SyndEntry entry = (SyndEntry) iter.next();
System.out.println(entry.getTitle());
System.out.println("\t excerpt: " +
entry.getDescription().getValue());
}
while (true) {
try {
Thread.sleep(1000 * 60 * 10); // check every 10 minutes
} catch (InterruptedException e) {
// ignore } System.err.print("Retrieving..");
feed = fetcher.retrieveFeed(new
URL("https://gmail.google.com/gmail/feed/atom"));
System.err.println("Done.");
int newFeedSize = feed.getEntries().size();
// note that this won't detect new items if the feed size is at maximum
if (feedSize != newFeedSize) {
System.out.println("New messages detected. There are now " +
newFeedSize + " items");
int itemsToShow = newFeedSize - feedSize;
int count = 0;
for (Iterator iter = feed.getEntries().iterator();
iter.hasNext();) {
SyndEntry entry = (SyndEntry) iter.next();
System.out.println(entry.getTitle());
System.out.println("\t excerpt: " +
entry.getDescription().getValue());
count++;
if (count >= itemsToShow) {
break;
}
}
feedSize = newFeedSize;
}
}
}
static class BasicAuthenticator extends Authenticator {
/**
* @see java.net.Authenticator#getPasswordAuthentication()
*/
protected PasswordAuthentication getPasswordAuthentication() {
if ("gmail.google.com".equals(getRequestingHost())) {
return new PasswordAuthentication("user.name", "password".toCharArray());
} else {
return null;
}
}
}
}