Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
Copyright (C) 2013-2014 Dell, Inc ==================================================================== Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ====================================================================
  
  
  package org.dasein.cloud.azure;
  
  import org.w3c.dom.Node;
  import  javax.annotation.Nonnull;
  import  javax.annotation.Nullable;
  import javax.crypto.Mac;
  
  import java.io.File;
  import java.net.URI;
  import java.util.Date;
  import java.util.HashMap;
  import java.util.Map;
  import java.util.TreeMap;
  import java.util.TreeSet;

Handles connectivity to Microsoft Azure Storage services.

Author(s):
George Reese (george.reese@imaginary.com)
Qunying Huang (qunying.huang@enstratus.com)
Danielle Mayne (danielle.mayne@enstratius.com)
Version:
2013.04.1
Since:
2012.07.1
 
 public class AzureStorageMethod {
     static private final Logger logger = Azure.getLogger(AzureStorageMethod.class);
     static private final Logger wire = Azure.getWireLogger(AzureStorageMethod.class);
 
     static public final String VERSION = "2009-09-19";
     //static public final String VERSION = "2012-02-12";
 
     private String Header_Prefix_MS = "x-ms-";
     
     public static final String  Storage_OPERATION_DELETE = "DELETE";
     public static final String  Storage_OPERATION_PUT = "PUT";
     public static final String  Storage_OPERATION_GET = "GET";
 
     private Azure  provider;
 
     public AzureStorageMethod(Azure azurethrows AzureConfigException {
          = azure;
         ProviderContext ctx = .getContext();
         
         ifctx == null ) {
             throw new AzureConfigException("No context was provided for this request");
         }        
     }
 
     private void fetchKeys() throws CloudExceptionInternalException {
         ProviderContext ctx = .getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was set for this request");
         }
 
         ifctx.getStoragePrivate() == null ) {
             AzureMethod method = new AzureMethod();
 
             String storageService = .getStorageService();
             ifstorageService == null || storageService.isEmpty()) {
                 throw new CloudException("Unable to find storage service in the current region: " + ctx.getRegionId());
             }
 
             Document doc = method.getAsXML(ctx.getAccountNumber(), "/services/storageservices/" + storageService + "/keys");
 
             ifdoc == null ) {
                 throw new CloudException("Unable to identify the storage keys for this account");
             }
             NodeList keys = doc.getElementsByTagName("StorageServiceKeys");
 
             forint i=0; i<keys.getLength(); i++ ) {
                 Node key = keys.item(i);
 
                 ifkey.getNodeName().equalsIgnoreCase("StorageServiceKeys") && key.hasChildNodes() ) {
                     NodeList parts = key.getChildNodes();
                     String p = nulls = null;
 
                     forint j=0; j<parts.getLength(); j++ ) {
                         Node part = parts.item(j);
 
                         ifpart.getNodeName().equalsIgnoreCase("primary") && part.hasChildNodes() ) {
                             p = part.getFirstChild().getNodeValue().trim();
                         }
                         else ifpart.getNodeName().equalsIgnoreCase("secondary") && part.hasChildNodes() ) {
                             s = part.getFirstChild().getNodeValue().trim();
                         }
                     }
                     ifp != null ) {
                         try {
                             ctx.setStoragePrivate(p.getBytes("utf-8"));
                         }
                         catchUnsupportedEncodingException e ) {
                             .error("UTF-8 not supported: " + e.getMessage());
                             throw new InternalException(e);
                         }
                         break;
                     }
                     else ifs != null ) {
                         try {
                             ctx.setStoragePrivate(s.getBytes("utf-8"));
                         }
                         catchUnsupportedEncodingException e ) {
                             .error("UTF-8 not supported: " + e.getMessage());
                             throw new InternalException(e);
                         }
                         break;
                     }
                 }
             }
         }
     }
 
     private String getStorageAccount() throws CloudExceptionInternalException {
         return .getStorageService();
     }
 
     private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method, @Nonnull Map<StringStringqueryParamsthrows  CloudExceptionInternalException {
         fetchKeys();
 
         ProviderContext ctx = .getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was specified for this request");
         }
         Header h = method.getFirstHeader("content-type");
         String contentType = (h == null ? null : h.getValue());
 
         ifcontentType == null ) {
             contentType = "";
         }
         StringBuilder stringToSign = new StringBuilder();
 
         stringToSign.append(method.getMethod().toUpperCase()).append("\n");
         stringToSign.append("\n"); // content-md5
         stringToSign.append(contentType).append("\n");
         stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");
 
         Header[] headers = method.getAllHeaders();
         TreeSet<Stringkeys = new TreeSet<String>();
 
         forHeader header  : headers ) {
             ifheader.getName().startsWith() ) {
                 keys.add(header.getName().toLowerCase());
             }
         }
 
         forString key : keys ) {
             Header header = method.getFirstHeader(key);
 
             ifheader != null ) {
                 Header[] all = method.getHeaders(key);
 
                 stringToSign.append(key.toLowerCase().trim()).append(":");
                 ifall != null && all.length > 0 ) {
                     forHeader current : all ) {
                         String v = (current.getValue() != null ? current.getValue() : "");
 
                         stringToSign.append(v.trim().replaceAll("\n"" ")).append(",");
                     }
                 }
                 stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
             }
             else {
                 stringToSign.append(key.toLowerCase().trim()).append(":");
             }
             stringToSign.append("\n");
         }
 
         stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());
 
         keys.clear();
         forString key : queryParams.keySet() ) {
             ifkey.equalsIgnoreCase("comp") ) {
                 key = key.toLowerCase();
                 keys.add(key);
             }
         }
         if( !keys.isEmpty() ) {
             stringToSign.append("?");
             forString key : keys ) {
                 String value = queryParams.get(key);
 
                 ifvalue == null ) {
                     value = "";
                 }
                 stringToSign.append(key).append("=").append(value).append("&");
             }
             stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
         }
         try {
             if.isDebugEnabled() ) {
                 .debug("BEGIN STRING TO SIGN");
                 .debug(stringToSign.toString());
                 .debug("END STRING TO SIGN");
             }
             Mac mac = Mac.getInstance("HmacSHA256");
             mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));
 
             String signature = new String(Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));
 
             if.isDebugEnabled() ) {
                 .debug("signature=" + signature);
             }
             return signature;
         }
         catchUnsupportedEncodingException e ) {
             .error("UTF-8 not supported: " + e.getMessage());
             throw new InternalException(e);
         }
         catchNoSuchAlgorithmException e ) {
             .error("No such algorithm: " + e.getMessage());
             throw new InternalException(e);
         }
         catchInvalidKeyException e ) {
             .error("Invalid key: " + e.getMessage());
             throw new InternalException(e);
         }
     }
 
     public static Document createDoc() throws InternalException{
 		try {
 			return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
 		} catch (ParserConfigurationException e) {
 			throw new InternalException(e);
 		}		
 	}

