Thursday, July 17, 2014

Another way to get an OSGI Reference

The code below will return a ResourceResolver without using an annotation. This will significantly clean up your method signatures in many cases. The only caveat to using this approach is understanding how this command will execute (currently under admin), so if you need to perform an action under a particular user, you will need to pass in additional parameters depending on what you're trying to do.


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import org.osgi.framework.BundleContext;
import org.osgi.framework.FrameworkUtil;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.resource.ResourceResolverFactory;
org.osgi.framework.ServiceReference;

private ResourceResolverFactory factory;

...
private ResourceResolver getResolver() throws LoginException {

//Get the Bundle's context
BundleContext context = FrameworkUtil.getBundle(this.getClass().getBundleContext();
//Set the service reference you want
ServiceReference ref = context.getServiceReference(ResourceResolverFactory.class.getName());
//Retrieve the Service
factory = (ResourceResolverFactory) context.getService(ref);
return factory.getAdministrativeResourceResolver(null);

}
...

No comments:

Post a Comment