XWiki + Groovy = <3 : The 10 lines RSS aggregator macro

Sep 12 2009

Update : I've changed the code a little (surrounding displayed items by verbatim blocks) after Raffa's comment (see comments section on this post) to protect against code injection by RSS channel hosts.

XWiki now (starting with the 2.0 serie) supports rendering macros definition in wiki pages. And really, that opens a door to a lot of fun. It basically means for developers the ability to write macros as we write wiki content, with all the other macros available, including scripting macros. That's where groovy comes in :)

I won't go in the technical details of how to write wiki macros here - there is a tutorial on XWiki.org dev guide covering this topic. I just want to show my love for the groovy programming language (and of course for XWiki) through a 10 lines of code RSS aggregator macro.

Here it goes :

{{groovy}}
import java.util.TreeMap;
import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

def urls = [];
def entries = new TreeMap();

xcontext.macro.content.eachLine() {	urls.add(it.trim()); }

urls.each() { rssUrl ->
  def feed = new SyndFeedInput().build(new XmlReader(new URL(rssUrl)));
  feed.entries.each() {  entries.put(it.publishedDate, ["entry":it, "feed": feed]); }
}
println """|=Title|=Date|=Author|=Feed"""
(entries.keySet() as List).reverse()[0..10].each() { 
   def e = entries.get(it).entry, f = entries.get(it).feed;
   println """|[[{{{${e.title}}}}>>${e.link}]]|{{{${xwiki.formatDate(e.publishedDate)}}}}|"""
   print """{{{${e.author}}}}|{{{[[${f.title}}}}>>${f.link}]]"""
}

{{/groovy}}

That's enough. I can now call my macro from any page with :

{{rssaggregator}}
http://feeds.feedburner.com/xwikicomblogen
http://feeds.feedburner.com/massol
http://feeds.feedburner.com/ludoblog
{{/rssaggregator}}

Which will result in :

Unknown macro: rssaggregator

http://feeds.feedburner.com/ludoblog

Of course, the macro could be a lot improved - this is just a proof of concept. We could add parameters to chose the displayed columns, the maximum number of entries, etc.

Anyway, groovy is sweet, and so macros as wiki pages are :)

About Me

Amongst other things, I'm an Open Source software developer, working at XWiki. View Jerome Velociter's profile on LinkedIn

This wiki is licensed under a Creative Commons 2.0 license
XWiki Enterprise 2.4.30467 - Documentation