Consuming REST services in OSGi the cool way

November 28, 2012 | 2 min Read

I recently introduced you to the JAX-RS Consumer. If you’ve read that post you might remember that I promised to write about the OSGi integration of the consumer. This is the topic of this short post.

As you might know, a while ago I created the OSGI-JAX-RS connector. This connector gives you the opportunity to publish your @Path/@Provider resources by registering them as OSGi services. So, why not consume a REST service as an OSGi service? That’s exactly what the JAX-RS Consumer OSGi integration provides. It registers an OSGi service called ConsumerPublisher. Using this service you can publish your @Path interfaces. The ConsumerPublisher creates consumer objects out of them and registers them as OSGi services. Afterwards you will be able to consume them as you do with all other OSGi services.

This is best explained with a small example. Let’s say we are using Declarative Services. So, this gives us the option to register a component and inject the ConsumerPublisher as in the code below.

public class Publisher {
  
  public void addConsumerPublisher( ConsumerPublisher publisher ) {
    publisher.publishConsumers( "https://server:port/root", 
                                new Class[] { MyResource.class }, 
                                new Object[] {new CustomProvider() } );
  }
}

When the JAX-RS consumer bundle is started, the ConsumerPublisher service will be registered and is injected into our component. What we have to do additionally, is to add a base url, our @Path interfaces and the custom @Providers we want to use. The ConsumerPublisher takes care of creating the consumer objects out of the interfaces and registers them as OSGi services. In this example we can afterwards get/call a service of the type MyResource.

If you would like to try this out yourself I have created a p2 repository containing the consumer and it’s dependencies. A working example can also be found on GitHub. Any feedback is very welcome ;).