Azure Storage Services Asynchronously in Java

When performing I/O bound operation, the program should use asynchronous approach.  This is particularly important when you access the Azure storage services.  As of now, Azure managed libraries for .NET and Java do not support asynchronous APIs.  Instead, by using underlying run time’s asynchronous programming approaches along with Azure storage services REST API makes you do I/O bound operations on Azure storage services.

In this post, I explain how to access Azure blob storage services asynchronously in Java.  I have used following libraries:

  • org.apache.commons.codec-1.6.jar (for base64 string encoding)
  • async-http-client-1.7.3.jar (Ning’s Async Http Client library – )
  • log4j-1.2.16.jar and slf4j-*-1.6.4.jar (Logging)

AzureStorage Class

The class “AzureStorage” contains the implementation to create HTTP request object for accessing the Azure RESTful resources.

public class AzureStorage...

// fields
String storageMedium;
String accountName;
byte[] secretKey;
String host;
java.util.regex.Pattern urlAbsolutePathPattern;

AzureStorage(String accountName, String storageMedium, String base64SecretKey)
// public method
Request get(String resourcePath)
// utility method
String createAuthorizationHeader(Request request)

The constructor requires storage account name, storage medium (this is neither Java nor Azure terminology, just identify whether you want to access blob, table or queue) and the primary shared key of the account.  In this post, I just provide simple get() method for GET related Azure storage APIs.  The input to the method is the resource path.  Most the REST API requires authorization which in-turn sign the particular request by shared key.   createAuthorizationHeader() method does this job.

The Ctor

