Search code examples
javaeclipseosgiosgi-bundle

How to use Eclipse Interface Command Provider in Activator class in OSGI


I'm new to code with Eclipse Interface Command Provider. I saw an example at the website

public void _say(CommandInterpreter ci) {
    ci.print("You said:" + ci.nextArgument());
}

@Override
public String getHelp() {
    return "\tsay - repeats what you say\n";
}

It is used to get command as String and print it again.

Now this is another one to execute the command

String command = intcp.nextArgument();
if (command != null) {
    intcp.execute(command);
}

Why we use this execute(command) method? and How to use it? Are there any examples for it ?


Solution

  • OSGI console is used mainly for debugging OSGI applications. It's not very convenient way to implement a calculator. Plain console application would be better. Anyway, it's a good way to familiarize yourself with the API.

    First, create a class implementing CommandProvider:

    public class Calculator implements CommandProvider {
    
        // add prints sum of its two arguments
        public void _add(CommandInterpreter ci) {
            int a = Integer.parseInt(ci.nextArgument());
            int b = Integer.parseInt(ci.nextArgument());
            ci.println(a+b);
        }
    
        // quit just calls "exit"
        public void _quit(CommandInterpreter ci) {
            ci.execute("exit");
        }
    
        @Override
        public String getHelp() {
            return "";
        }
    
    }
    

    You need to register it in your bundle's activator:

    public class Activator implements BundleActivator {
    
        public void start(BundleContext bundleContext) throws Exception {
            bundleContext.registerService(CommandProvider.class.getName(),
                    new Calculator(), null);
        }
    
        @Override
        public void stop(BundleContext context) throws Exception {
        }
    }
    

    To actually use those command, you need to start RCP application with -console command line argument. If your bundle is loaded lazily, it needs to be started before commands will be available:

    osgi> start com.example.mybundle
    osgi> add 2 2
    4
    osgi> quit
    Really want to stop Equinox? (y/n; default=y)  y