Monday, June 2, 2014

HalBuilder: First steps

My team and I are working on trying to find best Java client to consume Hal REST services. I was trying HalBuilder and took me a time to figure a few tweaks to make the simple example describe in the website to work. Perhaps, I was doing something wrong, but just in case someone is also stuck on that, here's the code:

Maven Dependencies:

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
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-api</artifactId>
 <version>2.2.1</version>
</dependency>
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-core</artifactId>
 <version>3.1.3</version>
</dependency>
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-json</artifactId>
 <version>3.1.3</version>
</dependency>
<dependency>
 <groupId>com.theoryinpractise</groupId>
 <artifactId>halbuilder-standard</artifactId>
 <version>3.0.1</version>
</dependency>
 
<dependency>
  <groupId>com.ning</groupId>
  <artifactId>async-http-client</artifactId>
  <version>1.8.9</version>
</dependency>

Java code:

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
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.concurrent.ExecutionException;
 
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.Response;
import com.theoryinpractise.halbuilder.api.ReadableRepresentation;
import com.theoryinpractise.halbuilder.api.RepresentationFactory;
import com.theoryinpractise.halbuilder.json.JsonRepresentationFactory;
 
public class TestHalBuilderAPI {
  
 public static void main(String[] args) throws InterruptedException, ExecutionException, IOException {
  RepresentationFactory representationFactory = new JsonRepresentationFactory();
  representationFactory.withFlag(RepresentationFactory.PRETTY_PRINT); 
   
  AsyncHttpClient asyncHttpClient = new AsyncHttpClient();
  Response response = asyncHttpClient.prepareGet("http://gotohal.net/restbucks/api").execute().get();
   
  InputStreamReader inputStreamReader = new InputStreamReader(response.getResponseBodyAsStream());
  
  ReadableRepresentation representation = representationFactory.readRepresentation(inputStreamReader);
  String ordersLinkUrl = representation.getLinkByRel("orders").getHref(); 
  System.out.println(ordersLinkUrl); 
  asyncHttpClient.close();
 }
}