package net.colbadhombre.JSPWiki.plugins; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiPage; import com.ecyrd.jspwiki.plugin.PluginException; import com.ecyrd.jspwiki.plugin.WikiPlugin; import java.io.BufferedReader; import java.io.IOException; import java.io.StringReader; import java.util.Map; public class FortuneCookiePlugin implements WikiPlugin { public String execute(WikiContext context, Map params) throws PluginException { String pageName = (String)params.get("page"); WikiEngine engine = context.getEngine(); WikiPage page = engine.getPage( pageName ); String pageData = engine.getPureText( page ); String line = ""; BufferedReader br = null; try { br = new BufferedReader(new StringReader(pageData)); line = br.readLine(); if (line == null) { return "Fortune file empty (" + pageName + ")"; } int lineCount = -1; try { // first line is a count of the number of fortunes in the file, if it is a number. lineCount = Integer.parseInt(line); } catch (NumberFormatException nfe) { // not a number, gotta count. lineCount = 0; while (line != null) { if (line.length() > 0 && !line.trim().startsWith("//")) { lineCount++; } line = br.readLine(); } br.close(); br = new BufferedReader(new StringReader(pageData)); } // pick the line to insert int chosenLine = (int)Math.floor(lineCount * Math.random()); lineCount = 0; line = br.readLine(); while (lineCount != chosenLine && line != null) { line = br.readLine(); if (line.length() > 0 && !line.trim().startsWith("//")) { lineCount++; } } br.close(); } catch (IOException e) { return "IO exception with fortune file."; } finally { if (br != null) { try { br.close(); } catch (IOException e) { // } } } if( line.startsWith( "*" ) ) { line = line.substring( 1 ); } if( line.endsWith( "\\" ) ) { line = line.substring( 0, line.length() - 2 ); } // invoke the wiki markup translator TranslatorReader reader = new TranslatorReader( context, new StringReader( line ) ); int c; StringBuffer wikiLine = new StringBuffer(); try { while( ( c = reader.read() ) != -1 ) { wikiLine.append( (char)c ); } } catch( IOException ioe ) { // nothing } return wikiLine.toString(); } }