Java Reference
In-Depth Information
Listing 3.8 Bundle
update
command
package org.foo.shell;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
public class UpdateCommand extends BasicCommand {
public void exec(String id) throws Exception {
Bundle bundle = getBundle(id);
bundle.update();
}
}
By now, you may have noticed the pattern we mentioned in the beginning. Most lifecy-
cle operations are methods on the
Bundle
and
BundleContext
objects. The
Bundle.
update()
method is no exception, as you can see. The
update()
method is available
in two forms: one with no parameters (shown) and one taking an input stream (not
shown). The
update
command uses the form without parameters here, which reads
the updated bundle
JAR
file using the original location value as a source
URL
. If the
bundle being updated is in the
ACTIVE
state, it needs to be stopped first, as required
by the bundle lifecycle. You don't need to do this explicitly, because the framework
does it for you, but it's still good to understand that this occurs because it impacts the
application's behavior. The update happens in either the
RESOLVED
or
INSTALLED
state
and results in a new revision of the bundle in the
INSTALLED
state. If the bundle is in
the
UNINSTALLED
state, an
IllegalStateException
is thrown. As in the
stop
com-
mand, a bundle shouldn't try to update itself.
The
Bundle-UpdateLocation
anti-pattern
We should point out an anti-practice for updating a bundle. The OSGi specification
provides a third option for updating bundles based on bundle metadata. A bundle may
declare a piece of metadata in its bundle manifest called
Bundle-UpdateLocation
.
If it's present,
Bundle.update()
with no parameters uses the update location value
specified in the metadata as the URL for retrieving the updated bundle JAR file. Using
this approach is discouraged because it's confusing if you forget it's set, and it
doesn't make sense to bake this sort of information into the bundle.
UNINSTALL COMMAND
You can now wrap up the lifecycle operations
by implementing the
uninstal
l command, as
shown next (see figure 3.12).
To uninstall a bundle, you call the
Bundle.
uninstall()
method after retrieving the
Bun-
dle
object associated with the user-supplied
bundle identifier. The framework stops the
bundle, if necessary. If the bundle is already
Installed
Uninstall
Uninstalled
Figure 3.12
The uninstall-related portion
of the bundle lifecycle state diagram