com.microsoft.windowsazure.management.websites.WebHostingPlanOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.websites.WebHostingPlanOperationsImpl.java

Source

/**
 * 
 * Copyright (c) Microsoft and contributors.  All rights reserved.
 * 
 * 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.
 * 
 */

// Warning: This code was generated by a tool.
// 
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.

package com.microsoft.windowsazure.management.websites;

import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete;
import com.microsoft.windowsazure.core.utils.BOMInputStream;
import com.microsoft.windowsazure.core.utils.CollectionStringBuilder;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.websites.models.HistoricalUsageMetric;
import com.microsoft.windowsazure.management.websites.models.HistoricalUsageMetricData;
import com.microsoft.windowsazure.management.websites.models.HistoricalUsageMetricSample;
import com.microsoft.windowsazure.management.websites.models.SkuOptions;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlan;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanCreateParameters;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanCreateResponse;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanGetHistoricalUsageMetricsParameters;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanGetHistoricalUsageMetricsResponse;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanGetResponse;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanListResponse;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanUpdateParameters;
import com.microsoft.windowsazure.management.websites.models.WebHostingPlanUpdateResponse;
import com.microsoft.windowsazure.management.websites.models.WorkerSizeOptions;
import com.microsoft.windowsazure.tracing.CloudTracing;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.bind.DatatypeConverter;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
* Operations for managing web hosting plans beneath your subscription.
*/
public class WebHostingPlanOperationsImpl
        implements ServiceOperations<WebSiteManagementClientImpl>, WebHostingPlanOperations {
    /**
    * Initializes a new instance of the WebHostingPlanOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    WebHostingPlanOperationsImpl(WebSiteManagementClientImpl client) {
        this.client = client;
    }

    private WebSiteManagementClientImpl client;

    /**
    * Gets a reference to the
    * microsoft.windowsazure.management.websites.WebSiteManagementClientImpl.
    * @return The Client value.
    */
    public WebSiteManagementClientImpl getClient() {
        return this.client;
    }

    /**
    * Creates a new Web Hosting Plan.  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param parameters Required. Web Hosting Plan Parameters.
    * @return The Create Web Web Hosting Plan operation response.
    */
    @Override
    public Future<WebHostingPlanCreateResponse> createAsync(final String webSpaceName,
            final WebHostingPlanCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<WebHostingPlanCreateResponse>() {
            @Override
            public WebHostingPlanCreateResponse call() throws Exception {
                return create(webSpaceName, parameters);
            }
        });
    }

    /**
    * Creates a new Web Hosting Plan.  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param parameters Required. Web Hosting Plan Parameters.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The Create Web Web Hosting Plan operation response.
    */
    @Override
    public WebHostingPlanCreateResponse create(String webSpaceName, WebHostingPlanCreateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
            URISyntaxException {
        // Validate
        if (webSpaceName == null) {
            throw new NullPointerException("webSpaceName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getName() == null) {
            throw new NullPointerException("parameters.Name");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("webSpaceName", webSpaceName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/WebSpaces/";
        url = url + URLEncoder.encode(webSpaceName, "UTF-8");
        url = url + "/ServerFarms";
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpPost httpRequest = new HttpPost(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/xml");
        httpRequest.setHeader("x-ms-version", "2014-04-01");

        // Serialize Request
        String requestContent = null;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document requestDoc = documentBuilder.newDocument();

        Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServerFarm");
        requestDoc.appendChild(serverFarmElement);

        Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
        nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
        serverFarmElement.appendChild(nameElement);

        if (parameters.getNumberOfWorkers() != null) {
            Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "NumberOfWorkers");
            numberOfWorkersElement
                    .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
            serverFarmElement.appendChild(numberOfWorkersElement);
        }

        if (parameters.getSKU() != null) {
            Element sKUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SKU");
            sKUElement.appendChild(requestDoc.createTextNode(parameters.getSKU().toString()));
            serverFarmElement.appendChild(sKUElement);
        }

        if (parameters.getWorkerSize() != null) {
            Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "WorkerSize");
            workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
            serverFarmElement.appendChild(workerSizeElement);
        }

        if (parameters.getAdminSiteName() != null) {
            Element adminSiteNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "AdminSiteName");
            adminSiteNameElement.appendChild(requestDoc.createTextNode(parameters.getAdminSiteName()));
            serverFarmElement.appendChild(adminSiteNameElement);
        }

        DOMSource domSource = new DOMSource(requestDoc);
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(domSource, streamResult);
        requestContent = stringWriter.toString();
        StringEntity entity = new StringEntity(requestContent);
        httpRequest.setEntity(entity);
        httpRequest.setHeader("Content-Type", "application/xml");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            WebHostingPlanCreateResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new WebHostingPlanCreateResponse();
                DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
                documentBuilderFactory2.setNamespaceAware(true);
                DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
                Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

                Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement2 != null) {
                    WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
                    result.setWebHostingPlan(webHostingPlanInstance);

                    Element nameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement2 != null) {
                        String nameInstance;
                        nameInstance = nameElement2.getTextContent();
                        webHostingPlanInstance.setName(nameInstance);
                    }

                    Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                    if (numberOfWorkersElement2 != null && numberOfWorkersElement2.getTextContent() != null
                            && !numberOfWorkersElement2.getTextContent().isEmpty()) {
                        int numberOfWorkersInstance;
                        numberOfWorkersInstance = DatatypeConverter
                                .parseInt(numberOfWorkersElement2.getTextContent());
                        webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance);
                    }

                    Element sKUElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "SKU");
                    if (sKUElement2 != null && sKUElement2.getTextContent() != null
                            && !sKUElement2.getTextContent().isEmpty()) {
                        SkuOptions sKUInstance;
                        sKUInstance = SkuOptions.valueOf(sKUElement2.getTextContent());
                        webHostingPlanInstance.setSKU(sKUInstance);
                    }

                    Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                    if (workerSizeElement2 != null && workerSizeElement2.getTextContent() != null
                            && !workerSizeElement2.getTextContent().isEmpty()) {
                        WorkerSizeOptions workerSizeInstance;
                        workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement2.getTextContent());
                        webHostingPlanInstance.setWorkerSize(workerSizeInstance);
                    }

                    Element adminSiteNameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                    if (adminSiteNameElement2 != null) {
                        String adminSiteNameInstance;
                        adminSiteNameInstance = adminSiteNameElement2.getTextContent();
                        webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Deletes a Web Hosting Plan  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> deleteAsync(final String webSpaceName, final String webHostingPlanName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return delete(webSpaceName, webHostingPlanName);
            }
        });
    }

    /**
    * Deletes a Web Hosting Plan  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse delete(String webSpaceName, String webHostingPlanName)
            throws IOException, ServiceException {
        // Validate
        if (webSpaceName == null) {
            throw new NullPointerException("webSpaceName");
        }
        if (webHostingPlanName == null) {
            throw new NullPointerException("webHostingPlanName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("webSpaceName", webSpaceName);
            tracingParameters.put("webHostingPlanName", webHostingPlanName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/WebSpaces/";
        url = url + URLEncoder.encode(webSpaceName, "UTF-8");
        url = url + "/ServerFarms/";
        url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        CustomHttpDelete httpRequest = new CustomHttpDelete(url);

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2014-04-01");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            OperationResponse result = null;
            // Deserialize Response
            result = new OperationResponse();
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Gets details of an existing Web Hosting Plan  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @return The Get Web Hosting Plan operation response.
    */
    @Override
    public Future<WebHostingPlanGetResponse> getAsync(final String webSpaceName, final String webHostingPlanName) {
        return this.getClient().getExecutorService().submit(new Callable<WebHostingPlanGetResponse>() {
            @Override
            public WebHostingPlanGetResponse call() throws Exception {
                return get(webSpaceName, webHostingPlanName);
            }
        });
    }

    /**
    * Gets details of an existing Web Hosting Plan  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The Get Web Hosting Plan operation response.
    */
    @Override
    public WebHostingPlanGetResponse get(String webSpaceName, String webHostingPlanName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (webSpaceName == null) {
            throw new NullPointerException("webSpaceName");
        }
        if (webHostingPlanName == null) {
            throw new NullPointerException("webHostingPlanName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("webSpaceName", webSpaceName);
            tracingParameters.put("webHostingPlanName", webHostingPlanName);
            CloudTracing.enter(invocationId, this, "getAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/WebSpaces/";
        url = url + URLEncoder.encode(webSpaceName, "UTF-8");
        url = url + "/serverFarms/";
        url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpGet httpRequest = new HttpGet(url);

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2014-04-01");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            WebHostingPlanGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new WebHostingPlanGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element serverFarmElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement != null) {
                    WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
                    result.setWebHostingPlan(webHostingPlanInstance);

                    Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        String nameInstance;
                        nameInstance = nameElement.getTextContent();
                        webHostingPlanInstance.setName(nameInstance);
                    }

                    Element numberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                            "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                    if (numberOfWorkersElement != null && numberOfWorkersElement.getTextContent() != null
                            && !numberOfWorkersElement.getTextContent().isEmpty()) {
                        int numberOfWorkersInstance;
                        numberOfWorkersInstance = DatatypeConverter
                                .parseInt(numberOfWorkersElement.getTextContent());
                        webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance);
                    }

                    Element sKUElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                            "http://schemas.microsoft.com/windowsazure", "SKU");
                    if (sKUElement != null && sKUElement.getTextContent() != null
                            && !sKUElement.getTextContent().isEmpty()) {
                        SkuOptions sKUInstance;
                        sKUInstance = SkuOptions.valueOf(sKUElement.getTextContent());
                        webHostingPlanInstance.setSKU(sKUInstance);
                    }

                    Element workerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                            "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                    if (workerSizeElement != null && workerSizeElement.getTextContent() != null
                            && !workerSizeElement.getTextContent().isEmpty()) {
                        WorkerSizeOptions workerSizeInstance;
                        workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement.getTextContent());
                        webHostingPlanInstance.setWorkerSize(workerSizeInstance);
                    }

                    Element adminSiteNameElement = XmlUtility.getElementByTagNameNS(serverFarmElement,
                            "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                    if (adminSiteNameElement != null) {
                        String adminSiteNameInstance;
                        adminSiteNameInstance = adminSiteNameElement.getTextContent();
                        webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * You can retrieve historical usage metrics for a site by issuing an HTTP
    * GET request.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for
    * more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @param parameters Required. Parameters supplied to the Get Historical
    * Usage Metrics Web hosting plan operation.
    * @return The Get Historical Usage Metrics Web hosting plan operation
    * response.
    */
    @Override
    public Future<WebHostingPlanGetHistoricalUsageMetricsResponse> getHistoricalUsageMetricsAsync(
            final String webSpaceName, final String webHostingPlanName,
            final WebHostingPlanGetHistoricalUsageMetricsParameters parameters) {
        return this.getClient().getExecutorService()
                .submit(new Callable<WebHostingPlanGetHistoricalUsageMetricsResponse>() {
                    @Override
                    public WebHostingPlanGetHistoricalUsageMetricsResponse call() throws Exception {
                        return getHistoricalUsageMetrics(webSpaceName, webHostingPlanName, parameters);
                    }
                });
    }

    /**
    * You can retrieve historical usage metrics for a site by issuing an HTTP
    * GET request.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166964.aspx for
    * more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @param parameters Required. Parameters supplied to the Get Historical
    * Usage Metrics Web hosting plan operation.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @return The Get Historical Usage Metrics Web hosting plan operation
    * response.
    */
    @Override
    public WebHostingPlanGetHistoricalUsageMetricsResponse getHistoricalUsageMetrics(String webSpaceName,
            String webHostingPlanName, WebHostingPlanGetHistoricalUsageMetricsParameters parameters)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (webSpaceName == null) {
            throw new NullPointerException("webSpaceName");
        }
        if (webHostingPlanName == null) {
            throw new NullPointerException("webHostingPlanName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("webSpaceName", webSpaceName);
            tracingParameters.put("webHostingPlanName", webHostingPlanName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "getHistoricalUsageMetricsAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/WebSpaces/";
        url = url + URLEncoder.encode(webSpaceName, "UTF-8");
        url = url + "/serverFarms/";
        url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
        url = url + "/metrics";
        ArrayList<String> queryParameters = new ArrayList<String>();
        if (parameters.getMetricNames() != null && parameters.getMetricNames().size() > 0) {
            queryParameters.add("names="
                    + URLEncoder.encode(CollectionStringBuilder.join(parameters.getMetricNames(), ","), "UTF-8"));
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        if (parameters.getStartTime() != null) {
            queryParameters.add("StartTime="
                    + URLEncoder.encode(simpleDateFormat.format(parameters.getStartTime().getTime()), "UTF-8"));
        }
        SimpleDateFormat simpleDateFormat2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
        simpleDateFormat2.setTimeZone(TimeZone.getTimeZone("UTC"));
        if (parameters.getEndTime() != null) {
            queryParameters.add("EndTime="
                    + URLEncoder.encode(simpleDateFormat2.format(parameters.getEndTime().getTime()), "UTF-8"));
        }
        if (parameters.getTimeGrain() != null) {
            queryParameters.add("timeGrain=" + URLEncoder.encode(parameters.getTimeGrain(), "UTF-8"));
        }
        queryParameters.add("details=" + URLEncoder
                .encode(Boolean.toString(parameters.isIncludeInstanceBreakdown()).toLowerCase(), "UTF-8"));
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpGet httpRequest = new HttpGet(url);

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2014-04-01");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            WebHostingPlanGetHistoricalUsageMetricsResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new WebHostingPlanGetHistoricalUsageMetricsResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element metricResponsesElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "MetricResponses");
                if (metricResponsesElement != null) {
                    if (metricResponsesElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(metricResponsesElement,
                                        "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element usageMetricsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(metricResponsesElement,
                                            "http://schemas.microsoft.com/windowsazure", "MetricResponse")
                                    .get(i1));
                            HistoricalUsageMetric metricResponseInstance = new HistoricalUsageMetric();
                            result.getUsageMetrics().add(metricResponseInstance);

                            Element codeElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Code");
                            if (codeElement != null) {
                                String codeInstance;
                                codeInstance = codeElement.getTextContent();
                                metricResponseInstance.setCode(codeInstance);
                            }

                            Element dataElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Data");
                            if (dataElement != null) {
                                HistoricalUsageMetricData dataInstance = new HistoricalUsageMetricData();
                                metricResponseInstance.setData(dataInstance);

                                Element displayNameElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "DisplayName");
                                if (displayNameElement != null) {
                                    String displayNameInstance;
                                    displayNameInstance = displayNameElement.getTextContent();
                                    dataInstance.setDisplayName(displayNameInstance);
                                }

                                Element endTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "EndTime");
                                if (endTimeElement != null) {
                                    Calendar endTimeInstance;
                                    endTimeInstance = DatatypeConverter
                                            .parseDateTime(endTimeElement.getTextContent());
                                    dataInstance.setEndTime(endTimeInstance);
                                }

                                Element nameElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "Name");
                                if (nameElement != null) {
                                    String nameInstance;
                                    nameInstance = nameElement.getTextContent();
                                    dataInstance.setName(nameInstance);
                                }

                                Element primaryAggregationTypeElement = XmlUtility.getElementByTagNameNS(
                                        dataElement, "http://schemas.microsoft.com/windowsazure",
                                        "PrimaryAggregationType");
                                if (primaryAggregationTypeElement != null) {
                                    String primaryAggregationTypeInstance;
                                    primaryAggregationTypeInstance = primaryAggregationTypeElement.getTextContent();
                                    dataInstance.setPrimaryAggregationType(primaryAggregationTypeInstance);
                                }

                                Element startTimeElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "StartTime");
                                if (startTimeElement != null) {
                                    Calendar startTimeInstance;
                                    startTimeInstance = DatatypeConverter
                                            .parseDateTime(startTimeElement.getTextContent());
                                    dataInstance.setStartTime(startTimeInstance);
                                }

                                Element timeGrainElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "TimeGrain");
                                if (timeGrainElement != null) {
                                    String timeGrainInstance;
                                    timeGrainInstance = timeGrainElement.getTextContent();
                                    dataInstance.setTimeGrain(timeGrainInstance);
                                }

                                Element unitElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "Unit");
                                if (unitElement != null) {
                                    String unitInstance;
                                    unitInstance = unitElement.getTextContent();
                                    dataInstance.setUnit(unitInstance);
                                }

                                Element valuesSequenceElement = XmlUtility.getElementByTagNameNS(dataElement,
                                        "http://schemas.microsoft.com/windowsazure", "Values");
                                if (valuesSequenceElement != null) {
                                    for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(valuesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                            .size(); i2 = i2 + 1) {
                                        org.w3c.dom.Element valuesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(valuesSequenceElement,
                                                        "http://schemas.microsoft.com/windowsazure", "MetricSample")
                                                .get(i2));
                                        HistoricalUsageMetricSample metricSampleInstance = new HistoricalUsageMetricSample();
                                        dataInstance.getValues().add(metricSampleInstance);

                                        Element countElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                                "http://schemas.microsoft.com/windowsazure", "Count");
                                        if (countElement != null) {
                                            int countInstance;
                                            countInstance = DatatypeConverter
                                                    .parseInt(countElement.getTextContent());
                                            metricSampleInstance.setCount(countInstance);
                                        }

                                        Element maximumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                                "http://schemas.microsoft.com/windowsazure", "Maximum");
                                        if (maximumElement != null) {
                                            boolean isNil = false;
                                            Attr nilAttribute = maximumElement.getAttributeNodeNS(
                                                    "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                            if (nilAttribute != null) {
                                                isNil = "true".equals(nilAttribute.getValue());
                                            }
                                            if (isNil == false) {
                                                String maximumInstance;
                                                maximumInstance = maximumElement.getTextContent();
                                                metricSampleInstance.setMaximum(maximumInstance);
                                            }
                                        }

                                        Element minimumElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                                "http://schemas.microsoft.com/windowsazure", "Minimum");
                                        if (minimumElement != null) {
                                            boolean isNil2 = false;
                                            Attr nilAttribute2 = minimumElement.getAttributeNodeNS(
                                                    "http://www.w3.org/2001/XMLSchema-instance", "nil");
                                            if (nilAttribute2 != null) {
                                                isNil2 = "true".equals(nilAttribute2.getValue());
                                            }
                                            if (isNil2 == false) {
                                                String minimumInstance;
                                                minimumInstance = minimumElement.getTextContent();
                                                metricSampleInstance.setMinimum(minimumInstance);
                                            }
                                        }

                                        Element timeCreatedElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                                "http://schemas.microsoft.com/windowsazure", "TimeCreated");
                                        if (timeCreatedElement != null) {
                                            Calendar timeCreatedInstance;
                                            timeCreatedInstance = DatatypeConverter
                                                    .parseDateTime(timeCreatedElement.getTextContent());
                                            metricSampleInstance.setTimeCreated(timeCreatedInstance);
                                        }

                                        Element totalElement = XmlUtility.getElementByTagNameNS(valuesElement,
                                                "http://schemas.microsoft.com/windowsazure", "Total");
                                        if (totalElement != null) {
                                            String totalInstance;
                                            totalInstance = totalElement.getTextContent();
                                            metricSampleInstance.setTotal(totalInstance);
                                        }

                                        Element instanceNameElement = XmlUtility.getElementByTagNameNS(
                                                valuesElement, "http://schemas.microsoft.com/windowsazure",
                                                "InstanceName");
                                        if (instanceNameElement != null) {
                                            String instanceNameInstance;
                                            instanceNameInstance = instanceNameElement.getTextContent();
                                            metricSampleInstance.setInstanceName(instanceNameInstance);
                                        }
                                    }
                                }
                            }

                            Element messageElement = XmlUtility.getElementByTagNameNS(usageMetricsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Message");
                            if (messageElement != null) {
                                String messageInstance;
                                messageInstance = messageElement.getTextContent();
                                metricResponseInstance.setMessage(messageInstance);
                            }
                        }
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * You can list the web spaces under the current subscription by issuing a
    * GET request.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for
    * more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @return The List Web Hosting Plans operation response.
    */
    @Override
    public Future<WebHostingPlanListResponse> listAsync(final String webSpaceName) {
        return this.getClient().getExecutorService().submit(new Callable<WebHostingPlanListResponse>() {
            @Override
            public WebHostingPlanListResponse call() throws Exception {
                return list(webSpaceName);
            }
        });
    }

    /**
    * You can list the web spaces under the current subscription by issuing a
    * GET request.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn166961.aspx for
    * more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @return The List Web Hosting Plans operation response.
    */
    @Override
    public WebHostingPlanListResponse list(String webSpaceName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (webSpaceName == null) {
            throw new NullPointerException("webSpaceName");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("webSpaceName", webSpaceName);
            CloudTracing.enter(invocationId, this, "listAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/WebSpaces/";
        url = url + URLEncoder.encode(webSpaceName, "UTF-8");
        url = url + "/serverFarms";
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpGet httpRequest = new HttpGet(url);

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2014-04-01");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            WebHostingPlanListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new WebHostingPlanListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element serverFarmsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarms");
                if (serverFarmsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(serverFarmsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServerFarm")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element serverFarmsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(serverFarmsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ServerFarm")
                                .get(i1));
                        WebHostingPlan serverFarmInstance = new WebHostingPlan();
                        result.getWebHostingPlans().add(serverFarmInstance);

                        Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                                "http://schemas.microsoft.com/windowsazure", "Name");
                        if (nameElement != null) {
                            String nameInstance;
                            nameInstance = nameElement.getTextContent();
                            serverFarmInstance.setName(nameInstance);
                        }

                        Element numberOfWorkersElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                                "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                        if (numberOfWorkersElement != null && numberOfWorkersElement.getTextContent() != null
                                && !numberOfWorkersElement.getTextContent().isEmpty()) {
                            int numberOfWorkersInstance;
                            numberOfWorkersInstance = DatatypeConverter
                                    .parseInt(numberOfWorkersElement.getTextContent());
                            serverFarmInstance.setNumberOfWorkers(numberOfWorkersInstance);
                        }

                        Element sKUElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                                "http://schemas.microsoft.com/windowsazure", "SKU");
                        if (sKUElement != null && sKUElement.getTextContent() != null
                                && !sKUElement.getTextContent().isEmpty()) {
                            SkuOptions sKUInstance;
                            sKUInstance = SkuOptions.valueOf(sKUElement.getTextContent());
                            serverFarmInstance.setSKU(sKUInstance);
                        }

                        Element workerSizeElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                                "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                        if (workerSizeElement != null && workerSizeElement.getTextContent() != null
                                && !workerSizeElement.getTextContent().isEmpty()) {
                            WorkerSizeOptions workerSizeInstance;
                            workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement.getTextContent());
                            serverFarmInstance.setWorkerSize(workerSizeInstance);
                        }

                        Element adminSiteNameElement = XmlUtility.getElementByTagNameNS(serverFarmsElement,
                                "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                        if (adminSiteNameElement != null) {
                            String adminSiteNameInstance;
                            adminSiteNameInstance = adminSiteNameElement.getTextContent();
                            serverFarmInstance.setAdminSiteName(adminSiteNameInstance);
                        }
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }

    /**
    * Updates an existing Web Hosting Plan.  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @param parameters Required. Parameters supplied to the Update Web Hosting
    * Plan operation.
    * @return The Create Web Hosting Plan operation response.
    */
    @Override
    public Future<WebHostingPlanUpdateResponse> updateAsync(final String webSpaceName,
            final String webHostingPlanName, final WebHostingPlanUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<WebHostingPlanUpdateResponse>() {
            @Override
            public WebHostingPlanUpdateResponse call() throws Exception {
                return update(webSpaceName, webHostingPlanName, parameters);
            }
        });
    }

    /**
    * Updates an existing Web Hosting Plan.  (see
    * http://azure.microsoft.com/en-us/documentation/articles/azure-web-sites-web-hosting-plans-in-depth-overview/
    * for more information)
    *
    * @param webSpaceName Required. The name of the web space.
    * @param webHostingPlanName Required. The name of the web hosting plan.
    * @param parameters Required. Parameters supplied to the Update Web Hosting
    * Plan operation.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The Create Web Hosting Plan operation response.
    */
    @Override
    public WebHostingPlanUpdateResponse update(String webSpaceName, String webHostingPlanName,
            WebHostingPlanUpdateParameters parameters) throws ParserConfigurationException, SAXException,
            TransformerException, IOException, ServiceException, URISyntaxException {
        // Validate
        if (webSpaceName == null) {
            throw new NullPointerException("webSpaceName");
        }
        if (webHostingPlanName == null) {
            throw new NullPointerException("webHostingPlanName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("webSpaceName", webSpaceName);
            tracingParameters.put("webHostingPlanName", webHostingPlanName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/WebSpaces/";
        url = url + URLEncoder.encode(webSpaceName, "UTF-8");
        url = url + "/ServerFarms/";
        url = url + URLEncoder.encode(webHostingPlanName, "UTF-8");
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpPut httpRequest = new HttpPut(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/xml");
        httpRequest.setHeader("x-ms-version", "2014-04-01");

        // Serialize Request
        String requestContent = null;
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        Document requestDoc = documentBuilder.newDocument();

        Element serverFarmElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ServerFarm");
        requestDoc.appendChild(serverFarmElement);

        if (parameters.getNumberOfWorkers() != null) {
            Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "NumberOfWorkers");
            numberOfWorkersElement
                    .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
            serverFarmElement.appendChild(numberOfWorkersElement);
        }

        if (parameters.getSKU() != null) {
            Element sKUElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SKU");
            sKUElement.appendChild(requestDoc.createTextNode(parameters.getSKU().toString()));
            serverFarmElement.appendChild(sKUElement);
        }

        if (parameters.getWorkerSize() != null) {
            Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "WorkerSize");
            workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
            serverFarmElement.appendChild(workerSizeElement);
        }

        if (parameters.getAdminSiteName() != null) {
            Element adminSiteNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "AdminSiteName");
            adminSiteNameElement.appendChild(requestDoc.createTextNode(parameters.getAdminSiteName()));
            serverFarmElement.appendChild(adminSiteNameElement);
        }

        DOMSource domSource = new DOMSource(requestDoc);
        StringWriter stringWriter = new StringWriter();
        StreamResult streamResult = new StreamResult(stringWriter);
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.transform(domSource, streamResult);
        requestContent = stringWriter.toString();
        StringEntity entity = new StringEntity(requestContent);
        httpRequest.setEntity(entity);
        httpRequest.setHeader("Content-Type", "application/xml");

        // Send Request
        HttpResponse httpResponse = null;
        try {
            if (shouldTrace) {
                CloudTracing.sendRequest(invocationId, httpRequest);
            }
            httpResponse = this.getClient().getHttpClient().execute(httpRequest);
            if (shouldTrace) {
                CloudTracing.receiveResponse(invocationId, httpResponse);
            }
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

            // Create Result
            WebHostingPlanUpdateResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new WebHostingPlanUpdateResponse();
                DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
                documentBuilderFactory2.setNamespaceAware(true);
                DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
                Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

                Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ServerFarm");
                if (serverFarmElement2 != null) {
                    WebHostingPlan webHostingPlanInstance = new WebHostingPlan();
                    result.setWebHostingPlan(webHostingPlanInstance);

                    Element nameElement = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "Name");
                    if (nameElement != null) {
                        String nameInstance;
                        nameInstance = nameElement.getTextContent();
                        webHostingPlanInstance.setName(nameInstance);
                    }

                    Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
                    if (numberOfWorkersElement2 != null && numberOfWorkersElement2.getTextContent() != null
                            && !numberOfWorkersElement2.getTextContent().isEmpty()) {
                        int numberOfWorkersInstance;
                        numberOfWorkersInstance = DatatypeConverter
                                .parseInt(numberOfWorkersElement2.getTextContent());
                        webHostingPlanInstance.setNumberOfWorkers(numberOfWorkersInstance);
                    }

                    Element sKUElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "SKU");
                    if (sKUElement2 != null && sKUElement2.getTextContent() != null
                            && !sKUElement2.getTextContent().isEmpty()) {
                        SkuOptions sKUInstance;
                        sKUInstance = SkuOptions.valueOf(sKUElement2.getTextContent());
                        webHostingPlanInstance.setSKU(sKUInstance);
                    }

                    Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "WorkerSize");
                    if (workerSizeElement2 != null && workerSizeElement2.getTextContent() != null
                            && !workerSizeElement2.getTextContent().isEmpty()) {
                        WorkerSizeOptions workerSizeInstance;
                        workerSizeInstance = WorkerSizeOptions.valueOf(workerSizeElement2.getTextContent());
                        webHostingPlanInstance.setWorkerSize(workerSizeInstance);
                    }

                    Element adminSiteNameElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                            "http://schemas.microsoft.com/windowsazure", "AdminSiteName");
                    if (adminSiteNameElement2 != null) {
                        String adminSiteNameInstance;
                        adminSiteNameInstance = adminSiteNameElement2.getTextContent();
                        webHostingPlanInstance.setAdminSiteName(adminSiteNameInstance);
                    }
                }

            }
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }
            return result;
        } finally {
            if (httpResponse != null && httpResponse.getEntity() != null) {
                httpResponse.getEntity().getContent().close();
            }
        }
    }
}