Dashboard > blojsom 3.0 > ... > Plugin API Examples > Average Size Example
  blojsom 3.0 Log In   View a printable version of the current page.  
  Average Size Example
Added by David Czarnecki, last edited by David Czarnecki on Dec 03, 2006  (view change)
Labels: 
(None)

Average Size Plugin

Calculates the average size of the entries that pass through the plugin and places that average in the context.

Coding the Plugin

The following AverageSizePlugin.java file should be placed in a package called org.blojsom.plugin.example and compiled.

org.blojsom.plugin.example.AverageSizePlugin
package org.blojsom.plugin.example;

import org.blojsom.plugin.Plugin;
import org.blojsom.plugin.PluginException;
import org.blojsom.blog.Entry;
import org.blojsom.blog.Blog;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

public class AverageSizePlugin implements Plugin {

    public AverageSizePlugin() {
    }

    public void init() throws PluginException {
    }

    public Entry[] process(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Blog blog, Map context, Entry[] entries) throws PluginException {
        int size = 0;

        for (int i = 0; i < entries.length; i++) {
            Entry entry = entries[i];

            size += entry.getDescription().length();
        }

        context.put("AVERAGE_ENTRY_SIZE", new Integer(size / entries.length));
        
        return entries;
    }

    public void cleanup() throws PluginException {
    }

    public void destroy() throws PluginException {
    }
}

Configuring the Plugin

The compiled AverageSizePlugin.class should be placed in blojsom's /WEB-INF/classes directory keeping the org/blojsom/plugin/example directory structure.

Add the following to blojsom's plugin configuration file. /WEB-INF/classes/blojsom-plugins.xml.

<bean id="average-size" class="org.blojsom.plugin.example.AverageSizePlugin" init-method="init" destroy-method="destroy"/>

After starting your server, you can login to blojsom's web administration console and add this plugin to run in one of your plugin chains. This is configured under Plugins | Mappings. As this plugin doesn't depend on any other plugins, you can add it anywhere in the plugin chain.

Using the Plugin

In your template, for example using Velocity, you can now print out the average placed into the context from the plugin.

#if ($AVERAGE_ENTRY_SIZE)
The average size of the entries on this page is: $AVERAGE_ENTRY_SIZE
#end

This simply checks to see that an average is available in the context and if so, prints the value.

Site running on a free Atlassian Confluence Open Source Project License granted to blojsom. Evaluate Confluence today.
Powered by Atlassian Confluence, the Enterprise Wiki. (Version: 2.5.4 Build:#809 Jun 12, 2007) - Bug/feature request - Contact Administrators