Using with OSGi
Since REST servlets are basically just HttpServlets
, incorporating them into an OSGi environment is pretty
straightforward.
The following code shows how to register your REST servlets in an OSGi Activator:
package org.apache.juneau.examples.rest;
import org.osgi.framework.*;
import org.osgi.service.http.*;
import org.osgi.util.tracker.*;
import org.apache.juneau.rest.samples.*;
/**
* Activator class used when running samples as a bundle in an OSGi environment.
*/
public class Activator implements BundleActivator, ServiceTrackerCustomizer {
private ServiceTracker httpServiceTracker;
private BundleContext context;
@Override /* BundleActivator */
public void start(BundleContext context) throws Exception {
this.context = context;
httpServiceTracker = new ServiceTracker(context, HttpService.class.getName(), this);
httpServiceTracker.open();
}
@Override /* BundleActivator */
public void stop(BundleContext context) throws Exception {
httpServiceTracker.close();
}
@Override /* ServiceTrackerCustomizer */
public Object addingService(ServiceReference reference) {
Object service = context.getService(reference);
if (service instanceof HttpService) {
HttpService service = (HttpService)service;
try {
service.registerServlet("/sample", new MyRestServlet(), null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return service;
}
@Override /* ServiceTrackerCustomizer */
public void modifiedService(ServiceReference reference, Object service) {
}
@Override /* ServiceTrackerCustomizer */
public void removedService(ServiceReference reference, Object service) {
}
}