Consuming REST services in OSGi the cool way

Consuming REST services in OSGi the cool way

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.

<pre lang="java">
public class Publisher {
  
  public void addConsumerPublisher( ConsumerPublisher publisher ) {
    publisher.publishConsumers( "http://server:port/root", 
                                new Class<?>[] { MyResource.class }, 
                                new Object[] {new CustomProvider() } );
  }
}
</pre>

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 ;).

 

4 Comments
  • dave
    Posted at 1:40 pm, December 4, 2012

    I’m wondering how you created the cool looking chart (consumer.jpg)? Is is handmade or computer based somehow. Thxs

  • Dirk Zander
    Posted at 1:11 pm, December 20, 2012

    Hi Holger,
    is it possible to include the jax-rs-consumer in the jax-rs-connector P2 repo as well?
    Thanks.