`
hustlong
  • 浏览: 121258 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

用MyEclipse开发OSGi的例子

    博客分类:
  • OSGI
阅读更多
OSGi:Open Service GateWay Initiative。
熟悉Myeclipse的开发者肯定会喜欢它的插件机制的,在这种可扩展的机制后面,就是OSGi 的支持。Equinox就是一个OSGI规范的实现。我在MyEclipse下做了个小小的例子。通过这个例子,能对OSGI有个直观的感受。

1,建立插件工程:名称为:com.systemmanagement.services
选择目标平台的时候要注意选择OSGi Framework,Standard和Equinox都可以。
然后就是在这个工程下建立一个服务接口:

package com.systemmanagement.services.monitor;


public interface SysMonitor {

public String showCPUInfo();
}

为了让这个接口能作为服务被导出,需要在Manifest文件中做点修改:
加入这句:Export-Package: com.systemmanagement.services.monitor

2,再新建一个插件工程,名称为,com.systemmanagement.cpumonitor.建立这个工程的过程中选中自动生成Activator。
这个工程中有一个CpuMonitor类实现了SysMonitor接口。这个类的代码如下:
package com.systemmanagement.cpumonitor;

import com.systemmanagement.services.monitor.SysMonitor;

public class CpuMonitor  implements SysMonitor{

public String showCPUInfo()
{
return "CPU is in a good state ,don't worry";
}
}

同样的要对Manifest文件做修改:
加入:Import-Package: com.systemmanagement.services.monitor,org.osgi.framework;version="1.3.0"

自动生成的Activator类的代码有start和stop方法要实现:
代码如下:

package com.systemmanagement.cpumonitor;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import com.systemmanagement.services.monitor.SysMonitor;
import com.systemmanagement.cpumonitor.CpuMonitor;
import org.osgi.framework.ServiceRegistration;
import java.util.Properties;

public class Activator implements BundleActivator {

/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
BundleContext context=null;
ServiceRegistration sr=null;
public void start(BundleContext context) throws Exception {
this.context=context;
CpuMonitor cpumonitor=new CpuMonitor();
Properties pro=new Properties();
pro.put("device", "cpu");
sr=this.context.registerService(SysMonitor.class.getName(), cpumonitor, pro);

}

/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {
sr.unregister();
        context=null;

}

}

3,还要再建立第三个插件工程,命名为com.systemmanagement.console。
先修改Manifest:Import-Package: com.systemmanagement.services.monitor, org.osgi.util.tracker,  org.osgi.framework;version="1.3.0"

这个工程中有一下几个Class:

package com.systemmanagement.console;

import java.util.HashSet;
import java.util.Iterator;
import com.systemmanagement.services.monitor.SysMonitor;

public class ConsoleThread extends Thread{

private HashSet<SysMonitor> monitor=new HashSet<SysMonitor>();
private boolean running= Boolean.TRUE;

public ConsoleThread()
{}

public void addService(SysMonitor service)
{
this.monitor.add(service);
}

public void removeService(SysMonitor service)
{
this.monitor.remove(service);
}

public void run()
{
while(running)
{
for (Iterator<SysMonitor> sysit=monitor.iterator();sysit.hasNext();)
{
SysMonitor sysmonitor=sysit.next();
System.out.println(sysmonitor.showCPUInfo());

}
try
{
Thread.sleep(5000);
}
catch(Exception e)
{
System.out.println("Thread Exception");
}
}
}

public void stopThread()

{
this.running=false;
try
{
this.join();
}
catch(Exception e)
{
System.out.println(e.getLocalizedMessage());
}
}

}


MonitorServiceTracker:

package com.systemmanagement.console;

import org.osgi.framework.ServiceReference;
import org.osgi.util.tracker.*;
import org.osgi.framework.*;
import com.systemmanagement.services.monitor.*;

public class MonitorServiceTracker implements ServiceTrackerCustomizer {

private BundleContext bctx;
private ConsoleThread thread;

public MonitorServiceTracker(BundleContext ctx,ConsoleThread th)
{
this.bctx=ctx;
this.thread=th;

}
public Object addingService(ServiceReference arg0) {
// TODO Auto-generated method stub
SysMonitor service=(SysMonitor)bctx.getService(arg0);
thread.addService(service);
return service;
}

public void modifiedService(ServiceReference arg0, Object arg1) {
// TODO Auto-generated method stub
SysMonitor service=(SysMonitor)bctx.getService(arg0);
thread.addService(service);

}

public void removedService(ServiceReference arg0, Object arg1) {
// TODO Auto-generated method stub
SysMonitor service=(SysMonitor)bctx.getService(arg0);
thread.removeService(service);
}


}


还有一个Activator:

package com.systemmanagement.console;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.util.tracker.*;
import com.systemmanagement.services.monitor.*;

public class Activator implements BundleActivator {

/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#start(org.osgi.framework.BundleContext)
*/
private BundleContext context;
private ServiceTracker servicetrack;
private ConsoleThread thread=new ConsoleThread();

public void start(BundleContext context) throws Exception {

this.context=context;
servicetrack=new ServiceTracker(context,SysMonitor.class.getName(),new MonitorServiceTracker(context,thread));
servicetrack.open();
this.thread.start();
}


/*
* (non-Javadoc)
* @see org.osgi.framework.BundleActivator#stop(org.osgi.framework.BundleContext)
*/
public void stop(BundleContext context) throws Exception {

servicetrack.close();
this.thread.stopThread();
}

}

4,要用到的代码就这些了,下面来看看效果吧。
上面我们建立的三个插件工程其实就是SOGI概念中的Bundle,那么这些bundle需要在OSGI框架下运行和管理,如果你装了Eclipse那么Equinox就是一个现有的SOGi框架了,在你的硬盘上找出这个包:org.eclipse.osgi.jar  版本可以是其他的。
我把它copy到了一个简单的目录下:F:commonLib/osgi下面;
然后在命令下进入到上述目录,运行:java -jar org.eclipse.osgi.jar -console
出现了 osgi-> 然后就可以运行sogi的命令了:
运行help可以查看到可用的命令,列举如下:

osgi> help

Valid commands:
---Controlling the OSGi framework---
        launch - start the OSGi Framework
        shutdown - shutdown the OSGi Framework
        close - shutdown and exit
        exit - exit immediately (System.exit)
        init - uninstall all bundles
        setprop <key>=<value> - set the OSGi property
---Controlling Bundles---
        install - install and optionally start bundle from the given URL
        uninstall - uninstall the specified bundle(s)
        start - start the specified bundle(s)
        stop - stop the specified bundle(s)
        refresh - refresh the packages of the specified bundles
        update - update the specified bundle(s)
---Displaying Status---
        status [-s [<comma separated list of bundle states>]  [<segment of bsn>]
] - display installed bundles and registered services
        ss [-s [<comma separated list of bundle states>]  [<segment of bsn>]] -
display installed bundles (short status)
        services {filter} - display registered service details
        packages {<pkgname>|<id>|<location>} - display imported/exported package
details
        bundles [-s [<comma separated list of bundle states>]  [<segment of bsn>
]] - display details for all installed bundles
        bundle (<id>|<location>) - display details for the specified bundle(s)
        headers (<id>|<location>) - print bundle headers
        log (<id>|<location>) - display log entries
---Extras---
        exec <command> - execute a command in a separate process and wait
        fork <command> - execute a command in a separate process
        gc - perform a garbage collection
        getprop  { name } - displays the system properties with the given name,
or all of them.
---Controlling Start Level---
        sl {(<id>|<location>)} - display the start level for the specified bundl
e, or for the framework if no bundle specified
        setfwsl <start level> - set the framework start level
        setbsl <start level> (<id>|<location>) - set the start level for the bun
dle(s)
        setibsl <start level> - set the initial bundle start level
---Controlling the Profiling---
        profilelog - Display & flush the profile log messages

---Eclipse Runtime commands.---
        diag - Displays unsatisfied constraints for the specified bundle(s).
---Controlling the Console---
        more - More prompt for console output

然后就install我们刚才写的那几个Bundles吧;
第一步是打包刚才写的bundle:在myeclipse里面通过export,然后仅选择我们自己写的三个和osgi framework这四个,然后选择一个路径,finish之后,就自动生成了jar包。

接下来就可以运行install命令了:install :file:///youpath/service.jar
依次装载三个jar 。
然后在用ss查看状态和序号,
分别运行:start 2 ; start 3; start4 ;
好了你看到想要的结果了。然后体验osgi吧。
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics