Plugins as extension points for your apps!

Normally, we use plugins to help us in a daily tasks, for example: send emails, secure our actions, upload files to amazon etc.  Play itself has a lot of parts built on top of plugins, more examples: evolutions, ebean and web service client. Another usage of plugins is as extension points of our apps.

In one of my current projects, the application needs to process a lot of data and provide a visualization for the client. This is a multi tenant app. So there is a core which is responsible for processing the information and there are specialized apps which are responsible for build its own visualization. Let’s take a look in the piece of code in the core:

    public class AllocationResult {

    	public String getBrokenConstraintsAsString(){
           //need the Html object with the visualization
           return html;
    	}

    }

As you can see, after processing we need to generate the visualization part. Here is where the plugin can be used.

        public abstract class BrokenConstraintsViewPlugin implements Plugin{

        	private Application application;

        	public BrokenConstraintsViewPlugin(Application application) {
        		this.application = application;
        	}

        	public abstract Html getView(Collection<ConstraintMatchTotal> constraints);

        	@Override
        	public boolean enabled() {
        		return true;
        	}

        	@Override
        	public void onStart() {
        		// TODO Auto-generated method stub

        	}

        	@Override
        	public void onStop() {
        		// TODO Auto-generated method stub

        	}
        }    }

We created the plugin as an abstract class, in order to force the client apps to inherit this class and build the visualization. Now we can use Play to load the specialized plugin!

    public class AllocationResult {

    	private static BrokenConstraintsViewPlugin constraintsPlugin = Play
    			.application().plugin(BrokenConstraintsViewPlugin.class);

    	public String getBrokenConstraintsAsString(){
    		Html html = constraintsPlugin.getView(constraints);
    		return html.body();
    	}

    }

We can pass the abstract class as argument and the Application(negrito) class will load the specialization. Of course, you need to register your plugin in the play.plugins file.

This feature is very important in order to provide extension points in your apps.  If you are building an API using Play, maybe this feature will be helpful for you :). Thanks for reading!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s