public AzureStorage(String accountName, String storageMedium, String base64SecretKey) {
this.accountName = accountName;
this.storageMedium = storageMedium; = "";
secretKey = Base64.decodeBase64(base64SecretKey);
urlAbsolutePathPattern = Pattern.compile("http(?:s?)://[-a-z0-9.]+/([-a-z0-9]*)/\\?.*");

The host field contains the part of base Azure storage URL.  The primary shared key for the account has been converted to base 64 decoded byte array.  Since, there is no AbsolutePath facility from an URL in Java world, I have used regular expression here.  For example, the absolute path of the URL “” is “acontainer”.

The get() method

A HTTP request should be made to access a Azure storage with following details:

x-ms-version: 2009-09-19
x-ms-date: Fri, 20 Apr 2012 11:12:05 GMT
Authorization: SharedKey myaccount:9S/gs8jkAQKAN1Gp/y82B8jHR2r7HShZSiPdl2JSWQw=

The above request specifies the URL for the resource, the REST API version, the request time stamp, authorization header.  The get() method here frames these request headers.  To want to know the complete details of request and response of Azure REST API, visit

public Request get(String resourcePath) {
String RFC1123_PATTERN = "EEE, dd MMM yyyy HH:mm:ss z";
DateFormat rfc1123Format = new SimpleDateFormat(RFC1123_PATTERN);

// remaining code

The rfc1123Format is used to send request time stamp in RFC 1123 format as shown in the HTTP request.  The below code snippet creates the com.ning.http.client.Request object.

String url = "https://" + this.accountName + "." +
this.storageMedium + "." + + "/" + resourcePath;

RequestBuilder builder = new RequestBuilder("GET");

Request request = builder.setUrl(url)
.addHeader("content-type", "text/plain")
.addHeader("content-length", "0")
.addHeader(HeaderDate, rfc1123Format.format(new Date()))
.addHeader(HeaderPrefixMS + "version", "2009-09-19")

The below code creates signed Authorization header.

String authHeader = "";

try {
authHeader = createAuthorizationHeader(request);
} catch (InvalidKeyException e) {
// TODO Auto-generated catch block
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block

request.getHeaders().add("Authorization", "SharedKey " + this.accountName
+ ":" + authHeader);
return request;

This part in-turn calls method createAuthorizationHeader().

The createAuthorizationHeader() method

private String createAuthorizationHeader(Request request)
throws UnsupportedEncodingException,
NoSuchAlgorithmException, InvalidKeyException {

FluentCaseInsensitiveStringsMap headers = request.getHeaders();

StringBuffer stringToSign = new StringBuffer();
stringToSign.append(request.getMethod() + "\n");
stringToSign.append(headers.get("content-type").get(0) + "\n");

// remaining code part

The authorization header should be like

Authorization="[SharedKey|SharedKeyLite] :"

The createAuthorizationHeader() method mainly creates the “” string. The “Signature” is a HMAC-SHA256 based computed hash of the following content:

GET\n /*HTTP Verb*/
\n    /*Content-Encoding*/
\n    /*Content-Language*/
\n    /*Content-Length*/
\n    /*Content-MD5*/
\n    /*Content-Type*/
\n    /*Date*/
\n    /*If-Modified-Since */
\n    /*If-Match*/
\n    /*If-None-Match*/
\n    /*If-Unmodified-Since*/
\n    /*Range*/
x-ms-date:Sun, 11 Oct 2009 21:49:13 GMT\nx-ms-version:2009-09-19\n    /*CanonicalizedHeaders*/
/myaccount/myaccount/acontainer\ncomp:metadata\nrestype:container\ntimeout:20    /*CanonicalizedResource*/

For more details about this, visit:
The above Java code adds the string starting from GET to Range. For this demonstration, I skipped most of the headers with newline and added only content-length and content-type headers. The below code constructs the CanonicalizedHeaders.

List httpStorageHeaderNameArray = new ArrayList();

for(String key : headers.keySet()) {
if(key.toLowerCase().startsWith(HeaderPrefixMS)) {

for(String key : httpStorageHeaderNameArray) {
stringToSign.append(key + ":" + headers.get(key).get(0) + "\n");

The below code constructs the CanonicalizedResource.

java.util.regex.Matcher matcher = urlAbsolutePathPattern.matcher(request.getUrl());
String absolutePath = "";

if(matcher.find()) {
absolutePath =;
}else {
throw new IllegalArgumentException("resourcePath");
stringToSign.append("/" + this.accountName + "/" + absolutePath);
if(absolutePath.length() > 0) stringToSign.append("/");


List paramsArray = new ArrayList();
for(String key : request.getQueryParams().keySet()) {
for(String key : paramsArray) {
stringToSign.append(key + ":" + request.getQueryParams().get(key).get(0) + "\n");

Finally, the whole string should be signed with by the shared key.

byte[] dataToMac = stringToSign.substring(0, stringToSign.length() -1).getBytes("UTF-8");

SecretKeySpec signingKey = new SecretKeySpec(secretKey, "HmacSHA256");
Mac hmacSha256 = Mac.getInstance("HmacSHA256");
byte[] rawMac = hmacSha256.doFinal(dataToMac);
return Base64.encodeBase64String(rawMac);

The Calling Side

At the calling end, when you invoke the get() method, it returns the com.ning.http.client.Request instance.  You can make request asynchronously using Ning’s async library as shown below

AzureStorage blobStorage = new AzureStorage("account-name", "blob|table|queue", "sharedkey");
Request request = blobStorage.get("ablobcontainer/?restype=container&comp=list");
AsyncHttpClient client = new AsyncHttpClient();
ListenableFuture response = client.executeRequest(request, new AsyncHandler() {
        private final Response.ResponseBuilder builder = new Response.ResponseBuilder();

    public STATE onBodyPartReceived(final HttpResponseBodyPart content) throws Exception {
        return STATE.CONTINUE;

    public STATE onStatusReceived(final HttpResponseStatus status) throws Exception {
        return STATE.CONTINUE;

    public STATE onHeadersReceived(final HttpResponseHeaders headers) throws Exception {
        return STATE.CONTINUE;

    public Response onCompleted() throws Exception {

        public void onThrowable(Throwable arg0) {
                // TODO Auto-generated method stub


Visit for more details about the above code. After that, you can do other computations. When you reach the place where you want the response for the asynchronous request, you can do the following:

// till here, there are other interesting computation done

while(! response.isDone()) {
        if(response.isCancelled()) break;

Response actualResponse;
try {
        actualResponse = response.get();


} catch (InterruptedException e) {
        // TODO Auto-generated catch block
} catch (ExecutionException e) {
        // TODO Auto-generated catch block

The “while” part just wait for the asynchronous operation to be completed. After that, it processes the com.ning.http.client.Response instance.

You can download the complete example from

Mark this!
  • Digg
  • Add to favorites
  • RSS