论坛首页 Java企业应用论坛

为Equinox的控制台(Console)增加自己的命令

浏览 5023 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
作者 正文
   发表时间:2007-01-14  
SOA

        由于项目需要, 偶开始研究Equinox, 发现它的console做得很不错, 于是就想, 如果能把项目整合到equinox, 让console也支持项目特定的命令就好了, 于是开始研究可行性, 发现这是很简单的事情, 下面就来说说如何把自定义的命令添加到Equinox上的...

        开说之前先提一句: Console并不是OSGi规范所要求的, 也就是说, 如果实现这个功能, 那项目就对Equinox有所依赖了. 所以大家在使用这个功能之前要确定自己的项目有没有跨OSGi实现的要求, 如果有的话, 那本方法就不能使用了.

        Equinox 定义了命令提供商接口 CommandProvider, 它位于 org.eclipse.osgi.framework.console 包下, 大家可以在 org.eclipse.osgi_x.x.x.xxxxxx.jar 包中找到. CommandProvider 接口只有一个方法 getHelp(), 该方法用于在用户敲入 help 命令时显示所列出的命令帮助. 而自定义命令就是创建公共的(public)、以下划线("_")开头且带有一个类型为org.eclipse.osgi.framework.console.CommandInterpreter 参数的方法, 其中下划线后面的方法名称就是命令的名称, 例如 _uname(CommandInterpreter ci) 就是 Console 中的 uname 命令. 最后, 把实现类通过 BundleContext .registerService(...) 方法, 注册 名称为 org.eclipse.osgi.framework.console.CommandProvider  的服务. 下面有完整的代码供大家参考:

java 代码
  1. import java.util.Hashtable;   
  2.   
  3. import org.eclipse.osgi.framework.console.CommandInterpreter;   
  4. import org.eclipse.osgi.framework.console.CommandProvider;   
  5. import org.osgi.framework.BundleActivator;   
  6. import org.osgi.framework.BundleContext;   
  7. import org.osgi.framework.Constants;   
  8.   
  9. public class Activator implements BundleActivator, CommandProvider {   
  10.   
  11.   private BundleContext context;   
  12.   
  13.   public void start(BundleContext context) throws Exception {   
  14.     this.context = context;   
  15.   
  16.     // 注册服务   
  17.     context.registerService(CommandProvider.class.getName(), thisnew Hashtable());   
  18.   }   
  19.   
  20.   public void stop(BundleContext context) throws Exception {}   
  21.   
  22.   /**  
  23.    * 在控制台输入 help 命令时, 所显示的帮助.  
  24.    * @see CommandProvider#getHelp()  
  25.    */  
  26.   public String getHelp() {   
  27.   
  28.     StringBuffer buffer = new StringBuffer();   
  29.   
  30.     buffer.append("\tuname - framework information\n");   
  31.        
  32.     return buffer.toString();   
  33.   
  34.   }   
  35.      
  36.   /**  
  37.    * uname 命令.  
  38.    */  
  39.   public void _uname(CommandInterpreter ci) throws Exception {   
  40.     String vendor = context.getProperty(Constants.FRAMEWORK_VENDOR);   
  41.     String version = context.getProperty(Constants.FRAMEWORK_VERSION);   
  42.     String osName = context.getProperty(Constants.FRAMEWORK_OS_NAME);   
  43.     String osVersion = context.getProperty(Constants.FRAMEWORK_OS_VERSION);   
  44.     System.out.println("\n " + vendor + " " + version + " (" + osName + " " + osVersion + ")");   
  45.   }   
  46. }  

这样后台输出的结果就是:

osgi>uname

Eclipse 1.3.0 (WindowsXP 5.1)

osgi>

论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics