Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Migrated to Confluence 5.3

Quick presentation

Why ?

Excerpt

Puzzles' aim is to provide an easy way to add functionalities to an application through plugins.


Puzzles will hide from you the burden and complexity of handling dynamic class loading, plugins storage, notifications, etc. It's a rather small library with no external dependency and quite easy to use.

Terminology

Package

A package is a file containing everything the plugin needs. In most cases the package will be a zip or jar file, containing images, css files, jar files, etc.

PackageReader

A PackageReader is an object that knows to read inside a package, and access the files it contains. As long as you use plugins packaged as zip/jar files, you only need to use the ZipPackageReader that comes bundled with Puzzles.

PluginStore

A PluginStore is a repository where the plugins' packages (zip/jar files mainly) will be saved. Most commonly, the store will be a folder on the local file system.

PluginDescriptor

The PluginDescriptor is metainformation about the plugin. It contains information about the name of the plugin, the author, a URL where more information can be found, but also specifies how to instanciate the plugin (in case the plugin contains java code) and the public resources of the plugin. By "Public resources", we refer to any file in the package that are to be available outside of the plugin's scope: typically, you don't want the jar libraries to be available, so you won't declare them as public resource. But if your plugin contains images that you want to display in a web application, the image will have to be declared as a public resource.

PluginDescriptorBuilder

This is an object that is able to build a PluginDescriptor instance from a file. So far, Puzzles only comes with a PluginDescriptorBuilder that builds descriptors from java's properties files.

PluginLoader

A PluginLoader has two roles: the first one is to be a front-end to the PackageReader and PluginDescriptorBuilder, so that higher level objects don't have to deal with the Package/Descriptor stuff. The second role is to load the jar dependencies of the plugin (if there are any) and to instanciate the Plugin itself.

PluginRegistry

The PluginRegistry is what you'll deal with: it hides the Storing/Loading/Reading/etc. from you. It knows which plugins are installed, it knows how to give you URLs to the plugins' resources, it can install new plugins, uninstall previously installed plugins, etc., it notifies its listeners when plugins are installed or uninstalled.

PluginListener

Any object that implements this interface and that is added to the registry's PluginListeners will be notified when a plugin is installed/uninstalled.

Two minutes tutorial

For this tutorial, we'll build a simple stupid command line application that echoes every line you type: if you enter "toto" and press return, the program will display "toto". Simple, yes, but, let's add a possibility to extend the application: before displaying what you typed, the text will be handled to a Decorator, and those decorators will be our plugins, when the application is first started, there are no plugin:

First, our Decorator interface:

Code Block
titleDecorator.java
package puzzles.tutorial;

public interface Decorator{
    public String decorate(String toDecorate);
}

then our main class:

Code Block
titleSillyApp.java
package puzzles.tutorial;

