Thursday, February 12, 2009

A scripting bundle for OSGi

I've wrapped the scriptconsole4j as an OSGi bundle (tested in Apache Felix 1.4.0 and Equinox 3.4.0).

This console is a simple GUI that allows using the JSR-223 compatible scripting languages available in you Java 6 VM. The Rhino Engine (Javascript) is available by default.

If you want to execute scripts accessing the OSGi framework to retrieve services in adhoc scripts, you may find this version of the scriptconsole4j tool useful. When the bundle is started a scripting window is automatically displayed. Upon bundle termination, the window is disposed and vice-versa.

How to use it:
  • Just download it.
  • Install it on your favorite OSGi framework
  • Start the bundle
  • And its ready to be used

You can, for example, register listeners to framework objects:


var o = new Object();
o.bundleChanged = function(e) {
message = "An event happened to bundle "
+ e.getBundle().getBundleId();
output.println(message);
//Writing in the standard output
java.lang.System.out.println(message);
};

ctx.addBundleListener(new org.osgi.framework.BundleListener(o));

Since the bundle uses DynamicImport-Package, you can use it with any exported class, so you can dynamically implement and register services:

var o = new Object();
o.sayHello = function() { java.lang.System.out.println("closed")};

r = new com.foo.HelloServerService(o);
//registering the service in the OSGi Service Registry
ctx.registerService("foo.BarService",r,null);
//retrieving the service instance
service = ctx.getService(ctx.getServiceReference("foo.BarService"));
service.myMethod();

Take a look at the Rhino page showing how to use Java from Javascript, and use your imagination for the scripts that may help you.

Recently I needed the scripting functionality in OSGi on a Java 5 Virtual Machine, which does not come with the JSR-223. I've removed the JSR-223 dependant stuff from the scriptconsole4j and embedded the beanshell core with it. It worked fine but without dynamic class generation. I guess by adding the bsh-classgen it "would" work. Since we are running on OSGi, classloading is always an issue when dynamically generating stuff...
I'll test it and leave it available soon (I hope so).