Tuesday, August 16, 2011

Adding Custom Commands to the Equinox OSGi Console

Equinox is a very popular, widely used implementation of the OSGi framework. The command line console of Equinox can be accessed by running with the "-console" option.
You can run the equinox jar file with the console enabled as follows.

java -jar org.eclipse.osgi_3.6.2.R36x_v20110210.jar -console

Or you can also access the OSGi console of your Eclipse installation. Go to the folder where Eclipse is installed and run the following command.

./eclipse -console

if you type "help" command in the prompt you get, you will see a list of available commands and what they do. I am going to show you how to add your own command  to the console.


The CommandProvider interface provided by Equinox enables to extend the console by providing custom commands. We need to implement the CommandProvider interface. For each new command we add, we need to provide 'public void' methods which take in a CommandInterpreter object. Also the method names should start with an underscore and should be followed by the command name. The getHelp() method should return a string describing the commands we add, so that it can be displayed through the help command.

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

public class MyCommandProvider implements CommandProvider{

    public String getHelp() {
        return "---Custom Commands---\n" +
               "\tversion - display equinox osgi framework version\n";
    }

    public void _version (CommandInterpreter ci){
        ci.execute("getprop osgi.framework");
    }
}

Here the 'version' command is executing the already existing 'getprop' command with the 'osgi.framework' parameter. It would display all the system properties with the words 'osgi.framework'.

Now we have to inform the framework about this CommandProvider. To do that we have to register this as a service. We can do that in the Activator.

public class Activator implements BundleActivator {
    
    public void start(BundleContext context) throws Exception {
        context.registerService(CommandProvider.class.getName(),new MyCommandProvider(), null);
    }


Now run the framework in console mode, and install the bundle.

install file:///home/profile/projects/com.bundle.sample/target/sample-1.0.0.jar

Then start the bundle and run the help command. You will see the 'Custom Commands' section.
Then you can run the version command and see your new command in action.

osgi> version
osgi.framework=file:/home/nufail/src/equinox-RC2/plugins/org.eclipse.osgi_3.6.2.R36x_v20110210.jar
osgi.framework.version=3.6.2.R36x_v20110210

0 comments:

Post a Comment