Java Reference
In-Depth Information
}
private ServiceTracker init(BundleContext context) {
ServiceTracker tracker = null;
try {
tracker = new ServiceTracker(
context, org.osgi.service.log.LogService.class.getName(), null);
tracker.open();
} catch (NoClassDefFoundError error) { }
return tracker;
}
public void close() {
if (m_tracker != null) {
m_tracker.close();
}
}
public void log(int level, String msg) {
boolean logged = false;
if (m_tracker != null) {
LogService logger = (LogService) m_tracker.getService() ;
if (logger != null) {
logger.log(level, msg);
logged = true;
}
}
if (!logged) {
System.out.println("[" + level + "] " + msg);
}
}
}
The proxy logger has a constructor that takes the BundleContext object to track log
services, an init() method to create a ServiceTracker for log services, a close()
method to stop tracking log services, and a log() method for logging messages. Look-
ing more closely at the init() method, you try to use the logging package to create a
ServiceTracker B . Because you're optionally importing the logging package, you
surround it in a try-catch block. If an exception is thrown, you set your tracker to
null ; otherwise, you end up with a valid tracker.
When a message is logged, you check if you have a valid tracker C . If so, you try to
log to a log service. Even if you have a valid tracker, that doesn't mean you have a log
service, which is why you verify it D . If you have a log service, you use it; otherwise,
you log to standard output. The important point is that you attempt to probe for the
log package only once, with a single call to init() from the constructor, because an
optional import will never be satisfied later if it's not satisfied already.
The bundle activator is shown in the following listing.
B
Creates
ServiceTracker
C
Checks for
valid tracker
Checks for
log service
D
Listing 5.2 Bundle activator creating the proxy logger
public class Activator implements BundleActivator {
private volatile Logger m_logger = null;
public void start(BundleContext context) throws Exception {
m_logger = new Logger(context);
 
Search WWH ::




Custom Search