Using Abdera and the Jersey Client API

Marc recently published a short tutorial on how to use Apache Abdera with Apache Abdera with our reference implementation of JAX-RS, Jersey. His code is server side, i.e. it explains using Jersey and Abdera for creating RESTful web services with Atom payload[1]. In this article I will give an example on how the Jersey client API can be used to consume such a service with realitve ease.

It is hopefully known that Jersey contains a very simple, yet effective HTTP client API. Core to it is the heavy use of the builder pattern for creating and configuring requests. For our example, I start with creating the client:

  Client c = Client.create();

  WebResource r = c.resource(new URI(someLocation));

We can now get the InputStream from the WebResource to read the Atom feed into an Abdera Feed:

  InputStream is = (InputStream) r.get(InputStream.class);

  Document<Feed> doc = Abdera.getNewParser().parse(is);
  Feed feed = doc.getRoot();

  for (Entry entry : feed.getEntries()) {

doSomething(entry);
}

Now let's say we want to post an entry to the resource in Marc's article. In this case we would also have to use his AbderaSupport class, which implementes the proper MessageBodyReader and MessageBodyWriter interfaces for the Abdera objects. On the server side providing these interfaces is enough, but on the client side we need to configure the Jersey client. The following code helps doing this:

  public static class AbderaClientConfig extends DefaultClientConfig {

      @Override

      public Set<Class<?>> getProviderClasses() {

          Set<Class<?>> classes = new HashSet<Class<?>>();
          classes.add(AbderaSupport.class);
          return classes;
      }
  }

Thus completing our sample app: 
  ClientConfig cf = new AbderaClientConfig();

  Client c = Client.create(cf);

  WebResource r = c.resource(new URI(someLocation));
  
  Entry entry = AbderaSupport.getAbdera().newEntry(); 
  entry.setTitle(...); 
  entry.setContent(...);          
            
  ClientResponse cr = r.type(MediaType.APPLICATION_XML).put(ClientResponse.class, entry);  
Done.

tags:

[1] Tim pointed out that this style should properly called "AtomPub", and not APP, AtomPub/Sub or similar.

Comments:

Post a Comment:
Comments are closed for this entry.
About

beuchelt

Search

Categories
Archives
« September 2015
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today