高老庄

八戒的梦想:农妇,山泉,有点田
posts - 4, comments - 14, trackbacks - 0, articles - 3
  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理

osgi 添加自定义命令

Posted on 2010-01-22 17:34 高老庄 阅读(583) 评论(0)  编辑  收藏 所属分类: osgi

    在使用osgi实现时,可以使用诸如install,start,stop这样的命令来管理bundle或者调用服务.有时我们可能想添加一些自定义命令.可以通过如下的步骤来实现
    1.编写一个服务,实现如下的接口

1public interface CommandProvider {
2    /**
3     Answer a string (may be as many lines as you like) with help
4     texts that explain the command.
5     */

6    public String getHelp();
7
8}


如果想定义hello方法,可以如下实现该接口:

 

import java.util.Dictionary;
import java.util.Properties;

import org.eclipse.osgi.framework.console.CommandInterpreter;
import org.eclipse.osgi.framework.console.CommandProvider;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
public class Activator implements BundleActivator,CommandProvider  {
    BundleContext bundleContext
=null;
    
public void start(BundleContext context) throws Exception {
        System.out.println(
"start" +context.getBundle().getLocation());
        bundleContext
=context;
        context.registerService(CommandProvider.
class.getName(), new AntherCommandProvider(), null);
        Dictionary dictionary
=new Properties();
        dictionary.put(Constants.SERVICE_RANKING, 
10);
        context.registerService(CommandProvider.
class.getName(), this,dictionary);
        
    }


    
public void stop(BundleContext context) throws Exception {
        System.out.println(
"end" +context.getBundle().getLocation());
    }


    
public String getHelp() {
        
return "you are using the help command";
    }

    
    
public void _helloa(CommandInterpreter intp)
    
{
        intp.println(
"helloa "+ this.getClass().getName());
    }

    
    
public void _hello(CommandInterpreter intp) throws Exception {
        intp.println(
"hello " + this.getClass().getName());
    }

}


 

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

public class AntherCommandProvider implements CommandProvider {

    
public void _hello(CommandInterpreter intp)
    
{
        intp.println(
"hello "+ this.getClass().getName());
    }

    
public String getHelp() {
        
return null;
    }

}


其中,通过CommandInterpreter类型的nextArgument()方法可以迭代出所有的命令参数.
    2.注册服务
        如果不将该接口注册为服务,这个hello命令将不产生任何作用.注册的服务名称必须是org.eclipse.osgi.framework.console.CommandProvider.
       当系统中存在多个此接口的实现时,可以通过SERVICE_RANKING属性来决定了命令执行的顺序,既有最高值的服务将被优先执行.这种方式可以重载系统中已经存在的同名服务.
     3.执行命令
    请仔细体会输出结果


只有注册用户登录后才能发表评论。


网站导航: