Archive for the ‘Java’ Category

Web + API + CORS = Like

June 22, 2012

In my previous post around API driven web application architectures I delved into the need for every web application to have a corresponding API. There is shift in trends around scalable web application development.

Enterprises need “micro applications”  not “monolithic  applications”.

Take a look at Mary Meeker’s latest Internet trends which talks about mobile devices way surpassing PC based access as we step into the latter half of the decade.

Mobile apps need APIs, not UIs. Devices need APIs not UIs.

If you are building an enterprise application, build your API first not your UI. Of couse UI and User experience is really important and you will continue to court users over the web access from PC devices/mobile browsers.

Which comes to the real heart of this post. If your web application and API applications are two (or more ) applications, how do they talk to each other. Let’s look cover the basics before we review our options.

The Protocol: REST…REST…REST

 

This also implies that you should be using JSON for your data exchange and HTTP/HTTPS as your underlying transport mechanism. If your are thinking of XM-Hell, then think again.

The Client: HTML5, Javascript, CSS3

 
HTML5, CSS3, Ajax, Javascript are starting to make a huge comeback. Thanks to the Google(s),Facebook(s),Twitter(s), LinkedIn(s) of the world to popularize the power of client side scripting and the trend that is also know as “single page web apps”.
Note: If you have not read LinkedIn’s tech blog about how they build their iPad app, I would strongly recommend you do.

The options:

 
Ideally you should be able to do a Ajax request (GET, POST, DELETE etc.) over to your API app and it should work. Browsers have prevented this with the “Same origin policy” for JavaScript. This policy is a really good thing as it helps web applications be less prone security hacks that allow arbitrary scripts to be executed as the user. Given this policy, there are three options to get your web application to talk to your API:
  1. Server side Proxy
  2. JSONP
  3. Cross Origin Resource Sharing (CORS)
 
Server side Proxy 
 
This is the most obvious choice and probably what most developers will start with. Here’s how the sequence of events play out with this option:
This is certainly a very good option and is the chosen road for most applications especially when the web app needs to interact with a 3rd party API that the app does not control.  However proxying every request, has performance tradeoffs as well the need to keep the server side code up-to-date with the API versions. In the world of JSON/Ajax type web apps, the server side component is not adding too much value.
 
JSONP
 
Short for JSON with Padding, allows you to inject <script> elements at runtime and invoke a server side URL that returns the JSON data wrapped in a Javascript function. Read more about it here. The flow of events for JSONP is below:
For e.g. say your API end point is http://api.app.com/getSomething, the sequence of events would be:
  1. Your Javascript library (JQuery etc.) would create a new <script> DOM element with “src” attribute set to http://api.app.com/getSomething?callback=javascriptFn
  2. The API will receive a HTTP GET request, process the request and generate the JSON response
  3. Once the response is generated, it will wrap the JSON response around the Javascript function name and return the response setting the Content-Type header value to application/javascript
    The response would be something like this:

    javascriptFn({'responseStr':'Response Value'});

  4. The Browser receives the response and because the content type is set to JavaScript, it will attempt to call the function called javascriptFn passing in the JSON response. The function can now update the DOM/do any processing with the data as it deems fit.
The major downside is because this is all happening over HTTP(S) GET you cannot really pass in HTTP headers (e.g. Auth information) which essentially makes this a very un-secure option. This is a major reason why most IT/ Enterprises shun this approach. JSONP is certainly an option for any public web services that does not give away any user specific secret/authentication credentials.
 
Cross Origin Resource Sharing
 
Cross Origin Resource Sharing (CORS) is a more recent technique that overcomes the downsides of JSONP and provide a more “secure” way for your applications to talk to each other. It is currently a “draft” spec by W3C (http://www.w3.org/TR/cors/). However most modern web browsers have added support for CORS already.  For a good list of support browsers, go to http://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Browser_support
 
Implementing CORS on a server is as simple as sending additional HTTP headers, for example:

Access-Control-Allow-Origin: http://example.com:8080

There are additional headers that can be sent as part of the response. Below are some additional headers:


Access-Control-Allow-Origin
Access-Control-Allow-Credentials
Access-Control-Expose-Headers
Access-Control-Max-Age
Access-Control-Allow-Methods
Access-Control-Allow-Headers

On the client side, you call your API using the standard Ajax / XMLHttpRequest method. For e.g., if you were using JQuery (you should if you are not !!!). The code would look something like this:

function callApi(){
$.get( 'http://api-dot-com.herokuapp.com/apiCall',
{requestParam: 'Parametervalue'},
function(responseJson){
doSomething(responseJson); console.log(d);
}
);
}

The browser when making this Ajax request sends the following header as part of the request:

Origin: http://foo.example

In addition, the client(browser) can send an additional Access-Control-Request-Method and Access-Control-Request-Headers header values for fine grained control on the HTTP Method that is being used to make the request.

The server will receive this header and determine if the Access-Control-Allow-Origin should be sent back with the corresponding value.

Advertisements

Java on the Cloud in 5 minutes

March 16, 2012

Getting started with Java apps on the cloud just got “super easy”. It takes 5 minutes. Check it out at http://www.heroku.com/java.

“So easy even a Ruby Developer can do it”

Heroku for Java Developers

Back when I started doing active web development with Java using Struts, Spring, Spring MVC, i had to :

  • Create a Eclipse project
  • Declare my dependencies (Spring templates when available)
  • Create a local database
  • Build my persistence logic using JPA/Hibernate
  • Build and Test locally

All this and yet not runing on the cloud. If I wanted to share my app with a colleague, I really cannot unless I send them a Zip file of my project or give them my IP address.

Not an easy task !!! Now with the new and improved page on Heroku for Java developers, I can get a Spring MVC template app created and deployed to the cloud and available all in 5 minutes.

Now you can share your app with your colleagues, friends or bosses and focus on what you do best, “building the next big cloud service”.

Heroku also provides 4 getting started templates which covers most “customer engagement” applications that you will be build. It has templates for:

  • Spring MVC-Hibernate on Tomcat
  • Basic Hello World with Embedded Jetty
  • Play! app  (if you want to stay ahead of the next big thing in Java you should check out Play!)
  • RESTful API using JAX-RS and Jersey