public class SillyApp{
public static void main(String[] args) throws IOException, StoreException {
        //create a store where the plugins will be stored
        PluginStore ps = new SimpleFileSystemStore(new File("/home/puzzles/tutorial/plugins/"));

        //then create the registry that will manage our plugins
        //we give it as parameters a PluginLoader, and a Class
        //Decorator.class => if we try to deploy a plugin whose main class
        //does not implement Decorator then a PluginException will be thrown.
        //The PluginLoader is a NoArgConstructorLoader => the plugins will have to have
        //a constructor with no arguments, be packaged in a zip file (or jar)
        // and the plugin descriptor will have to be named "descriptor.properties"
        PluginRegistry<Decorator> pr = new SimplePluginRegistry<Decorator>(ps, 
                               new NoArgConstructorLoader<Decorator>(new PropertiesBasedDescriptorBuilder(), 
                                                                     new ZipPackageReader("descriptor.properties")), 
                               Decorator.class);

        //this map wil hold our plugins' instances
        //NB: this is just to show a usage of PluginListener,
        //normally you would just query the PluginRegistry to get the instance
        //of the plugin you want
        final Map<String, Decorator> decoratorss = new HashMap<String, Decorator>();

        //let's add an anonymous plugin listener:
        pr.addPluginListener(new PluginListener<Decorator>() {
            //will be called when a plugin is SUCCESSFULLY installed
            public void installedPlugin(PackagedPlugin<Decorator> packagedPlugin) {
                String name = packagedPlugin.getPluginDescriptor().getName();
                decorators.put(name, packagedPlugin.getPlugin());
                System.out.println("installing plugin [" + name + "]");
            }

            //will be called when a plugin is SUCCESSFULLY uninstalled
            public void uninstalledPlugin(PackagedPlugin<Decorator> packagedPlugin) {
                String name = packagedPlugin.getPluginDescriptor().getName();
                decorators.remove(name);
                System.out.println("uninstalling plugin [" + name + "]");
            }
        });

        //to read from the command line
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        //we start up the registry to load the plugins that might already be in the store
        pr.startUp();
        while (true) {
            String cmd = br.readLine();
            //if starts with install, we try to install a plugin => the second word is
            // the location of the plugin package on the file system
            if (cmd.startsWith("install")) {
                String filename = cmd.substring(cmd.indexOf(" ")).trim();
                File plugin = new File(filename);
                try {
                    pr.installPlugin(plugin.toURL());
                } catch (StoreException e) {
                    System.out.println("error in the store while installing plugin [" + filename + "]");
                } catch (PluginException e) {
                    System.out.println("error while installing plugin [" + filename + "]");
                }
            } else if (cmd.startsWith("uninstall")) {//second word is the name of the plugin to uninstall
                String pluginName = cmd.substring(cmd.indexOf(" ")).trim();
                try {
                    pr.uninstallPlugin(pluginName);
                } catch (PluginNotFoundException e) {
                    System.out.println("No such plugin [" + e.getPluginName() + "]");
                } catch (StoreException e) {
                    System.out.println("Error while removing plugin [" + pluginName + "] from the store");
                }
            } else if (cmd.startsWith("quit") || cmd.startsWith("exit")) {
                System.out.println("Exiting");
                System.exit(1);
            } else {
                int endIndex = cmd.indexOf(" ");
                //if there are several words, the first one is considered to be the potential name of a plugin
                if (endIndex > 0) {
                    String firstWord = cmd.substring(0, endIndex);

                    String lastWords = cmd.substring(endIndex + 1);
                    //let's get the decorator from our Map
                    Decorator decorator = decorators.get(firstWord.trim());
                    if (decorator != null) {
                        //there is a decorator with the name we type
                        //so we display the decorated version of the rest of the line
                        System.out.println(decorator.decorate(lastWords));
                    } else {
                        //no decorator was found, we just echo what was typed
                        System.out.println(cmd);
                    }
                } else {
                    //just one word typed, we display it
                    System.out.println(cmd);
                }
            }
        }
    }
}

ok so you can run that now. type "border HaHaHa I'm using the internet!" and the program will answer

No Format
border HaHaHa I'm using the internet!

Easy.

Now let's write a plugin:

Code Block
titleBorderDecorator.java
package puzzles.tutorial;

public class BorderDecorator implements Decorator{
    public String decorate(String toDecorate){
        int length = toDecorate.length()+2;
        String line = "+";
        for (int i = 0 ; i<length;i++){
            line+="-";
        }
        line+="+";
        return line+"\n"+"| "+toDecorate+" |\n"+line;
    }
}

compile it and package it in a jar named border_plugin.jar (the name in itself is not important, but we reuse it later in the plugin descriptor)

then we write a plugin descriptor:

Code Block
titledescriptor.properties
#the name of the plugin
name=border
author=souk
url=http://berkano.codehaus.org/Puzzles
description=a simple border plugin
version=0.1
#the class to be instanciated
class=puzzles.tutorial.BorderDecorator
#the jars to load in order to instanciate the plugin
jars=border_plugin.jar
#and some resources, there are none here
resources=

finally let's zip all that in a file called myFirstPuzzlesPlugin.zip. So you now have a zip file which contains a jar file and a properties file, let's run the application again:

type "border HaHaHa I'm using the internet!" and the program will still answer

No Format
border HaHaHa I'm using the internet!

now type "install /path/to/zipfile/myFirstPuzzlesPlugin.zip"
Now you should see:

No Format
installing plugin [border]

now type again "border HaHaHa I'm using the internet!" and you will see:

No Format
+--------------------------------+
| HaHaHa I'm using the internet! |
+--------------------------------+

Now stop the application, and restart it, you should see:

No Format
installing plugin [border]

the plugin has been loaded since it was in the store, you can try it again, it'll work.
to uninstall it, simply type: "uninstall border".

there you go, you just used a plugin !

Using Puzzles in your project

Spring integration

Pico integration

Other ?

Puzzles out-of-the-box UI Components

for Tapestry 3 & 4