ExampleClient Bundle部分源代码
public void start(BundleContext context) throws Exception {
ServiceReference[] refs = context.getServiceReferences(
NameService.class.getName(), "(ClassRoom=*)");
if (refs != null) {
try {
System.out.println("Enter a blank line to exit.");
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String name = "";
// Loop endlessly.
while (true) {
// Ask the user to enter a name.
System.out.print("Enter a Name: ");
name = in.readLine();
// If the user entered a blank line, then
// exit the loop.
if (name.length() == 0) {
break;
}
// First, get a name service and then check
// if the name is correct.
NameService nameservice = (NameService) context
.getService(refs[0]);
if (nameservice.checkName(name)) {
System.out.println("The Name is Correct.");
} else {
System.out.println("The Name is Incorrect.");
}
// Unget the name service.
context.ungetService(refs[0]);
}
} catch (IOException ex) {
}
} else {
System.out.println("Couldn't find any name service...");
}
}
本文来自编程入门网:http://www.bianceng.cn/Programming/Java/201112/32263_5.htm
(3)定义Bundle描述文件MANIFEST.MF,Bundle应用example的MANIFEST.MF文件如下:
MANIFEST.MF文件信息
Manifest-Version: 1.0
Bundle-ManifestVersion: 2
Bundle-Name: Example Bundle
Bundle-SymbolicName: example
Bundle-Version: 1.0.0
Bundle-Activator: example.osgi.Activator
Bundle-Localization: plugin
Import-Package: org.osgi.framework;version="1.3.0"
Export-Package: example.service
其中,Bundle-Activator属性指明了实现BundleActivator接口的类,该类用来启动和停止Bundle应用。Export-Package属性指定了该Bundle输出的共享包,该属性可以使其他的Bundle应用引用我们所定义的服务接口。
(4)创建项目名为exampleClient的Bundle应用,该应用在OSGi平台上查寻并引用example Bundle应用已经注册的姓名查询服务,然后从标准输入读入用户所输入的姓名信息,判断所输入姓名是否有效。exampleClient应用的部分源代码如下,读者可从参考资料中获得完整源代码。
ExampleClient Bundle部分源代码
public void start(BundleContext context) throws Exception {
ServiceReference[] refs = context.getServiceReferences(
NameService.class.getName(), "(ClassRoom=*)");
if (refs != null) {
try {
System.out.println("Enter a blank line to exit.");
BufferedReader in = new BufferedReader(new InputStreamReader(
System.in));
String name = "";
// Loop endlessly.
while (true) {
// Ask the user to enter a name.
System.out.print("Enter a Name: ");
name = in.readLine();
// If the user entered a blank line, then
// exit the loop.
if (name.length() == 0) {
break;
}
// First, get a name service and then check
// if the name is correct.
NameService nameservice = (NameService) context
.getService(refs[0]);
if (nameservice.checkName(name)) {
System.out.println("The Name is Correct.");
} else {
System.out.println("The Name is Incorrect.");
}
// Unget the name service.
context.ungetService(refs[0]);
}
} catch (IOException ex) {
}
} else {
System.out.println("Couldn't find any name service...");
}
}
本文来自编程入门网:http://www.bianceng.cn/Programming/Java/201112/32263_5.htm
http://www.bianceng.cn/Programming/Java/201112/32263_5.htm