The JavaEEIntegrationTestCase deployes two bundles
example-javaee-api
example-javaee-service
and two JavaEE archives
example-javaee-ejb3
example-javaee-servlet
It demonstrates how JavaEE components can access OSGi services.
public void testServletAccess() throws Exception { deployer.deploy(API_DEPLOYMENT_NAME); deployer.deploy(SERVICE_DEPLOYMENT_NAME); deployer.deploy(EJB3_DEPLOYMENT_NAME); deployer.deploy(SERVLET_DEPLOYMENT_NAME); String response = getHttpResponse("/sample/simple?account=kermit&amount=100", 2000); assertEquals("Calling PaymentService: Charged $100.0 to account 'kermit'", response); response = getHttpResponse("/sample/ejb?account=kermit&amount=100", 2000); assertEquals("Calling SimpleStatelessSessionBean: Charged $100.0 to account 'kermit'", response); deployer.undeploy(SERVLET_DEPLOYMENT_NAME); deployer.undeploy(EJB3_DEPLOYMENT_NAME); deployer.undeploy(SERVICE_DEPLOYMENT_NAME); deployer.undeploy(API_DEPLOYMENT_NAME); }
The JavaEE components must declare and explicit dependency on OSGi and the API bundle in order to see the service interface.
JavaArchive archive = ShrinkWrap.create(JavaArchive.class, EJB3_DEPLOYMENT_NAME); archive.addClasses(SimpleStatelessSessionBean.class); archive.setManifest(new Asset() { @Override public InputStream openStream() { ManifestBuilder builder = ManifestBuilder.newInstance(); String osgidep = "org.osgi.core,org.jboss.osgi.framework"; String apidep = ",deployment." + API_DEPLOYMENT_NAME + ":0.0.0"; builder.addManifestHeader("Dependencies", osgidep + apidep); return builder.openStream(); } });
Note, how the API bundles is prefixed with 'deployment' and suffixed with its version in the Dependencies header.
The JavaEE component itself can get the OSGi system BundleContext injected and use it to track the OSGi service it wants to work with.
public class SimpleStatelessSessionBean { @Resource private BundleContext context; private PaymentService service; @PostConstruct public void init() { // Track {@link PaymentService} implementations ServiceTracker tracker = new ServiceTracker(context, PaymentService.class.getName(), null) { @Override public Object addingService(ServiceReference sref) { service = (PaymentService) super.addingService(sref); return service; } @Override public void removedService(ServiceReference sref, Object sinst) { super.removedService(sref, service); service = null; } }; tracker.open(); } public String process(String account, String amount) { if (service == null) { return "PaymentService not available"; } return service.process(account, amount != null ? Float.valueOf(amount) : null); } }