Convert a xml document to string
 
 	@SuppressWarnings("unused")
 	public static String convertDomToStringDocument doc)  throws CloudExceptionInternalException{
 		try {
 			 if(doc == nullreturn null;
 			 StringWriter stw = new StringWriter();
 	         Transformer serializer = TransformerFactory.newInstance().newTransformer();
 	         serializer.transform(new DOMSource(doc), new StreamResult(stw));
 	        if(stw != null){
 	        	return stw.toString();
 	        }
 	        return null;
 			throw new InternalException(e);
 			throw new InternalException(e);
 		} catch (TransformerException e) {
 			throw new InternalException(e);
 		}
 	}
 	
 	@SuppressWarnings("deprecation")
 	public Document getAsDoc(@Nonnull String httpVerb, @Nonnull String resource, @Nullable Map<StringStringqueries, @Nullable String body, @Nullable Map<StringStringheaderMapboolean authorizationthrows CloudExceptionInternalException {
         if.isTraceEnabled() ) {
             .trace("enter - " + AzureStorageMethod.class.getName() + "." + httpVerb + "(" + getStorageAccount() + "," + resource + ")");
         }
         String endpoint =getStorageEnpoint();
 
         if.isDebugEnabled() ) {
             .debug(httpVerb + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource);
             .debug("");
         }
         try {
             HttpClient client =  getClient();
 
             ifheaderMap == null ) {
                 headerMap = new HashMap<String,String>();
             }
 
             HttpRequestBase method = getMethod(httpVerbbuildUrl(resourcequeries), queriesheaderMapauthorization);
 
             if.isDebugEnabled() ) {
                 .debug(method.getRequestLine().toString());
                 forHeader header : method.getAllHeaders() ) {
                     .debug(header.getName() + ": " + header.getValue());
                 }
                 .debug("");
                 ifbody != null ) {
                     .debug(body);
                     .debug("");
                 }
             }
             
             // If it is post or put
             if(method instanceof HttpEntityEnclosingRequestBase ){
             	
             	HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBasemethod;
             	
 	            if (body != null) {
 					entityEnclosingMethod.setEntity(new StringEntity(body"application/xml""utf-8"));
 	            }           	
             }           
           
             HttpResponse response ;
             StatusLine status;
             
             try {
                 response = client.execute(method);
                 status = response.getStatusLine();
             }
             catchIOException e ) {
                 .error("GET(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                 if.isTraceEnabled() ) {
                     e.printStackTrace();
                 }
                 throw new CloudException(e);
             }
             if.isDebugEnabled() ) {
                 .debug("GET(): HTTP Status " + status);
             }
             Header[] headers = response.getAllHeaders();
             if.isDebugEnabled() ) {
                 .debug(status.toString());
                 forHeader h : headers ) {
                     ifh.getValue() != null ) {
                         .debug(h.getName() + ": " + h.getValue().trim());
                     }
                     else {
                         .debug(h.getName() + ":");
                     }
                 }
                 .debug("");
             }
             
             ifstatus.getStatusCode() == . ) {
                 return null;
             }
             ifstatus.getStatusCode() != . && status.getStatusCode() != . ) {
                 .error(httpVerb + "(): Expected OK for " + httpVerb + "request, got " + status.getStatusCode());
                 
                 HttpEntity entity = response.getEntity();
                 String result;
                                
                 ifentity == null ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                 }
                 try {
                 	result = EntityUtils.toString(entity);           
                 }
                 catchIOException e ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                 }
                 if.isDebugEnabled() ) {
                     .debug(result);
                 }
                 .debug("");
                 AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result);
 
                 ifitems == null ) {
                     return null;
                 }
 
                 .error(httpVerb + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                 throw new AzureException(items);
             }
             else {
 
                 HttpEntity entity = response.getEntity();
 
                 ifentity == null ) {
                     return null;
                 }
                 InputStream input;
 
                 try {                	
                     input = entity.getContent();
                 }
                 catchIOException e ) {
                     .error(httpVerb + "(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
                     if.isTraceEnabled() ) {
                         e.printStackTrace();
                     }
                     throw new CloudException(e);
                 }
                 return parseResponse(inputtrue);
             }
         } catch (UnsupportedEncodingException e) {			
         	throw new CloudException(e);
 		}
         finally {
             if.isTraceEnabled() ) {
                 .trace("exit - " + AzureMethod.class.getName() + ".getStream()");
             }
             if.isDebugEnabled() ) {
                 .debug("");
                 .debug("--------------------------------------------------------> " );
             }
         } 
 	}
 	       
 	
 	
     public @Nullable InputStream getAsStream(@Nonnull String strMethod, @Nonnull String resource, @Nonnull Map<StringStringqueries, @Nullable String body,  @Nullable Map<StringStringheaderMapboolean authorizationthrows CloudExceptionInternalException {
         if.isTraceEnabled() ) {
             .trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")");
         }
         String endpoint = getStorageEnpoint();
         if.isDebugEnabled() ) {
             .debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource);
             .debug("");
         }
         try {
 
             HttpClient client =  getClient();
             
             String contentLength = null;
             if(body != null){        	
             	contentLength = String.valueOf(body.length());            	
             }else{
             	contentLength = "0";        	
             }
 
             HttpRequestBase method = getMethod(strMethodbuildUrl(resourcequeries),queriesheaderMapauthorization);
   
             if.isDebugEnabled() ) {
                 .debug(method.getRequestLine().toString());
                 forHeader header : method.getAllHeaders() ) {
                     .debug(header.getName() + ": " + header.getValue());
                 }
                 .debug("");
                 ifbody != null ) {
                     .debug(body);
                     .debug("");
                 }
             }
             
             // If it is post or put
             if(method instanceof HttpEntityEnclosingRequestBase ){
             	
             	HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBasemethod;
             	
 	            if (body != null) {
 					entityEnclosingMethod.setEntity(new StringEntity(body"application/xml""utf-8"));
 	            }            	
             }           
           
             HttpResponse response ;
             StatusLine status;
             
             try {
                 response = client.execute(method);
                 status = response.getStatusLine();
             }
             catchIOException e ) {
                 .error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                 if.isTraceEnabled() ) {
                     e.printStackTrace();
                 }
                 throw new CloudException(e);
             }
             if.isDebugEnabled() ) {
                 .debug("post(): HTTP Status " + status);
             }
             Header[] headers = response.getAllHeaders();
   
             if.isDebugEnabled() ) {
                 .debug(status.toString());
                 forHeader h : headers ) {
                     ifh.getValue() != null ) {
                         .debug(h.getName() + ": " + h.getValue().trim());
                     }
                     else {
                         .debug(h.getName() + ":");
                     }
                 }
                 .debug("");
             }
             
             ifstatus.getStatusCode() == . ) {
                 return null;
             }
             ifstatus.getStatusCode() != . && status.getStatusCode() != . ) {
                 .error(strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode());
                 
                 HttpEntity entity = response.getEntity();
                 String result;
                                
                 ifentity == null ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                 }
                 try {
                 	result = EntityUtils.toString(entity);                
           }
                 catchIOException e ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                 }
                 if.isDebugEnabled() ) {
                     .debug(result);
                 }
                 .debug("");
                 AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result);
 
                 ifitems == null ) {
                     return null;
                 }
                 
                 .error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                 throw new AzureException(items);
             }
             else {
 
                 HttpEntity entity = response.getEntity();
 
                 ifentity == null ) {
                     return null;
                 }
                 InputStream input;
 
                 try {                	
                     input = entity.getContent();
                 }
                 catchIOException e ) {
                     .error(strMethod + "(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
                     if.isTraceEnabled() ) {
                         e.printStackTrace();
                     }
                     throw new CloudException(e);
                 }
                 return input;
             }
         } catch (UnsupportedEncodingException e) {			
         	throw new CloudException(e);
 		}
         finally {
             if.isTraceEnabled() ) {
                 .trace("exit - " + AzureMethod.class.getName() + ".getStream()");
             }
             if.isDebugEnabled() ) {
                 .debug("");
                 .debug("--------------------------------------------------------> " );
             }
         } 
     }
 
     protected @Nonnull HttpClient getClient() throws InternalExceptionCloudException {
         ProviderContext ctx = .getContext();
 
         ifctx == null ) {
             throw new AzureConfigException("No context was defined for this request");
         }
         String endpoint = getStorageEnpoint();
         boolean ssl = endpoint.startsWith("https");
         int targetPort;
 
         try {
         	
             URI uri = new URI(endpoint);
             targetPort = uri.getPort();
             
             iftargetPort < 1 ) {
                 targetPort = (ssl ? 443 : 80);
             }
         }
         catchURISyntaxException e ) {
             throw new AzureConfigException(e);
         }
         HttpParams params = new BasicHttpParams();
    
         HttpProtocolParams.setVersion(params.);
        
         HttpProtocolParams.setContentCharset(params.);
         
         Properties p = ctx.getCustomProperties();
 
         ifp != null ) {
             String proxyHost = p.getProperty("proxyHost");
             String proxyPort = p.getProperty("proxyPort");
 
             ifproxyHost != null ) {
                 int port = 0;
 
                 ifproxyPort != null && proxyPort.length() > 0 ) {
                     port = Integer.parseInt(proxyPort);
                 }
                 params.setParameter(.new HttpHost(proxyHostportssl ? "https" : "http"));
             }
         }
         return new DefaultHttpClient (params);
         
     }
 
 
     public @Nonnull Document parseResponse(@Nonnull String responseBodyboolean withWireLoggingthrows CloudExceptionInternalException {
         try {
             if != null && .isDebugEnabled() ) {
                 String[] lines = responseBody.split("\n");
 
                 iflines.length < 1 ) {
                     lines = new String[] { responseBody };
                 }
                 forString l : lines ) {
                     .debug(l);
                 }
                 .debug("");
             }
             ByteArrayInputStream bas = new ByteArrayInputStream(responseBody.getBytes());
 
             DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
             DocumentBuilder parser = factory.newDocumentBuilder();
             Document doc = parser.parse(bas);
 
             bas.close();
             return doc;
         }
         catchIOException e ) {
             throw new CloudException(e);
         }
         catchParserConfigurationException e ) {
             throw new CloudException(e);
         }
         catchSAXException e ) {
             throw new CloudException(e);
         }
     }
     
     public @Nonnull Document parseResponse(@Nonnull InputStream responseBodyAsStreamboolean withWireLoggingthrows CloudExceptionInternalException {
         try {
             BufferedReader in = new BufferedReader(new InputStreamReader(responseBodyAsStream"UTF-8"));
             StringBuilder sb = new StringBuilder();
             String line;
 
             while( (line = in.readLine()) != null ) {
                 sb.append(line);
                 sb.append("\n");
             }
             in.close();          
             // The response may start with ? instead of <
             String strResponsesb.toString();
                            
             int index = strResponse.indexOf("<");
             
             if(index > 0){
             	return parseResponse(strResponse.substring(index), withWireLogging);
             }else{
             	return parseResponse(strResponsewithWireLogging);
             }
             
         }
         catchIOException e ) {
             throw new CloudException(e);
         }
     }
     
 	public String buildUrl(String resourceMap<StringStringqueriesthrows InternalExceptionCloudException {
         String endpoint = getStorageEnpoint();
 
         StringBuilder str = new StringBuilder();       
         str.append(endpoint);
         
         if(!endpoint.endsWith("/")){
         	str.append("/");
         }
         if(resource != null && !resource.equalsIgnoreCase("null")){
         	str.append(resource);	
         }        
     
         if(queries != null && queries.size() > 0 ){
         	str.append("?");
         }
         
         boolean firstPara = true;
         if(queries != null){
         	//comp key should be put first
         	ifqueries.containsKey("comp")){
     		    str.append("comp");
                 str.append("=");
                 str.append(queries.get("comp"));
                 firstPara = false;
         	}
         	
             for(String keyqueries.keySet()){
             	ifkey.equals("comp")) continue;
             	
             	if(firstPara ){ 
         		    str.append(key);
                     str.append("=");
                     str.append(queries.get(key));
                     firstPara = false;
         		}else{
     			   str.append("&");
     			   str.append(key);
                    str.append("=");
                    str.append(queries.get(key));
         		}
         	}            
         } 
         return str.toString();        
     }
 	
 	
     public String getBlobProperty(@Nonnull String strMethod, @Nonnull String resource, @Nonnull Map<StringStringqueriesString body, @Nullable Map<StringStringheaderMapboolean authorizationString propertyNamethrows CloudExceptionInternalException {
         if.isTraceEnabled() ) {
             .trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")");
         }
         String endpoint = getStorageEnpoint();
 
         if.isDebugEnabled() ) {
             .debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource);
             .debug("");
         }
         try {
 
             HttpClient client =  getClient();
 
             ifheaderMap == null ) {
                 headerMap = new HashMap<StringString>();
             }
 
             HttpRequestBase method = getMethod(strMethodbuildUrl(resourcequeries), queriesheaderMapauthorization );
      	
             if.isDebugEnabled() ) {
                 .debug(method.getRequestLine().toString());
                 forHeader header : method.getAllHeaders() ) {
                     .debug(header.getName() + ": " + header.getValue());
                 }
                 .debug("");
                 ifbody != null ) {
                     .debug(body);
                     .debug("");
                 }
             }
             
             // If it is post or put
             if(method instanceof HttpEntityEnclosingRequestBase ){
             	
             	HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBasemethod;
             	
 	            if (body != null) {
 					entityEnclosingMethod.setEntity(new StringEntity(body"application/xml""utf-8"));
 	            }           	
             }           
           
             HttpResponse response ;
             StatusLine status;
             
             try {
                 response = client.execute(method);
                 status = response.getStatusLine();
             }
             catchIOException e ) {
                 .error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                 if.isTraceEnabled() ) {
                     e.printStackTrace();
                 }
                 throw new CloudException(e);
             }
             if.isDebugEnabled() ) {
                 .debug("get(): HTTP Status " + status);
             }
 
             if.isDebugEnabled() ) {
                 Header[] headers = response.getAllHeaders();
                 .debug(status.toString());
                 forHeader h : headers ) {
                     ifh.getValue() != null ) {
                         .debug(h.getName() + ": " + h.getValue().trim());
                     }
                     else {
                         .debug(h.getName() + ":");
                     }
                 }
                 .debug("");
             }
             ifstatus.getStatusCode() == . ) {
                 return null;
             }
             if((status.getStatusCode() != .
             		&& status.getStatusCode() != . 
             		&& status.getStatusCode() != . ) 
             		&& status.getStatusCode() != . ) {
                 .error(strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode());
                 
                 HttpEntity entity = response.getEntity();
                 String result;
                                
                 ifentity == null ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                 }
                 try {
                 	result = EntityUtils.toString(entity);
                 	
                     int index = result.indexOf("<");                    
                     // The result may not be a stardard xml format
                     if(index > 0){
                     	result = result.substring(index);                    	
                     }     
                 }
                 catchIOException e ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                 }
                 if.isDebugEnabled() ) {
                     .debug(result);
                 }
                 .debug("");
                 AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result);
                 .error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                 throw new AzureException(items);
             }
             else{
             	Header header = response.getFirstHeader(propertyName);
             	if(header != null){
             		return header.getValue();          		
             	}else{
             		return null;
             	}
             }
         } catch (UnsupportedEncodingException e) {			
         	throw new CloudException(e);
 		}
         finally {
             if.isTraceEnabled() ) {
                 .trace("exit - " + AzureMethod.class.getName() + ".getStream()");
             }
             if.isDebugEnabled() ) {
                 .debug("");
                 .debug("--------------------------------------------------------> " );
             }
         } 
     }
     
     public void invoke(@Nonnull String strMethod, @Nonnull String resource, @Nonnull Map<StringStringqueries, @Nullable String body, @Nullable Map<StringStringheaderMapboolean authorizationthrows CloudExceptionInternalException {
         if.isTraceEnabled() ) {
             .trace("enter - " + AzureStorageMethod.class.getName() + "." + strMethod + "(" + getStorageAccount() + "," + resource + ")");
         }
         String endpoint = getStorageEnpoint();
 
         if.isDebugEnabled() ) {
             .debug(strMethod + "--------------------------------------------------------> " + endpoint + getStorageAccount() + resource);
             .debug("");
         }
         try {
             HttpClient client =  getClient();
             
             ifheaderMap == null ) {
                 headerMap = new HashMap<StringString>();
             }
 
             HttpRequestBase method = getMethod(strMethodbuildUrl(resourcequeries), queriesheaderMapauthorization );
      	
             if.isDebugEnabled() ) {
                 .debug(method.getRequestLine().toString());
                 forHeader header : method.getAllHeaders() ) {
                     .debug(header.getName() + ": " + header.getValue());
                 }
                 .debug("");
                 ifbody != null ) {
                     .debug(body);
                     .debug("");
                 }
             }
             
             // If it is post or put
             if(method instanceof HttpEntityEnclosingRequestBase ){
             	
             	HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBasemethod;
             	
 	            if (body != null) {
 					entityEnclosingMethod.setEntity(new StringEntity(body"application/xml""utf-8"));
 	            }           	
             }           
           
             HttpResponse response ;
             StatusLine status;
             
             try {
                 response = client.execute(method);
                 status = response.getStatusLine();
             }
             catchIOException e ) {
                 .error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                 if.isTraceEnabled() ) {
                     e.printStackTrace();
                 }
                 throw new CloudException(e);
             }
             if.isDebugEnabled() ) {
                 .debug("post(): HTTP Status " + status);
             }
             Header[] headers = response.getAllHeaders();
         
             if.isDebugEnabled() ) {
                 .debug(status.toString());
                 forHeader h : headers ) {
                     ifh.getValue() != null ) {
                         .debug(h.getName() + ": " + h.getValue().trim());
                     }
                     else {
                         .debug(h.getName() + ":");
                     }
                 }
                 .debug("");
             }
  
             if((status.getStatusCode() != .
             		&& status.getStatusCode() != . 
             		&& status.getStatusCode() != . ) 
             		&& status.getStatusCode() != . ) {
                 .error(strMethod + "(): Expected OK for " + strMethod + "request, got " + status.getStatusCode());
                 
                 HttpEntity entity = response.getEntity();
                 String result;
                                
                 ifentity == null ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                 }
                 try {
                 	result = EntityUtils.toString(entity);
                 }
                 catchIOException e ) {
                     throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                 }
                 if.isDebugEnabled() ) {
                     .debug(result);
                 }
                 .debug("");
                 AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), result);
 
                 ifitems != null ) {
                     .error(strMethod + "(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                     throw new AzureException(items);
                 }
                else {
                    throw new AzureException(.status.getStatusCode(), "UnknownError"result);
                }
            }
        } catch (UnsupportedEncodingException e) {			
        	throw new CloudException(e);
        finally {
            if.isTraceEnabled() ) {
                .trace("exit - " + AzureMethod.class.getName() + ".getStream()");