Created
June 2, 2017 16:38
-
-
Save nantunes/de344f6ee2f4500c2100a98a99ff6db9 to your computer and use it in GitHub Desktop.
BundleActivator registering resources
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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