Retrieving blob objects from Azure with Apex

Maybe you need to retrieve blobs stored in Azure Storage Services and save them as Salesforce attachments.

Let’s suppose we have an attachment base64 encoded stored as a blob in Azure. We could retrieve it with the following snippet:

String blobName = '';
String urlQueue = 'https://.blob.core.windows.net//' + blobName;

string storageKey = '';

Datetime dt = Datetime.now();
string formattedDate = dt.formatGMT('EEE, dd MMM yyyy HH:mm:ss') + ' GMT';

string stringToSign = 'GET\n' + '\n\n\n\n\n\n\n\n\n\n\n' +'x-ms-date:' + formattedDate + '\nx-ms-version:2015-02-21\n///' + blobName;

String signature = '';
Blob unicodeKey = EncodingUtil.base64Decode(storageKey);
Blob data = Crypto.generateMac('HMACSHA256', Blob.valueOf(stringToSign), unicodeKey);
signature = EncodingUtil.base64Encode(data);

string authHeader = 'SharedKey :' + signature;

HttpRequest req = new HttpRequest();
req.setMethod('GET');

req.setHeader('x-ms-date', formattedDate);
req.setHeader('x-ms-version', '2015-02-21');
req.setHeader('Authorization', authHeader);
req.setHeader('Accept', 'application/atom+xml,application/xml');

req.setEndpoint(urlQueue);

Http http = new Http();

try
{
HTTPResponse res = http.send(req);
// in the response body you have your blob

// Let's save it as attachment
Attachment myAttachment = new Attachment();
myAttachment.body = EncodingUtil.base64Decode(res.getBody());
myAttachment.name = 'my azure blob.pdf';
Case c = [SELECT Id from Case LIMIT 1];
myAttachment.parentId = c.Id;
insert myAttachment;
}
catch (system.CalloutException ce)
{
// please handle exceptions properly :)
system.debug(ce);
}
This request can be used for getting other Azure resource, not just blob's. For example, if you want to get messages from a queue, you only need to change two lines:

String urlQueue = 'https://.queue.core.windows.net//messages';

//.... the rest is the same

string stringToSign = 'GET\n' + '\n\n\n\n\n\n\n\n\n\n\n' +'x-ms-date:' + formattedDate + '\nx-ms-version:2015-02-21\n///messages';

//.... the rest is the same
// example for processing queued messages
try
{
HTTPResponse res = http.send(req);
Dom.Document doc = res.getBodyDocument();
Dom.XMLNode root = doc.getRootElement();

for(Dom.XMLNode message : root.getChildElements()) {
String messageId = message.getChildElement('MessageId', null).getText();
String messageText = EncodingUtil.base64Decode(message.getChildElement('MessageText', null).getText()).toString();
}

}
catch (system.CalloutException ce)
{
system.debug(ce);
}

Leave a Reply

avatar
  Subscribe  
Notify of