Sunday, January 2, 2011

Java Open Data Protocol API

Recently, I have played with Open Data Protocol (OData) using Java and I am not entirely happy with the API’s that I have had to use.  So, in true developer style I am going to attempt to write my own.  Have called it JOCU (Java OData Consuming Utility). I figure that by doing this I will learn the OData Protocol, touch up on my Java coding, practice TDD and JUnit, and maybe play with GIT or some other source control.

Open Data Protocol

Now for some understanding.  The Open Data Protocol was put together by various organisations to surface data in a consistent way that was manageable cross platform.  It allows for updating and retrieving of data to the data store via the URI conventions.  I wont go into it in detail cause I am likely to get it wrong, and that isn't the idea of this post.  For more information, go to http://www.odata.org/.

So, on with the show… my first hurtle

I have started the API and have already come across something worth noting down.  I had written a function to get the source code for a file, called GetSource.  The original code is below:

public String GetSource(String URIForSource) throws  MalformedURLException, IOException  {

URL url = new URL(URIForSource);
HttpURLConnection URLConn = (HttpURLConnection)url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(URLConn.getInputStream()));

String str;
String result = "";
while ((str = in.readLine()) != null)
result = result + str;
in.close();
return result;
}

Now for HTML files and for static XML files this is fine.  However, when you use this for an OData source, it dies (returns a 400 Bad Request error).  I then thought that there was something wrong with my URL so I copied it into a browser and it worked!  I was left with the question: why would the URL work in a browser yet not in code?  After some investigating, I found that I needed to identify the types of responses that I would accept.  As a result, I added one line to my code and came up with the below:

public String GetSource(String URIForSource) throws  MalformedURLException, IOException  {

URL url = new URL(URIForSource);
HttpURLConnection URLConn = (HttpURLConnection)url.openConnection();
URLConn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
BufferedReader in = new BufferedReader(new InputStreamReader(URLConn.getInputStream()));

String str;
String result = "";
while ((str = in.readLine()) != null)
result = result + str;
in.close();
return result;
}

As you can see in line 5, I set the connection to accept xml, along with other types that I needn’t go into.  As a result, the code is now working perfectly (under what tests I have written to date that is).


Next is to manage the tokens that the XML returns.

No comments:

Post a Comment