Java

An Introduction to Microsoft Azure

Azure is a well known cloud computing service created by Microsoft for building, testing, deploying, and managing applications and services through a global network of Microsoft-managed data centres. It provides software as a service (SAAS),platform as a service and infrastructure as a service and supports many different programming languages, tools and frameworks, including both Microsoft-specific and third-party software and systems.

Storage account in Azure :

After creating an account in azure, user can create a ‘storage account’ in Azure portal.With this storage account, a user gets access to Blob Storage, Table Storage, File Storage, and Queue storage. Let’s explain those just a bit better.

    • Azure Blob Storage

Blob Storage is basically storage for unstructured data that can include pictures, videos, music files, documents etc.Blobs are stored in ‘container’.
Blob Storage service comes with three types of blobs: block blobs, append blobs and page blobs. You can use block blobs for documents, image files, and video file storage. Append blobs are similar to block blobs, but are more often used for append operations like logging. Page blobs are used for objects meant for frequent read-write operations. Blob alos provides functionality of Searching and Indexing.

    • Azure File Storage

File Storage is basically storage for structured data that can include directory structures , files etc. These files are stored in a directory-like structure called a ‘share’.

    • Azure Table Storage

Table storage, as the name indicates, is preferred for tabular data, which is ideal for key-value data storage. Table Storage is massively scalable and extremely easy to use. Like other NoSQL data stores, it is schema-less and accessed via a REST API.

    • Azure Queue Storage

The Queue Storage service is used to exchange messages between components either in the cloud or on-premise. It provides a reliable messaging solution for asynchronous communication between application components, whether they are running in the cloud, on the desktop, on an on-premises server, or on a mobile device.

Interaction of Blob storage with Java :

    • Configure your application to access Blob storage

Add the following import statements to the top of the Java file where you want to use the Azure Storage APIs to access blobs.

 // Include the following imports to use blob APIs.
import com.microsoft.azure.storage.*;
import com.microsoft.azure.storage.blob.*;
    • Set up an Azure Storage connection string

An Azure Storage client uses a storage connection string to store endpoints and credentials for accessing data management services. When running in a client application, you must provide the storage connection string in the following format, using the name of your storage account and the Primary access key for the storage account listed in the Azure portal for the AccountName and AccountKey values. The following example shows how you can declare a static field to hold the connection string.

// Define the connection-string with your values
public static final String storageConnectionString =
"DefaultEndpointsProtocol=http;" +
"AccountName=your_storage_account;" +
"AccountKey=your_storage_account_key";

In an application running within a role in Microsoft Azure, this string can be stored in the service configuration file too. In the code at given link, we provide the account name and key as a input so that same code can run for any user.

    • Create a container

A CloudBlobClient object lets you get reference objects for containers and blobs. The following code creates a CloudBlobClient object.
Every blob in Azure storage must reside in a container. Use the CloudBlobClient object to get a reference to the container you want to use. You can create the container if it doesn’t exist with the createIfNotExists method, which will otherwise return the existing container. By default, the new container is private, so you must specify your storage access key (as you did earlier) to download blobs from this container.


try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Get a reference to a container.
// The container name must be lower case
CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

// Create the container if it does not exist.
container.createIfNotExists();
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();
}

    • Upload a blob into container

To upload a file to a blob, get a container reference and use it to get a blob reference. Once you have a blob reference, you can upload any stream by calling upload on the blob reference. This operation will create the blob.If it doesn’t exist, or overwrite it if it does. The following code sample shows this, and assumes that the container has already been created.


try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

// Define the path to a local file.
final String filePath = "C:\\myimages\\myimage.jpg";

// Create or overwrite the "myimage.jpg" blob with contents from a local file.
CloudBlockBlob blob = container.getBlockBlobReference("myimage.jpg");
File source = new File(filePath);
blob.upload(new FileInputStream(source), source.length());
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();

    •  List the blobs in a container

To list the blobs in a container, first get a container reference like you did to upload a blob. You can use the container’s listBlobs method with a for loop. The following code outputs the Uri of each blob in a container to the console.


try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

// Loop over blobs within the container and output the URI to each of them.
for (ListBlobItem blobItem : container.listBlobs()) {
System.out.println(blobItem.getUri());
}
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();

    • Download a blob

To download blobs, follow the same steps as you did for uploading a blob in order to get a blob reference. In the uploading example, we called upload on the blob object. In the following example, 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.


try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

// Loop through each blob item in the container.
for (ListBlobItem blobItem : container.listBlobs()) {
// If the item is a blob, not a virtual directory.
if (blobItem instanceof CloudBlob) {
// Download the item and save it to a file with the same name.
CloudBlob blob = (CloudBlob) blobItem;
blob.download(new FileOutputStream("C:\\mydownloads\\" + blob.getName()));
}
}
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();
}

    • Delete a blob

To delete a blob, get a blob reference, and call deleteIfExists.


try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

// Retrieve reference to a blob named "myimage.jpg".
CloudBlockBlob blob = container.getBlockBlobReference("myimage.jpg");

// Delete the blob.
blob.deleteIfExists();
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();
}

    • Delete a blob container

Finally, to delete a blob container, get a blob container reference, and call deleteIfExists.


try
{
// Retrieve storage account from connection-string.
CloudStorageAccount storageAccount = CloudStorageAccount.parse(storageConnectionString);

// Create the blob client.
CloudBlobClient blobClient = storageAccount.createCloudBlobClient();

// Retrieve reference to a previously created container.
CloudBlobContainer container = blobClient.getContainerReference("mycontainer");

// Delete the blob container.
container.deleteIfExists();
}
catch (Exception e)
{
// Output the stack trace.
e.printStackTrace();
}

Download sample code from zCon Solutions Github Repo


Written by Vyankatesh Repal, Sr. Software Engg. at zCon Solutions

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s