替Equinox的控制台(Console)增加自己的命令
为Equinox的控制台(Console)增加自己的命令??????? 由于项目需要, 偶开始研究Equinox, 发现它的console做
为Equinox的控制台(Console)增加自己的命令
??????? 由于项目需要, 偶开始研究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??的服务.?下面有完整的代码供大家参考:
- import?java.util.Hashtable; ??
- ??
- 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?{ ??
- ??
- ??private?BundleContext?context; ??
- ??
- ??public?void?start(BundleContext?context)?throws?Exception?{ ??
- ????this.context?=?context; ??
- ??
- ????//?注册服务 ??
- ????context.registerService(CommandProvider.class.getName(),?this,?new?Hashtable()); ??
- ??} ??
- ??
- ??public?void?stop(BundleContext?context)?throws?Exception?{} ??
- ??
- ??/** ?
- ???*?在控制台输入?help?命令时,?所显示的帮助. ?
- ???*?@see?CommandProvider#getHelp() ?
- ???*/??
- ??public?String?getHelp()?{ ??
- ??
- ????StringBuffer?buffer?=?new?StringBuffer(); ??
- ??
- ????buffer.append("\tuname?-?framework?information\n"); ??
- ???? ??
- ????return?buffer.toString(); ??
- ??
- ??} ??
- ?? ??
- ??/** ?
- ???*?uname?命令. ?
- ???*/??
- ??public?void?_uname(CommandInterpreter?ci)?throws?Exception?{ ??
- ????String?vendor?=?context.getProperty(Constants.FRAMEWORK_VENDOR); ??
- ????String?version?=?context.getProperty(Constants.FRAMEWORK_VERSION); ??
- ????String?osName?=?context.getProperty(Constants.FRAMEWORK_OS_NAME); ??
- ????String?osVersion?=?context.getProperty(Constants.FRAMEWORK_OS_VERSION); ??
- ????System.out.println("\n?"?+?vendor?+?"?"?+?version?+?"?("?+?osName?+?"?"?+?osVersion?+?")"); ??
- ??} ??
- }??
这样后台输出的结果就是:
osgi>uname
Eclipse 1.3.0 (WindowsXP 5.1)
osgi>
1 楼 gembin 2007-08-28 不错啊