Java Reference
In-Depth Information
URL
handlers must be registered as
OSG
i services, which also means the handlers are
tied to their bundle lifecycle.
FIXING THE URL HANDLER ISSUE
Your first thought may be to try to disable the
URL
Handlers Service so it doesn't
install this factory. Unfortunately, there's no standard switch for this; but to disable it
in Felix, you set the
felix.service.urlhandlers
framework property to
false
. Turn-
ing off the global
URL
Handlers Service also has serious implications. It means no
bundle can contribute dynamic protocol handlers, which would break applications
that rely on the
URL
Handlers Service. It also won't fix this particular problem
because the
jeditresource
handler isn't visible to the default
URL
StreamHandler-
Factory
when you run jEdit as a bundle. The
JDK
's
URL
Handler factory uses
Class.forName()
to search the application class path for valid handlers, but your
jeditresource
handler is hidden from view inside the jEdit bundle class loader.
The solution is to register the
jeditresource
handler as a
URLStreamHandler-
Service
when the jEdit bundle is started and remove it when the bundle is stopped.
But how can you add
OSG
i-specific code without affecting classic jEdit users? Cast your
mind back to section 6.1.5, where we talked about using lifecycles to manage external
resources. This is exactly the sort of situation that requires a bundle activator, such as
the one shown next.
Listing 6.3 Bundle activator to manage the
jeditresource
handler
package org.gjt.sp.jedit;
import java.io.IOException;
import java.net.*;
import java.util.Properties;
import org.osgi.framework.*;
import org.osgi.service.url.*;
import org.gjt.sp.jedit.proto.jeditresource.Handler;
public class Activator implements BundleActivator {
private static class JEditResourceHandlerService
extends AbstractURLStreamHandlerService {
private Handler jEditResourceHandler = new Handler();
public URLConnection openConnection(URL url)
throws IOException {
return jEditResourceHandler.openConnection(url);
}
}
Delegates to
real handler
public void start(BundleContext context) {
Properties properties = new Properties();
properties.setProperty(URLConstants.URL_HANDLER_PROTOCOL,
"jeditresource");
Publishes URL
handler service
context.registerService(
URLStreamHandlerService.class.getName(),
new JEditResourceHandlerService(),