11 October 2010

A custom JSP tag for mediawiki

I'm pretty happy with the following custom JSP tag for mediawiki I wrote last week (http://code.google.com/p/code915/source/browse/trunk/charpak/src/WEB-INF/src/fr/inserm/umr915/charpak/j2ee/tags/MediaWikiTag.java). For a given title, it calls the mediawiki api to test if an article exists in a mediawiki installation. In my case, this system will be useful to let my users write some custom annotations to some records from our database.

<u915:mediawiki title="${geneName}" preload="Template:Gene"/>
If the article does exist on the mediawiki installation a simple hyperlink is created. If the article does not exist, an hyperlink for creating/editing the new article is displayed with a predload option: Preloading wikitext presents the user with a partially created page rather than a blank page, possibly with inline instructions for content organization..For example, in the following web application, the blue and red icons point to some existing articles or some articles to be created:


Internals

This custom tag calls the mediawiki api (e.g api.php?action=query&format=xml&titles=Charles+Darwin )and get the XML response as a DOM document. An XPath expression is then evaluated to test if an attribute '@missing' was declared for the given article.
boolean pageFound=false;
String termUTF8 = URLEncoder.encode(term,"UTF-8");
URL url=new URL(baseurl+"/api.php?action=query&format=xml&titles="+termUTF8);
URLConnection con=url.openConnection();
in=con.getInputStream();
Document dom=this.domBuilder.parse(in);
Element e=(Element)this.xpathPage.evaluate(dom,XPathConstants.NODE);
if(e!=null && e.getAttributeNode("missing")==null)
{
pageFound=true;
}
in.close();


That's it,
Pierre

No comments: