Java Reference
In-Depth Information
like any normal resource using the well-known service name as the name of the
resource file. When a concrete type is obtained from the content of the file, the code
needing the service can load and instantiate the associated class.
The
OSG
i specification uses this mechanism to provide a standard way to get the
concrete framework implementation class. But rather than directly retrieve a frame-
work implementation class,
OSG
i defines a framework factory service as follows:
public interface FrameworkFactory {
Framework newFramework(Map config);
}
This interface provides a simple way to create new framework instances and pass a con-
figuration map into them. As a concrete example, the Apache Felix framework imple-
mentation has the following entry in its
JAR
file declaring its service implementation:
META-INF/services/org.osgi.framework.launch.FrameworkFactory
The content of this
JAR
file entry is the name of the concrete class implementing the
factory service:
org.apache.felix.framework.FrameworkFactory
Of course, these details are only for illustrative purposes, because you only need to
know how to get a framework factory service instance. The standard way to do this in
Java 6 is to use
java.util.ServiceLoader
. You obtain a
ServiceLoader
instance for a
framework factory like this:
ServiceLoader<FrameworkFactory> factoryLoader =
ServiceLoader.load(FrameworkFactory.class);
Using the
ServiceLoader
instance referenced by
factoryLoader
, you can iterate over
all available
OSG
i framework factory services like this:
Iterator<FrameworkFactory> it = factoryLoader.iterator();
In most cases, you only care if there's a single provider of the factory service; you can
invoke
it.next()
to get the first available factory and use
FrameworkFactory.
newInstance()
to create a framework instance. If you're not using Java 6, you can also
use the
ClassLoader.getResource()
method as illustrated in the following listing.
Listing 13.2 Retrieving a
FrameworkFactory
service manually
private static FrameworkFactory getFrameworkFactory() throws Exception {
URL url = Main.class.getClassLoader().getResource(
"META-INF/services/org.osgi.framework.launch.FrameworkFactory");
if (url != null) {
BufferedReader br =
new BufferedReader(new InputStreamReader(url.openStream()));
try {
for (String s = br.readLine(); s != null; s = br.readLine()) {
s = s.trim();
if ((s.length() > 0) && (s.charAt(0) != '#')) {
Looks up framework
factory provider
B