Java Reference
In-Depth Information
because it may depend on some bundle that's not yet installed. By installing all the
bundles first, you stand a better chance of successfully resolving the bundles when you
activate them.
Notice also that you don't call start() on all bundles B ; instead, you only call
start () on bundles that aren't fragment bundles. Fragments can't be started and will
throw an exception if you try to start them, which is why you avoid doing so. How do
you know a bundle is a fragment? This simple approach works:
private static boolean isFragment(Bundle bundle) {
return bundle.getHeaders().get(Constants.FRAGMENT_HOST) != null;
You check to see if the bundle's manifest headers contain the Fragment-Host header.
If so, it must be a fragment, and you don't want to start it.
Starting the main bundle
You've installed and started all the bundles contained in the specified directory. In
most cases, this would be good enough. But for the examples in this topic, you need
one more step. In chapter 2, we showed how you can use the module layer all by itself
to modularize the paint program. In that example, none of the bundles contained a
BundleActivator , because activators are part of the lifecycle layer. In such an sce-
nario, you need a way to start your application: you can use the standard Java Main-
Class JAR file manifest header as a way to define a main bundle from which you can
load the main class and execute its static void main() method.
NOTE The notion of a main bundle with a main class isn't an OSG i conven-
tion or a standard. We defined this approach for this topic to show that it's
possible to use the OSG i modularity layer to modularize OSG i-unaware appli-
cations. You could also consider introducing a custom manifest header for
this purpose to avoid confusion with the standard Main-Class header.
The next listing shows how to load the main class and invoke its main() method.
Listing 13.5 Invoking the main class from the main bundle
if (mainBundle != null) {
final String className =
(String) mainBundle.getHeaders().get("Main-Class");
if (mainClassName != null) {
final Class mainClass = mainBundle.loadClass(className);
try {
Method method = mainClass.getMethod(
"main", new Class[] { String[].class });
String[] mainArgs = new String[args.length-1];
System.arraycopy(args, 1, mainArgs, 0, mainArgs.length);
method.invoke(null, new Object[] { mainArgs });
} catch (Exception ex) {
System.err.println("Error invoking main method: "
Invokes static
main method
Search WWH ::

Custom Search