Getting Started With Azure Blob Service Using Grails

08 / Jun / 2016 by Sagar Mal Shankhala 2 comments

Many of you already know about Microsoft Azure, which is a cloud based computing platform infrastructure for deploying, and managing applications and services globally. One of its most useful service is the blob service, which is a service for storing large amounts of unstructured data, whether text or binary data which is easily accessible from anywhere.

After reading this blog, you’ll be able to perform blob operations such as download, upload and list the blobs from the blob container using Microsoft Azure Blob service.

Basic Terms of Blob Service:

Blob: It stands for “Binary Large Object.” Its usage is in database-land, where blob data might be data stored in our database does not confirm to an established data type as defined by the database.

StorageAccount:  A storage account is required to create a blob client and further to perform  various operations on Blob Storage.

Blob Container: A blob container refers of organization of blobs and it is necessary to create and store a blob.The container has its own metadata and properties.

The first step(s) to use Azure’s API involve adding the dependency to your Grails app & use the credentials from your Azure account to connect to the API. Basic steps are outlined below:

 Step 1:   Add Azure SDK jar dependency

The first step is to add the Azure SDK dependency to your project. The Maven link to the dependency is as follows:

http://mvnrepository.com/artifact/com.microsoft.azure/azure-core/0.9.3

If you’re using Gradle, then the dependency declaration in build.gradle is as follows

[code]
dependencies {


compile ‘com.microsoft.azure:azure-core:0.9.3’
compile ‘com.microsoft.azure:azure-storage:4.2.0’


}
[/code]

Step 2:    Get Azure credentials

The next step is to register with an account on Azure so that we can create get the credentials to communicate with Azure’s API. Here is the link  where you can register

https://azure.microsoft.com/en-us/?c=16.17

After the successful registration, you’ll get your account name and key .

Put the “accountName” and “accountKey”  into application.yml or application.groovy

Example:

[code]

cloud:
azure:
credentials:
accessName: "XXXXXXX"
secretkey : "XXXXXXX"


[/code]

Once you’re account is setup and all necessary dependencies have been added to your application, we can move towards the more interesting part. Let’s take a quick look at some code samples that can upload, download and list blob objects in a container. As usual, code samples are written for Grails 3.x projects , but it should work as it is for other SpringBoot based frameworks.

Upload Blob:

Uploading a blob is very simple and is outlined in the following three steps:

   Step 1: Get a container reference and use it to get a blob reference.

   Step 2: Call upload on the blob reference.

   Step 3: Use the blob reference to upload  new blob or overwrite an existing one.

Following is a code sample that will let you upload blob objects:

[java]
def upload() {

  def file = request.getFile(‘filePath’)
  File source = new File(file.originalFilename)
  source.setBytes(file.getBytes());

  try {

      CloudBlobContainer container = getContainer()
      CloudBlockBlob blob = container.getBlockBlobReference(file.originalFilename);
      blob.upload(new FileInputStream(source), source.length());

}

  catch (Exception e) {
      e.printStackTrace();
  }

  forward action: ‘list’
}
[/java]

Connection:

[java]
private String getConnection() {
 return "DefaultEndpointsProtocol=http;" +
          "AccountName=${accountName};" +
          "AccountKey=${accessKey}";

}

private CloudBlobContainer getContainer() {

CloudStorageAccount storageAccount = CloudStorageAccount.parse(getConnection());
  CloudBlobClient blobClient = storageAccount.createCloudBlobClient();
  CloudBlobContainer container = blobClient.getContainerReference("testapp");
  return container

}
[/java]

Download Blob:

Step 1: Get a container reference and use it to get a blob reference.

Step 2: call download to transfer the blob contents to a stream object such as a

FileOutputStream that you can use to persist the blob to a local file.

[java]
def download(String fileName) {

  try {
      CloudBlobContainer container = getContainer()
      for (ListBlobItem blobItem : container.listBlobs()) {
          if (blobItem instanceof CloudBlob) {
              CloudBlob blob = (CloudBlob) blobItem;
              if (blob.getName() == fileName) {
                  blob.download(new FileOutputStream("/home/sagar/Desktop/" + blob.getName()));
                  break
              }
          }
      }
  }
  catch (Exception e) {
      e.printStackTrace();
  }
  forward action: ‘list’
}

[/java]

Lists the Blob:

Step 1: Get a container reference and use it to get a blob reference. 

Step 2: then get  a list blob items from listblobs method of container.

[java]
def list() {
  List uriList = [];
  try {
      CloudBlobContainer container = getContainer()
      for (ListBlobItem blobItem : container.listBlobs()) {
          CloudBlob blob = (CloudBlob) blobItem;
          uriList.add(blob.getName());
      }
  }
  catch (Exception e) {
      e.printStackTrace();
  }
  render view: "blobOperation", model: [uriList: uriList]
}

[/java]

Full Example of Azure Blob Storage Service at :

https://github.com/sagarmal624/AzureBlobStorage.git


FOUND THIS USEFUL? SHARE IT

comments (2)

Leave a Reply

Your email address will not be published. Required fields are marked *