Tip: Custom OSGi (Equinox) Console Commands

Tip: Custom OSGi (Equinox) Console Commands

Ever use the OSGi console included in Eclipse (i.e., run the eclipse executable with -console)?

Ever wanted to add your own console commands for your application?

If so, the process is pretty easy and straightforward. The first step is to implement the CommandProvider interface. Here is a simple and fun example:

[code lang=”java”]
package com.code9.examples.console;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;

public class MyCommandProvider implements CommandProvider {

public Object _iddqd(CommandInterpreter intp) {
intp.println(“Immortal mode enabled”);
return null;
}

public Object _idkfa(CommandInterpreter intp) {
intp.println(“Wooooo!”);
return null;
}

public Object _idclip(CommandInterpreter intp) {
intp.println(“No clipping mode on”);
return null;
}

public String getHelp() {
StringBuffer buffer = new StringBuffer();
buffer.append(“—My commands—\n\t”);
buffer.append(“iddqd – God mode\n\t”);
buffer.append(“idkfa – Armed mode\n\t”);
buffer.append(“idclip – No clipping mode\n”);
return buffer.toString();
}

}
[/code]

To extend the console, we simply need to register our implementation with the service registry. We can do this in our activator:

[code lang=”java”]
package com.code9.examples.console;

import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

public class Activator implements BundleActivator {

private CommandProvider service;

public void start(BundleContext context) throws Exception {
service = new MyCommandProvider();

// register the service
context.registerService(CommandProvider.class.getName(), service, null);
}

public void stop(BundleContext context) throws Exception {
service = null;
}

}
[/code]

And that’s it! If you give the plug-in a run, you’ll see this output:

The code for this example can be downloaded here (licensed under the EDL 1.0).