package org.simon.jspwiki.plugin; import com.ecyrd.jspwiki.plugin.WikiPlugin; import com.ecyrd.jspwiki.plugin.PluginException; import com.ecyrd.jspwiki.WikiContext; import com.ecyrd.jspwiki.WikiEngine; import com.ecyrd.jspwiki.WikiPage; import java.util.*; import java.io.FileInputStream; import java.io.File; import java.io.IOException; import java.io.FileOutputStream; import org.apache.log4j.Category; /** * User: SimonLei * Date: 2004-2-15 * Time: 10:25:31 * $Id$ */ public class PageViewCountPlugin implements WikiPlugin { private static Category log = Category.getInstance(PageViewCountPlugin.class); private static HashMap counters = null; private static Thread counterSaveThread = null; public static final String COUNTER_PAGE = "PageCount.txt"; private static String ROOT = null; private synchronized void loadProperties(WikiEngine engine) { if (counters != null) return; counters = new HashMap(); ROOT = engine.getServletContext().getRealPath("/"); Properties stringCounters = new Properties(); try { FileInputStream fis = new FileInputStream(new File(ROOT, COUNTER_PAGE)); stringCounters.load( fis); fis.close(); } catch (IOException e) { log.error("Can't load counter page, will create a new one.", e); } Enumeration enu = stringCounters.propertyNames(); while (enu.hasMoreElements()) { String str = (String) enu.nextElement(); counters.put(str, new Counter(stringCounters.getProperty(str))); } if (counterSaveThread == null) { counterSaveThread = new CounterSaveThread(); counterSaveThread.start(); } } public String execute(WikiContext context, Map params) throws PluginException { WikiEngine engine = context.getEngine(); WikiPage page = context.getPage(); loadProperties(engine); if (page == null) return "0"; String pageName = page.getName(); synchronized (counters) { Counter counter = (Counter) counters.get(pageName); if (counter == null) { counter = new Counter(0); counters.put(pageName, counter); } counter.increase(); return counter.toString(); } } class Counter { private int count; public Counter(int _count) { count = _count; } public Counter(String _count) { try { count = Integer.parseInt(_count); } catch (Exception e) { count = 0; } } public void increase() { count++; } public String toString() { return "" + count; } } class CounterSaveThread extends Thread { public void run() { try { while (true) { synchronized (counters) { Properties stringCounters = new Properties(); Iterator iter = counters.keySet().iterator(); while (iter.hasNext()) { Object key = iter.next(); stringCounters.put(key, counters.get(key).toString()); } try { FileOutputStream fos = new FileOutputStream(new File(ROOT, COUNTER_PAGE)); stringCounters.store( fos, "The view counts for pages. Don't modify it."); fos.close (); } catch (IOException e) { log.error("Can't store counters", e); } } Thread.sleep(5 * 1000); } } catch (InterruptedException e) { log.error("The counter store thread interrupted. No more counter saved."); } } } }