Skip to content

Instantly share code, notes, and snippets.

@nantunes
Created June 2, 2017 16:38
Show Gist options
  • Save nantunes/de344f6ee2f4500c2100a98a99ff6db9 to your computer and use it in GitHub Desktop.
Save nantunes/de344f6ee2f4500c2100a98a99ff6db9 to your computer and use it in GitHub Desktop.
BundleActivator registering resources
package net.nantunes.helloword.one.internal;
import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.http.HttpContext;
import org.osgi.service.http.HttpService;
import org.osgi.service.http.NamespaceException;
import org.osgi.util.tracker.ServiceTracker;
import org.osgi.util.tracker.ServiceTrackerCustomizer;
import java.util.Dictionary;
import java.util.Hashtable;
public final class Activator implements BundleActivator,
ServiceTrackerCustomizer<HttpService, HttpService> {
private BundleContext bundleContext;
private ServiceTracker<HttpService, HttpService> tracker;
/**
* Called when the OSGi framework starts our bundle
*/
public void start( BundleContext bc ) throws Exception {
bundleContext = bc;
tracker = new ServiceTracker<>( bc, HttpService.class, this );
tracker.open();
}
/**
* Called when the OSGi framework stops our bundle
*/
public void stop( BundleContext bc ) throws Exception {
tracker.close();
}
@Override
public HttpService addingService( ServiceReference<HttpService> reference ) {
final HttpService httpService = bundleContext.getService( reference );
if ( httpService != null ) {
// create a default context to share between registrations
final HttpContext httpContext = httpService.createDefaultHttpContext();
// register the hello world servlet
final Dictionary<String, Object> initParams = new Hashtable<>();
initParams.put( "from", "HttpService" );
try {
// register images as resources
httpService.registerResources( "/images-1", "/images", httpContext );
// register alternative alias for images resources
httpService.registerResources( "/alt-images-1", "/images", httpContext );
} catch ( NamespaceException e ) {
e.printStackTrace();
}
}
return httpService;
}
@Override
public void modifiedService( ServiceReference<HttpService> reference, HttpService service ) {
// ignore
}
@Override
public void removedService( ServiceReference<HttpService> reference, HttpService service ) {
try {
service.unregister( "/images-1" );
service.unregister( "/alt-images-1" );
} catch ( Exception ignored ) {
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment