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  javax.annotation.Nonnull;
 import  javax.annotation.Nullable;
 import java.io.*;
 import java.net.URI;
Handles connectivity to Microsoft Azure services.

Author(s):
George Reese (george.reese@imaginary.com)
Version:
2012.07 initial version
Since:
2012.07
 
 public class AzureMethod {
     static private final Logger logger = Azure.getLogger(AzureMethod.class);
     static private final Logger wire   = Azure.getWireLogger(AzureMethod.class);
 
     static public class AzureResponse {
         public int httpCode;
         public Object body;
     }
 
     private class HttpProxyConfig
     {
         private String host;
         private Integer port;
 
         public HttpProxyConfig(String hostInteger port)
         {
             this. = host;
             this. = port;
         }
 
         public String getHost() {
             return ;
         }
 
         public Integer getPort() {
             return ;
         }
     }
 
    private String endpoint;
    private Azure provider;
    
    public AzureMethod(Azure azurethrows CloudException {
         = azure;
        ProviderContext ctx = .getContext();
        
        ifctx == null ) {
            throw new AzureConfigException("No context was provided for this request");
        }
         = ctx.getEndpoint();
        if == null ) {
            throw new AzureConfigException("No endpoint was provided for this request");
        }
        if( !.endsWith("/") ) {
             =  + "/";
        }
    }
    public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull String resourcethrows CloudExceptionInternalException {
        try {
            return getAsStream(accountnew URI( + account + resource));
        }
        catchURISyntaxException e ) {
            throw new InternalException("Endpoint misconfiguration (" +  + account + resource + "): " + e.getMessage());
        }
    }
    public @Nullable InputStream getAsStream(@Nonnull String account, @Nonnull URI urithrows CloudExceptionInternalException {
        .trace("enter - " + AzureMethod.class.getName() + ".get(" + account + "," + uri + ")");
        .debug("--------------------------------------------------------> " + uri.toASCIIString());
        try {
            HttpClient client = getClient();
            HttpUriRequest get = new HttpGet(uri);
            if (uri.toString().indexOf("/services/images") > -1) {
                get.addHeader("x-ms-version""2012-08-01");
            }
            else if(uri.toString().contains("/services/vmimages"))
            {
                get.addHeader("x-ms-version""2014-05-01");
            }
            else {
                get.addHeader("x-ms-version""2012-03-01");
            }
            if( != null && .getSendAsHeader()){
               get.addHeader(.getHeaderName(), .getRequestId());
            }
            .debug(get.getRequestLine().toString());
            forHeader header : get.getAllHeaders() ) {
                .debug(header.getName() + ": " + header.getValue());
            }
            HttpResponse response;
            StatusLine status;
            try {
                response = client.execute(get);
                status = response.getStatusLine();
            }
            catchIOException e ) {
                .error("get(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage());
                throw new CloudException(e);
            }
            .debug("get(): HTTP Status " + status);
            Header[] headers = response.getAllHeaders();
            .debug(status.toString());
            forHeader h : headers ) {
                if (h.getValue() != null) {
                    .debug(h.getName() + ": " + h.getValue().trim());
                } else {
                    .debug(h.getName() + ":");
                }
            }
            ifstatus.getStatusCode() == . ) {
                return null;
            }
            ifstatus.getStatusCode() != . && status.getStatusCode() != . ) {
                .error("get(): Expected OK for GET request, got " + status.getStatusCode());
                HttpEntity entity = response.getEntity();
                String body;
                ifentity == null ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                }
                try {
                    body = EntityUtils.toString(entity);
                }
                catchIOException e ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                }
                .debug(body);
                AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);
                ifitems == null ) {
                    return null;
                }
                .error("get(): [" + 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("get(): Failed to read response error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                .debug("---> Binary Data <---");
                return input;
            }
        }
        finally {
            .trace("exit - " + AzureMethod.class.getName() + ".getStream()");
            .debug("--------------------------------------------------------> " + uri.toASCIIString());
        }
    }
    public @Nullable Document getAsXML(@Nonnull String account, @Nonnull String resourcethrows CloudExceptionInternalException {
        try {
            return getAsXML(accountnew URI( + account + resource));
        }
        catchURISyntaxException e ) {
            throw new InternalException("Endpoint misconfiguration (" +  + account + resource + "): " + e.getMessage());
        }
    }
    public @Nullable <T> T get(Class<T> classType, @Nonnull String resourcethrows CloudExceptionInternalException {
        try {
            return this.<T>get(classTypenew URI( + .getContext().getAccountNumber() + resource));
        }
        catchURISyntaxException e ) {
            throw new InternalException("Endpoint misconfiguration (" +  + .getContext().getAccountNumber() + resource + "): " + e.getMessage());
        }
    }
    public @Nullable <T> T get(Class<T> classType, @Nonnull URI urithrows CloudExceptionInternalException{
        InputStream responseAsStream = getAsStream(.getContext().getAccountNumber(), uri);
        if(responseAsStream == null) {
            .info("Unable to perform HTTP GET at following resource: " + uri.toString());
            return null;
        }
        try {
            JAXBContext context = JAXBContext.newInstance(classType);
            Unmarshaller u = context.createUnmarshaller();
            return (T)u.unmarshal(responseAsStream);
        }
        catch(Exception ex)
        {
            .error(ex.getMessage());
            throw new InternalException(ex);
        }
    }
    public <T> String post(String resource, T objectthrows JAXBExceptionCloudExceptionInternalException {
        StringWriter stringWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstance(object.getClass());
        Marshaller m = jc.createMarshaller();
        m.marshal(objectstringWriter);
        return post(.getContext().getAccountNumber(), resourcestringWriter.toString());
    }
    public <T> String put(String resource, T objectthrows JAXBExceptionCloudExceptionInternalException {
        StringWriter stringWriter = new StringWriter();
        JAXBContext jc = JAXBContext.newInstanceobject.getClass());
        Marshaller m = jc.createMarshaller();
        m.marshal(objectstringWriter);
        return invoke("PUT",.getContext().getAccountNumber(), resource,stringWriter.toString());
    }
    public @Nullable Document getAsXML(@Nonnull String account, @Nonnull URI urithrows CloudExceptionInternalException {
        InputStream stream = getAsStream(accounturi);
        if(stream == null)
            return null;
        return parseResponse(streamtrue);
    }
    
    protected @Nonnull HttpClient getClient() throws CloudExceptionInternalException {
        ProviderContext ctx = .getContext();
        ifctx == null ) {
            throw new AzureConfigException("No context was defined for this request");
        }
        String endpoint = ctx.getEndpoint();
        ifendpoint == null ) {
            throw new AzureConfigException("No cloud endpoint was defined");
        }
        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();
        SchemeRegistry registry = new SchemeRegistry();
        try {
            registry.register(new Scheme(ssl ? "https" : "http"targetPortnew AzureSSLSocketFactory(new AzureX509())));
        }
        catchKeyManagementException e ) {
            e.printStackTrace();
            throw new InternalException(e);
        }
        catchUnrecoverableKeyException e ) {
            e.printStackTrace();
            throw new InternalException(e);
        }
        catchNoSuchAlgorithmException e ) {
            e.printStackTrace();
            throw new InternalException(e);
        }
        catchKeyStoreException e ) {
            e.printStackTrace();
            throw new InternalException(e);
        }
        HttpProtocolParams.setVersion(params.);
        HttpProtocolParams.setContentCharset(params.);
        HttpProtocolParams.setUserAgent(params"Dasein Cloud");
        params.setParameter(., 300000);
        HttpProxyConfig httpProxyConfig = getHttpProxyConfigData();
        if(httpProxyConfig != null){
            params.setParameter(.new HttpHost(httpProxyConfig.getHost(), httpProxyConfig.getPort()));
            registry.register(new Scheme("http"httpProxyConfig.getPort(), new PlainSocketFactory()));
        }
        ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry);
        return new DefaultHttpClient(ccmparams);
    }
    {
        HttpProxyConfig httpProxyConfig = null;
        ifp != null && p.getProperty("proxyHost") != null && p.getProperty("proxyPort") != null) {
            if(p.getProperty("proxyPort").length() > 0) {
                httpProxyConfig = new HttpProxyConfig(p.getProperty("proxyHost"), Integer.parseInt(p.getProperty("proxyPort")));
            }
        }
        else {
            p = System.getProperties();
            if (p != null && p.getProperty("proxyHost") != null && p.getProperty("proxyPort") != null) {
                if (p.getProperty("proxyPort").length() > 0) {
                    httpProxyConfig = new HttpProxyConfig(p.getProperty("proxyHost"), Integer.parseInt(p.getProperty("proxyPort")));
                }
            }
        }
        return httpProxyConfig;
    }
    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));
            StringBuilder sb = new StringBuilder();
            String line;
            while( (line = in.readLine()) != null ) {
                sb.append(line);
                sb.append("\n");
            }
            in.close();
            return parseResponse(sb.toString(), withWireLogging);
        }
        catchIOException e ) {
            throw new CloudException(e);
        }
    }
    public String post(@Nonnull String account, @Nonnull String resource, @Nonnull String bodythrows CloudExceptionInternalException {
        if.isTraceEnabled() ) {
            .trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
        }
        if.isDebugEnabled() ) {
            .debug("POST --------------------------------------------------------> " +  + account + resource);
            .debug("");
        }
        String requestId = null;
        try {
            HttpClient client = getClient();
            String url =  + account + resource;
            HttpPost post = new HttpPost(url);
            if(url.toLowerCase().contains("operations"))
            {
                post.addHeader("x-ms-version""2014-02-01");
            }
            else if(url.toLowerCase().contains("/deployments"))
            {
                post.addHeader("x-ms-version""2014-05-01");
            }
            else {
                post.addHeader("x-ms-version""2012-03-01");
            }
            if( != null && .getSendAsHeader()){
                post.addHeader(.getHeaderName(), .getRequestId());
            }
            //If it is networking configuration services
            if(url.endsWith("/services/networking/media")){
            	post.addHeader("Content-Type""text/plain;charset=UTF-8");
            }else{
            	post.addHeader("Content-Type""application/xml;charset=UTF-8");
            }
            
            if.isDebugEnabled() ) {
                .debug(post.getRequestLine().toString());
                forHeader header : post.getAllHeaders() ) {
                    .debug(header.getName() + ": " + header.getValue());
                }
                .debug("");
                ifbody != null ) {
                    .debug(body);
                    .debug("");
                }
            }
            ifbody != null ) {
                try {
                	 if(url.endsWith("/services/networking/media")){
                		 post.setEntity(new StringEntity(body"text/plain""utf-8"));                     	
                     }else{
                    	 post.setEntity(new StringEntity(body"application/xml""utf-8")); 
                     }
                    
                }
                catchUnsupportedEncodingException e ) {
                    throw new InternalException(e);
                }
            }
            HttpResponse response;
            StatusLine status;
            try {
                response = client.execute(post);
                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 ) {
                    if.isDebugEnabled() ) {
                        .debug(h.getName() + ": " + h.getValue().trim());
                    }
                    if (h.getName().equalsIgnoreCase("x-ms-request-id")) {
                        requestId = h.getValue().trim();
                    }
                }
                else {
                    if.isDebugEnabled() ) {
                        .debug(h.getName() + ":");
                    }
                }
            }
            if.isDebugEnabled() ) {
                .debug("");
            }
            ifstatus.getStatusCode() != . && status.getStatusCode() != . && status.getStatusCode() != . ) {
                .error("post(): Expected OK for GET request, got " + status.getStatusCode());
                HttpEntity entity = response.getEntity();
                ifentity == null ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                }
                try {
                    body = EntityUtils.toString(entity);
                }
                catchIOException e ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                }
                if.isDebugEnabled() ) {
                    .debug(body);
                }
                .debug("");
                AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);
                ifitems == null ) {
                    throw new CloudException(.status.getStatusCode(), "Unknown""Unknown");
                }
                .error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                throw new AzureException(items);
            }
        }
        finally {
            if.isTraceEnabled() ) {
                .trace("exit - " + AzureMethod.class.getName() + ".post()");
            }
            if.isDebugEnabled() ) {
                .debug("");
                .debug("POST --------------------------------------------------------> " +  + account + resource);
            }
        }
        return requestId;
    }
    
    protected HttpRequestBase getMethod(String httpMethod,String url) {
    	HttpRequestBase method = null;
        if(httpMethod.equals("GET")){
        	method = new HttpGet(url);
        }else if(httpMethod.equals("POST")){
        	 method = new HttpPost(url);
        }else if(httpMethod.equals("PUT")){
            method = new HttpPut(url);	        	
        }else if(httpMethod.equals("DELETE")){
        	method = new HttpDelete(url);
        }else if(httpMethod.equals("HEAD")){
        	 method = new HttpHead(url);
        }else if(httpMethod.equals("OPTIONS")){
        	 method = new HttpOptions(url);
        }else if(httpMethod.equals("HEAD")){
        	method = new HttpTrace(url);
        }else{
        	method = new HttpGet(url);
        }
        return method;
    }
    
    public String invoke(@Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String bodythrows CloudExceptionInternalException {
        if.isTraceEnabled() ) {
            .trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
        }
        if.isDebugEnabled() ) {
            .debug("POST --------------------------------------------------------> " +  + account + resource);
            .debug("");
        }
        String requestId = null;
        try {
            HttpClient client = getClient();
            String url =  + account + resource;
            HttpRequestBase httpMethod = getMethod(methodurl);
            //If it is networking configuration services
            if (httpMethod instanceof HttpPut) {
                if(url.endsWith("/services/networking/media")){
                    httpMethod.addHeader("Content-Type""text/plain");
                }else{
                    httpMethod.addHeader("Content-Type""application/xml;charset=UTF-8");
                }
            }
            else {
                httpMethod.addHeader("Content-Type""application/xml;charset=UTF-8");
            }
            //dmayne version is older for anything to do with images and for disk deletion
            if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
                httpMethod.addHeader("x-ms-version""2012-08-01");
            }
            else if(httpMethod instanceof HttpDelete && url.indexOf("services/vmimages") > -1 ){
                httpMethod.addHeader("x-ms-version""2014-06-01");
            }
            else if(httpMethod instanceof HttpDelete && url.contains("deployments") && url.endsWith("?comp=media")){
                httpMethod.addHeader("x-ms-version""2013-08-01");
            }
            else {
                httpMethod.addHeader("x-ms-version""2012-03-01");
            }
            if( != null && .getSendAsHeader()){
                httpMethod.addHeader(.getHeaderName(), .getRequestId());
            }
            if.isDebugEnabled() ) {
                .debug(httpMethod.getRequestLine().toString());
                forHeader header : httpMethod.getAllHeaders() ) {
                    .debug(header.getName() + ": " + header.getValue());
                }
                .debug("");
                ifbody != null ) {
                    .debug(body);
                    .debug("");
                }
            }
            
            
            if(httpMethod instanceof HttpEntityEnclosingRequestBase ){
            	
            	HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBasehttpMethod;
            	
	            if (body != null) {
					try {
						entityEnclosingMethod.setEntity(new StringEntity(body"application/xml""utf-8"));
                        throw new CloudException(e);
					}
	            }           	
            }          
                      
            HttpResponse response;
            StatusLine status;
            try {
                response = client.execute(httpMethod);
                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 ) {
                    if.isDebugEnabled() ) {
                        .debug(h.getName() + ": " + h.getValue().trim());
                    }
                    if (h.getName().equalsIgnoreCase("x-ms-request-id")) {
                        requestId = h.getValue().trim();
                    }
                }
                else {
                    if.isDebugEnabled() ) {
                        .debug(h.getName() + ":");
                    }
                }
            }
            if.isDebugEnabled() ) {
                .debug("");
            }
            if (status.getStatusCode() == .) {
                .warn("Expected OK, got "+status.getStatusCode());
                String responseBody = "";
                HttpEntity entity = response.getEntity();
                ifentity == null ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                }
                try {
                    responseBody = EntityUtils.toString(entity);
                }
                catchIOException e ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                }
                .debug(responseBody);
                .debug("https: char "+responseBody.indexOf("https://"));
                .debug("account number: char "+responseBody.indexOf(account));
                String tempEndpoint = responseBody.substring(responseBody.indexOf("https://"), responseBody.indexOf(account)-responseBody.indexOf("https://"));
                .debug("temp redirect location: "+tempEndpoint);
                tempRedirectInvoke(tempEndpointmethodaccountresourcebody);
            }
            else ifstatus.getStatusCode() != . && status.getStatusCode() != . && status.getStatusCode() != . ) {
                .error("post(): Expected OK for GET request, got " + status.getStatusCode());
                HttpEntity entity = response.getEntity();
                ifentity == null ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                }
                try {
                    body = EntityUtils.toString(entity);
                }
                catchIOException e ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                }
                if.isDebugEnabled() ) {
                    .debug(body);
                }
                .debug("");
                AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);
                ifitems == null ) {
                    throw new CloudException(.status.getStatusCode(), "Unknown""Unknown");
                }
                .error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                throw new AzureException(items);
            }
        }
        finally {
            if.isTraceEnabled() ) {
                .trace("exit - " + AzureMethod.class.getName() + ".post()");
            }
            if.isDebugEnabled() ) {
                .debug("");
                .debug("POST --------------------------------------------------------> " +  + account + resource);
            }
        }
        return requestId;
    }
    public void tempRedirectInvoke(@Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String bodythrows CloudExceptionInternalException {
        if.isTraceEnabled() ) {
            .trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")");
        }
        if.isDebugEnabled() ) {
            .debug("POST --------------------------------------------------------> " +  + account + resource);
            .debug("");
        }
        try {
            HttpClient client = getClient();
            String url = tempEndpoint + account + resource;
            HttpRequestBase httpMethod = getMethod(methodurl);
            //If it is networking configuration services
            if (httpMethod instanceof HttpPut) {
                if(url.endsWith("/services/networking/media")){
                    httpMethod.addHeader("Content-Type""text/plain");
                }else{
                    httpMethod.addHeader("Content-Type""application/xml;charset=UTF-8");
                }
            }
            else {
                httpMethod.addHeader("Content-Type""application/xml;charset=UTF-8");
            }
            //dmayne version is older for anything to do with images and for disk deletion
            if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) {
                httpMethod.addHeader("x-ms-version""2012-08-01");
            }
            else {
                httpMethod.addHeader("x-ms-version""2012-03-01");
            }
            if( != null && .getSendAsHeader()){
                httpMethod.addHeader(.getHeaderName(), .getRequestId());
            }
            if.isDebugEnabled() ) {
                .debug(httpMethod.getRequestLine().toString());
                forHeader header : httpMethod.getAllHeaders() ) {
                    .debug(header.getName() + ": " + header.getValue());
                }
                .debug("");
                ifbody != null ) {
                    .debug(body);
                    .debug("");
                }
            }
            if(httpMethod instanceof HttpEntityEnclosingRequestBase ){
                HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBasehttpMethod;
                if (body != null) {
                    try {
                        entityEnclosingMethod.setEntity(new StringEntity(body"application/xml""utf-8"));
                    } catch (UnsupportedEncodingException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            HttpResponse response;
            StatusLine status;
            try {
                response = client.execute(httpMethod);
                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() != . && status.getStatusCode() != . && status.getStatusCode() != . ) {
                .error("post(): Expected OK for GET request, got " + status.getStatusCode());
                HttpEntity entity = response.getEntity();
                ifentity == null ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation");
                }
                try {
                    body = EntityUtils.toString(entity);
                }
                catchIOException e ) {
                    throw new AzureException(.status.getStatusCode(), status.getReasonPhrase(), e.getMessage());
                }
                if.isDebugEnabled() ) {
                    .debug(body);
                }
                .debug("");
                AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body);
                ifitems == null ) {
                    throw new CloudException(.status.getStatusCode(), "Unknown""Unknown");
                }
                .error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details);
                throw new AzureException(items);
            }
        }
        finally {
            if.isTraceEnabled() ) {
                .trace("exit - " + AzureMethod.class.getName() + ".post()");
            }
            if.isDebugEnabled() ) {
                .debug("");
                .debug("POST --------------------------------------------------------> " +  + account + resource);
            }
        }
    }
    public @Nonnull int getOperationStatus(String requestIDthrows CloudExceptionInternalException {
        ProviderContext ctx = .getContext();
        Document doc = getAsXML(ctx.getAccountNumber(),"/operations/"+requestID);
        if (doc == null) {
            return -2;
        }
        NodeList entries = doc.getElementsByTagName("Operation");
        Node entry = entries.item(0);
        NodeList s = entry.getChildNodes();
        String status = "";
        String httpCode = "";
        for (int i =0; i<s.getLength(); i++) {
            Node attribute = s.item(i);
            ifattribute.getNodeType() == .) {
                continue;
            }
            ifattribute.getNodeName().equalsIgnoreCase("status") && attribute.hasChildNodes() ) {
                status = attribute.getFirstChild().getNodeValue().trim();
                continue;
            }
            if (status.length() > 0 && !status.equalsIgnoreCase("inProgress")) {
                ifattribute.getNodeName().equalsIgnoreCase("httpstatuscode") && attribute.hasChildNodes() ) {
                    httpCode = attribute.getFirstChild().getNodeValue().trim();
                }
            }
        }
        if (status.equalsIgnoreCase("succeeded")) {
           return .;
        }
        else if (status.equalsIgnoreCase("failed")) {
            String errMsg = checkError(shttpCode);
            throw new CloudException(errMsg);
        }
        return -1;
    }
    private String checkError(NodeList sString httpCodethrows CloudExceptionInternalException {
        String errMsg = httpCode+": ";
        for (int i=0; i<s.getLength(); i++) {
            Node attribute = s.item(i);
            ifattribute.getNodeType() == .) {
                continue;
            }
            ifattribute.getNodeName().equalsIgnoreCase("Error") && attribute.hasChildNodes() ) {
                NodeList errors = attribute.getChildNodes();
                for (int error = 0; error < errors.getLength(); error++) {
                    Node node = errors.item(error);
                    if (node.getNodeName().equalsIgnoreCase("code") && node.hasChildNodes()) {
                        errMsg = errMsg + node.getFirstChild().getNodeValue().trim();
                        continue;
                    }
                    if (node.getNodeName().equalsIgnoreCase("message") && node.hasChildNodes()) {
                        errMsg = errMsg + ". reason: " + node.getFirstChild().getNodeValue().trim();
                    }
                }
            }
        }
        return errMsg;
    }