com.microsoft.windowsazure.management.network.ApplicationGatewayOperationsImpl.java Source code

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.network.ApplicationGatewayOperationsImpl.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.network;

import com.microsoft.windowsazure.core.LazyCollection;
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.CloudError;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.network.models.AGHttpListener;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayCertificate;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayGetCertificate;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayGetConfiguration;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayGetResponse;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayListCertificate;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayListResponse;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayOperation;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewayOperationResponse;
import com.microsoft.windowsazure.management.network.models.ApplicationGatewaySetConfiguration;
import com.microsoft.windowsazure.management.network.models.AsyncOperationStatus;
import com.microsoft.windowsazure.management.network.models.BackendAddressPool;
import com.microsoft.windowsazure.management.network.models.BackendHttpSettings;
import com.microsoft.windowsazure.management.network.models.BackendServer;
import com.microsoft.windowsazure.management.network.models.CreateApplicationGatewayParameters;
import com.microsoft.windowsazure.management.network.models.FrontendIPConfiguration;
import com.microsoft.windowsazure.management.network.models.FrontendPort;
import com.microsoft.windowsazure.management.network.models.GatewayOperationResponse;
import com.microsoft.windowsazure.management.network.models.HttpLoadBalancingRule;
import com.microsoft.windowsazure.management.network.models.Protocol;
import com.microsoft.windowsazure.management.network.models.UpdateApplicationGatewayParameters;
import com.microsoft.windowsazure.tracing.ClientRequestTrackingHandler;
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.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.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
* The Application Gateway Management API includes operations for managing
* application gateways in your subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj154113.aspx for more
* information)
*/
public class ApplicationGatewayOperationsImpl
        implements ServiceOperations<NetworkManagementClientImpl>, ApplicationGatewayOperations {
    /**
    * Initializes a new instance of the ApplicationGatewayOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    ApplicationGatewayOperationsImpl(NetworkManagementClientImpl client) {
        this.client = client;
    }

    private NetworkManagementClientImpl client;

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

    /**
    * The Add certificate operation adds the ssl certificate to the application
    * gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param certificateName Required. Certificate name
    * @param certificate Required. The application gateway ssl certificate
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> addCertificateAsync(final String gatewayName,
            final String certificateName, final ApplicationGatewayCertificate certificate) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return addCertificate(gatewayName, certificateName, certificate);
            }
        });
    }

    /**
    * The Add certificate operation adds the ssl certificate to the application
    * gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param certificateName Required. Certificate name
    * @param certificate Required. The application gateway ssl certificate
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse addCertificate(String gatewayName, String certificateName,
            ApplicationGatewayCertificate certificate)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("gatewayName", gatewayName);
            tracingParameters.put("certificateName", certificateName);
            tracingParameters.put("certificate", certificate);
            CloudTracing.enter(invocationId, this, "addCertificateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginAddCertificateAsync(gatewayName, certificateName, certificate).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * The Begin Add certificate operation adds the ssl certificate to the
    * application gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param certificateName Required. Certificate name
    * @param certificate Required. The application gateway ssl certificate
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginAddCertificateAsync(final String gatewayName,
            final String certificateName, final ApplicationGatewayCertificate certificate) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginAddCertificate(gatewayName, certificateName, certificate);
            }
        });
    }

    /**
    * The Begin Add certificate operation adds the ssl certificate to the
    * application gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param certificateName Required. Certificate name
    * @param certificate Required. The application gateway ssl certificate
    * @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.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginAddCertificate(String gatewayName, String certificateName,
            ApplicationGatewayCertificate certificate)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }
        if (certificateName == null) {
            throw new NullPointerException("certificateName");
        }
        if (certificate == null) {
            throw new NullPointerException("certificate");
        }

        // 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("gatewayName", gatewayName);
            tracingParameters.put("certificateName", certificateName);
            tracingParameters.put("certificate", certificate);
            CloudTracing.enter(invocationId, this, "beginAddCertificateAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/sslcertificates/";
        url = url + URLEncoder.encode(certificateName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        HttpPut httpRequest = new HttpPut(url);

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

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

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

        if (certificate.getData() != null) {
            Element dataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Data");
            dataElement.appendChild(requestDoc.createTextNode(certificate.getData()));
            certificateFileElement.appendChild(dataElement);
        }

        if (certificate.getCertificateFormat() != null) {
            Element certificateFormatElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateFormat");
            certificateFormatElement.appendChild(requestDoc.createTextNode(certificate.getCertificateFormat()));
            certificateFileElement.appendChild(certificateFormatElement);
        }

        if (certificate.getPassword() != null) {
            Element passwordElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Password");
            passwordElement.appendChild(requestDoc.createTextNode(certificate.getPassword()));
            certificateFileElement.appendChild(passwordElement);
        }

        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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Begin Create Application Gateway operation  creates Application
    * Gateway with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Begin
    * CreateApplication Gateway request.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginCreateApplicationGatewayAsync(
            final CreateApplicationGatewayParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginCreateApplicationGateway(parameters);
            }
        });
    }

    /**
    * The Begin Create Application Gateway operation  creates Application
    * Gateway with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Begin
    * CreateApplication Gateway request.
    * @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.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginCreateApplicationGateway(CreateApplicationGatewayParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        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("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginCreateApplicationGatewayAsync", 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/networking/ApplicationGateways";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        HttpPost httpRequest = new HttpPost(url);

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

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

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

        if (parameters.getDescription() != null) {
            Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Description");
            descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
            createApplicationGatewayParametersElement.appendChild(descriptionElement);
        }

        if (parameters.getGatewaySize() != null) {
            Element gatewaySizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "GatewaySize");
            gatewaySizeElement.appendChild(requestDoc.createTextNode(parameters.getGatewaySize()));
            createApplicationGatewayParametersElement.appendChild(gatewaySizeElement);
        }

        Element instanceCountElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "InstanceCount");
        instanceCountElement.appendChild(requestDoc.createTextNode(Long.toString(parameters.getInstanceCount())));
        createApplicationGatewayParametersElement.appendChild(instanceCountElement);

        if (parameters.getName() != null) {
            Element nameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
            nameElement.appendChild(requestDoc.createTextNode(parameters.getName()));
            createApplicationGatewayParametersElement.appendChild(nameElement);
        }

        if (parameters.getSubnets() != null) {
            if (parameters.getSubnets() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getSubnets()).isInitialized()) {
                Element subnetsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Subnets");
                for (String subnetsItem : parameters.getSubnets()) {
                    Element subnetsItemElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Subnet");
                    subnetsItemElement.appendChild(requestDoc.createTextNode(subnetsItem));
                    subnetsSequenceElement.appendChild(subnetsItemElement);
                }
                createApplicationGatewayParametersElement.appendChild(subnetsSequenceElement);
            }
        }

        if (parameters.getVnetName() != null) {
            Element vnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VnetName");
            vnetNameElement.appendChild(requestDoc.createTextNode(parameters.getVnetName()));
            createApplicationGatewayParametersElement.appendChild(vnetNameElement);
        }

        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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Begin Delete Application Gateway operation  deletes Application
    * Gateway with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginDeleteApplicationGatewayAsync(final String gatewayName) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginDeleteApplicationGateway(gatewayName);
            }
        });
    }

    /**
    * The Begin Delete Application Gateway operation  deletes Application
    * Gateway with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginDeleteApplicationGateway(String gatewayName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }

        // 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("gatewayName", gatewayName);
            CloudTracing.enter(invocationId, this, "beginDeleteApplicationGatewayAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        CustomHttpDelete httpRequest = new CustomHttpDelete(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/xml");
        httpRequest.setHeader("x-ms-version", "2015-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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Begin Delete Application Gateway certificate.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @param certificateName Required. The name of the certificate.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginDeleteApplicationGatewayCertificateAsync(final String gatewayName,
            final String certificateName) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginDeleteApplicationGatewayCertificate(gatewayName, certificateName);
            }
        });
    }

    /**
    * The Begin Delete Application Gateway certificate.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @param certificateName Required. The name of the certificate.
    * @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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginDeleteApplicationGatewayCertificate(String gatewayName,
            String certificateName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }
        if (certificateName == null) {
            throw new NullPointerException("certificateName");
        }

        // 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("gatewayName", gatewayName);
            tracingParameters.put("certificateName", certificateName);
            CloudTracing.enter(invocationId, this, "beginDeleteApplicationGatewayCertificateAsync",
                    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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/sslcertificates/";
        url = url + URLEncoder.encode(certificateName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        CustomHttpDelete httpRequest = new CustomHttpDelete(url);

        // Set Headers
        httpRequest.setHeader("Content-Type", "application/xml");
        httpRequest.setHeader("x-ms-version", "2015-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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, null, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Execute Application Gateway Operation executes specified operation on
    * Application Gateway .  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Name of the gateway
    * @param parameters Required. Parameters supplied to the Begin Execute
    * Operation request.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginExecuteOperationAsync(final String gatewayName,
            final ApplicationGatewayOperation parameters) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginExecuteOperation(gatewayName, parameters);
            }
        });
    }

    /**
    * The Execute Application Gateway Operation executes specified operation on
    * Application Gateway .  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Name of the gateway
    * @param parameters Required. Parameters supplied to the Begin Execute
    * Operation request.
    * @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.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginExecuteOperation(String gatewayName,
            ApplicationGatewayOperation parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }
        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("gatewayName", gatewayName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginExecuteOperationAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/Operations";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        HttpPost httpRequest = new HttpPost(url);

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

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

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

        if (parameters.getOperationType() != null) {
            Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "OperationType");
            operationTypeElement.appendChild(requestDoc.createTextNode(parameters.getOperationType()));
            applicationGatewayOperationElement.appendChild(operationTypeElement);
        }

        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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Begin Set Application Gateway config operation  sets the specified
    * config on the application gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param config Required. The Begin Set Application Gateway Config
    * operation  sets the specified config on the application gateway
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginSetConfigAsync(final String gatewayName,
            final ApplicationGatewaySetConfiguration config) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginSetConfig(gatewayName, config);
            }
        });
    }

    /**
    * The Begin Set Application Gateway config operation  sets the specified
    * config on the application gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param config Required. The Begin Set Application Gateway Config
    * operation  sets the specified config on the application gateway
    * @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.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginSetConfig(String gatewayName, ApplicationGatewaySetConfiguration config)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }
        if (config == null) {
            throw new NullPointerException("config");
        }

        // 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("gatewayName", gatewayName);
            tracingParameters.put("config", config);
            CloudTracing.enter(invocationId, this, "beginSetConfigAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/configuration";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        HttpPost httpRequest = new HttpPost(url);

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

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

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

        if (config.getFrontendIPConfigurations() != null) {
            if (config.getFrontendIPConfigurations() instanceof LazyCollection == false
                    || ((LazyCollection) config.getFrontendIPConfigurations()).isInitialized()) {
                Element frontendIPConfigurationsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIPConfigurations");
                for (FrontendIPConfiguration frontendIPConfigurationsItem : config.getFrontendIPConfigurations()) {
                    Element frontendIPConfigurationElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "FrontendIPConfiguration");
                    frontendIPConfigurationsSequenceElement.appendChild(frontendIPConfigurationElement);

                    if (frontendIPConfigurationsItem.getName() != null) {
                        Element nameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                        nameElement.appendChild(requestDoc.createTextNode(frontendIPConfigurationsItem.getName()));
                        frontendIPConfigurationElement.appendChild(nameElement);
                    }

                    if (frontendIPConfigurationsItem.getType() != null) {
                        Element typeElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
                        typeElement.appendChild(requestDoc.createTextNode(frontendIPConfigurationsItem.getType()));
                        frontendIPConfigurationElement.appendChild(typeElement);
                    }

                    if (frontendIPConfigurationsItem.getStaticIPAddress() != null) {
                        Element staticIPAddressElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "StaticIPAddress");
                        staticIPAddressElement.appendChild(
                                requestDoc.createTextNode(frontendIPConfigurationsItem.getStaticIPAddress()));
                        frontendIPConfigurationElement.appendChild(staticIPAddressElement);
                    }
                }
                applicationGatewayConfigurationElement.appendChild(frontendIPConfigurationsSequenceElement);
            }
        }

        if (config.getFrontendPorts() != null) {
            if (config.getFrontendPorts() instanceof LazyCollection == false
                    || ((LazyCollection) config.getFrontendPorts()).isInitialized()) {
                Element frontendPortsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendPorts");
                for (FrontendPort frontendPortsItem : config.getFrontendPorts()) {
                    Element frontendPortElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendPort");
                    frontendPortsSequenceElement.appendChild(frontendPortElement);

                    if (frontendPortsItem.getName() != null) {
                        Element nameElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                        nameElement2.appendChild(requestDoc.createTextNode(frontendPortsItem.getName()));
                        frontendPortElement.appendChild(nameElement2);
                    }

                    Element portElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Port");
                    portElement
                            .appendChild(requestDoc.createTextNode(Integer.toString(frontendPortsItem.getPort())));
                    frontendPortElement.appendChild(portElement);
                }
                applicationGatewayConfigurationElement.appendChild(frontendPortsSequenceElement);
            }
        }

        if (config.getBackendAddressPools() != null) {
            if (config.getBackendAddressPools() instanceof LazyCollection == false
                    || ((LazyCollection) config.getBackendAddressPools()).isInitialized()) {
                Element backendAddressPoolsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendAddressPools");
                for (BackendAddressPool backendAddressPoolsItem : config.getBackendAddressPools()) {
                    Element backendAddressPoolElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendAddressPool");
                    backendAddressPoolsSequenceElement.appendChild(backendAddressPoolElement);

                    if (backendAddressPoolsItem.getName() != null) {
                        Element nameElement3 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                        nameElement3.appendChild(requestDoc.createTextNode(backendAddressPoolsItem.getName()));
                        backendAddressPoolElement.appendChild(nameElement3);
                    }

                    if (backendAddressPoolsItem.getBackendServers() != null) {
                        if (backendAddressPoolsItem.getBackendServers() instanceof LazyCollection == false
                                || ((LazyCollection) backendAddressPoolsItem.getBackendServers()).isInitialized()) {
                            Element iPAddressesSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "IPAddresses");
                            for (BackendServer iPAddressesItem : backendAddressPoolsItem.getBackendServers()) {
                                Element iPAddressElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "IPAddress");
                                iPAddressesSequenceElement.appendChild(iPAddressElement);

                                if (iPAddressesItem.getIPAddress() != null) {
                                    iPAddressElement
                                            .appendChild(requestDoc.createTextNode(iPAddressesItem.getIPAddress()));
                                }
                            }
                            backendAddressPoolElement.appendChild(iPAddressesSequenceElement);
                        }
                    }
                }
                applicationGatewayConfigurationElement.appendChild(backendAddressPoolsSequenceElement);
            }
        }

        if (config.getBackendHttpSettingsList() != null) {
            if (config.getBackendHttpSettingsList() instanceof LazyCollection == false
                    || ((LazyCollection) config.getBackendHttpSettingsList()).isInitialized()) {
                Element backendHttpSettingsListSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendHttpSettingsList");
                for (BackendHttpSettings backendHttpSettingsListItem : config.getBackendHttpSettingsList()) {
                    Element backendHttpSettingsElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendHttpSettings");
                    backendHttpSettingsListSequenceElement.appendChild(backendHttpSettingsElement);

                    if (backendHttpSettingsListItem.getName() != null) {
                        Element nameElement4 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                        nameElement4.appendChild(requestDoc.createTextNode(backendHttpSettingsListItem.getName()));
                        backendHttpSettingsElement.appendChild(nameElement4);
                    }

                    Element portElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                            "Port");
                    portElement2.appendChild(
                            requestDoc.createTextNode(Integer.toString(backendHttpSettingsListItem.getPort())));
                    backendHttpSettingsElement.appendChild(portElement2);

                    if (backendHttpSettingsListItem.getProtocol() != null) {
                        Element protocolElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                        protocolElement.appendChild(
                                requestDoc.createTextNode(backendHttpSettingsListItem.getProtocol().toString()));
                        backendHttpSettingsElement.appendChild(protocolElement);
                    }

                    if (backendHttpSettingsListItem.getCookieBasedAffinity() != null) {
                        Element cookieBasedAffinityElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "CookieBasedAffinity");
                        cookieBasedAffinityElement.appendChild(
                                requestDoc.createTextNode(backendHttpSettingsListItem.getCookieBasedAffinity()));
                        backendHttpSettingsElement.appendChild(cookieBasedAffinityElement);
                    }
                }
                applicationGatewayConfigurationElement.appendChild(backendHttpSettingsListSequenceElement);
            }
        }

        if (config.getHttpListeners() != null) {
            if (config.getHttpListeners() instanceof LazyCollection == false
                    || ((LazyCollection) config.getHttpListeners()).isInitialized()) {
                Element httpListenersSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpListeners");
                for (AGHttpListener httpListenersItem : config.getHttpListeners()) {
                    Element httpListenerElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpListener");
                    httpListenersSequenceElement.appendChild(httpListenerElement);

                    if (httpListenersItem.getName() != null) {
                        Element nameElement5 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                        nameElement5.appendChild(requestDoc.createTextNode(httpListenersItem.getName()));
                        httpListenerElement.appendChild(nameElement5);
                    }

                    if (httpListenersItem.getFrontendIP() != null) {
                        Element frontendIPElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIP");
                        frontendIPElement.appendChild(requestDoc.createTextNode(httpListenersItem.getFrontendIP()));
                        httpListenerElement.appendChild(frontendIPElement);
                    }

                    if (httpListenersItem.getFrontendPort() != null) {
                        Element frontendPortElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendPort");
                        frontendPortElement2
                                .appendChild(requestDoc.createTextNode(httpListenersItem.getFrontendPort()));
                        httpListenerElement.appendChild(frontendPortElement2);
                    }

                    if (httpListenersItem.getProtocol() != null) {
                        Element protocolElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                        protocolElement2
                                .appendChild(requestDoc.createTextNode(httpListenersItem.getProtocol().toString()));
                        httpListenerElement.appendChild(protocolElement2);
                    }

                    if (httpListenersItem.getSslCert() != null) {
                        Element sslCertElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "SslCert");
                        sslCertElement.appendChild(requestDoc.createTextNode(httpListenersItem.getSslCert()));
                        httpListenerElement.appendChild(sslCertElement);
                    }
                }
                applicationGatewayConfigurationElement.appendChild(httpListenersSequenceElement);
            }
        }

        if (config.getHttpLoadBalancingRules() != null) {
            if (config.getHttpLoadBalancingRules() instanceof LazyCollection == false
                    || ((LazyCollection) config.getHttpLoadBalancingRules()).isInitialized()) {
                Element httpLoadBalancingRulesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpLoadBalancingRules");
                for (HttpLoadBalancingRule httpLoadBalancingRulesItem : config.getHttpLoadBalancingRules()) {
                    Element httpLoadBalancingRuleElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "HttpLoadBalancingRule");
                    httpLoadBalancingRulesSequenceElement.appendChild(httpLoadBalancingRuleElement);

                    if (httpLoadBalancingRulesItem.getName() != null) {
                        Element nameElement6 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                        nameElement6.appendChild(requestDoc.createTextNode(httpLoadBalancingRulesItem.getName()));
                        httpLoadBalancingRuleElement.appendChild(nameElement6);
                    }

                    if (httpLoadBalancingRulesItem.getType() != null) {
                        Element typeElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Type");
                        typeElement2.appendChild(requestDoc.createTextNode(httpLoadBalancingRulesItem.getType()));
                        httpLoadBalancingRuleElement.appendChild(typeElement2);
                    }

                    if (httpLoadBalancingRulesItem.getBackendHttpSettings() != null) {
                        Element backendHttpSettingsElement2 = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "BackendHttpSettings");
                        backendHttpSettingsElement2.appendChild(
                                requestDoc.createTextNode(httpLoadBalancingRulesItem.getBackendHttpSettings()));
                        httpLoadBalancingRuleElement.appendChild(backendHttpSettingsElement2);
                    }

                    if (httpLoadBalancingRulesItem.getListener() != null) {
                        Element listenerElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Listener");
                        listenerElement
                                .appendChild(requestDoc.createTextNode(httpLoadBalancingRulesItem.getListener()));
                        httpLoadBalancingRuleElement.appendChild(listenerElement);
                    }

                    if (httpLoadBalancingRulesItem.getBackendAddressPool() != null) {
                        Element backendAddressPoolElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "BackendAddressPool");
                        backendAddressPoolElement2.appendChild(
                                requestDoc.createTextNode(httpLoadBalancingRulesItem.getBackendAddressPool()));
                        httpLoadBalancingRuleElement.appendChild(backendAddressPoolElement2);
                    }
                }
                applicationGatewayConfigurationElement.appendChild(httpLoadBalancingRulesSequenceElement);
            }
        }

        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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Begin Update Application Gateway operation  updates Application
    * Gateway with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param updateParameters Required. Parameters supplied to the Begin
    * UpdateApplication Gateway request.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<GatewayOperationResponse> beginUpdateApplicationGatewayAsync(final String gatewayName,
            final UpdateApplicationGatewayParameters updateParameters) {
        return this.getClient().getExecutorService().submit(new Callable<GatewayOperationResponse>() {
            @Override
            public GatewayOperationResponse call() throws Exception {
                return beginUpdateApplicationGateway(gatewayName, updateParameters);
            }
        });
    }

    /**
    * The Begin Update Application Gateway operation  updates Application
    * Gateway with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param updateParameters Required. Parameters supplied to the Begin
    * UpdateApplication Gateway request.
    * @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.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public GatewayOperationResponse beginUpdateApplicationGateway(String gatewayName,
            UpdateApplicationGatewayParameters updateParameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }
        if (updateParameters == null) {
            throw new NullPointerException("updateParameters");
        }

        // 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("gatewayName", gatewayName);
            tracingParameters.put("updateParameters", updateParameters);
            CloudTracing.enter(invocationId, this, "beginUpdateApplicationGatewayAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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
        HttpPut httpRequest = new HttpPut(url);

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

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

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

        if (updateParameters.getDescription() != null) {
            Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Description");
            descriptionElement.appendChild(requestDoc.createTextNode(updateParameters.getDescription()));
            updateApplicationGatewayParametersElement.appendChild(descriptionElement);
        }

        if (updateParameters.getGatewaySize() != null) {
            Element gatewaySizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "GatewaySize");
            gatewaySizeElement.appendChild(requestDoc.createTextNode(updateParameters.getGatewaySize()));
            updateApplicationGatewayParametersElement.appendChild(gatewaySizeElement);
        }

        Element instanceCountElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "InstanceCount");
        instanceCountElement
                .appendChild(requestDoc.createTextNode(Long.toString(updateParameters.getInstanceCount())));
        updateApplicationGatewayParametersElement.appendChild(instanceCountElement);

        if (updateParameters.getSubnets() != null) {
            if (updateParameters.getSubnets() instanceof LazyCollection == false
                    || ((LazyCollection) updateParameters.getSubnets()).isInitialized()) {
                Element subnetsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Subnets");
                for (String subnetsItem : updateParameters.getSubnets()) {
                    Element subnetsItemElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Subnet");
                    subnetsItemElement.appendChild(requestDoc.createTextNode(subnetsItem));
                    subnetsSequenceElement.appendChild(subnetsItemElement);
                }
                updateApplicationGatewayParametersElement.appendChild(subnetsSequenceElement);
            }
        }

        if (updateParameters.getVnetName() != null) {
            Element vnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VnetName");
            vnetNameElement.appendChild(requestDoc.createTextNode(updateParameters.getVnetName()));
            updateApplicationGatewayParametersElement.appendChild(vnetNameElement);
        }

        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_ACCEPTED) {
                ServiceException ex = ServiceException.createFromXml(httpRequest, requestContent, httpResponse,
                        httpResponse.getEntity());
                if (shouldTrace) {
                    CloudTracing.error(invocationId, ex);
                }
                throw ex;
            }

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

                Element gatewayOperationAsyncResponseElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperationAsyncResponse");
                if (gatewayOperationAsyncResponseElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationAsyncResponseElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setOperationId(idInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Create Application Gateway operation  creates Application Gateway
    * with the specified parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to CreateApplication
    * Gateway request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> createAsync(
            final CreateApplicationGatewayParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return create(parameters);
            }
        });
    }

    /**
    * The Create Application Gateway operation  creates Application Gateway
    * with the specified parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to CreateApplication
    * Gateway request.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @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 response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse create(CreateApplicationGatewayParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException,
            ParserConfigurationException, SAXException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginCreateApplicationGatewayAsync(parameters).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * The Delete Application Gateway operation  deletes Application Gateway
    * with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> deleteAsync(final String gatewayName) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return delete(gatewayName);
            }
        });
    }

    /**
    * The Delete Application Gateway operation  deletes Application Gateway
    * with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @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 response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse delete(String gatewayName) throws InterruptedException,
            ExecutionException, ServiceException, IOException, ParserConfigurationException, SAXException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("gatewayName", gatewayName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginDeleteApplicationGatewayAsync(gatewayName).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * The Delete Application Gateway certificate operation.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @param certificateName Required. The name of the certificate.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> deleteCertificateAsync(final String gatewayName,
            final String certificateName) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return deleteCertificate(gatewayName, certificateName);
            }
        });
    }

    /**
    * The Delete Application Gateway certificate operation.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @param certificateName Required. The name of the certificate.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse deleteCertificate(String gatewayName, String certificateName)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("gatewayName", gatewayName);
            tracingParameters.put("certificateName", certificateName);
            CloudTracing.enter(invocationId, this, "deleteCertificateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginDeleteApplicationGatewayCertificateAsync(gatewayName, certificateName).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * The Execute Application Gateway Operation executes specofoed operation in
    * the Application Gateway.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Name of the gateway
    * @param parameters Required. Parameters supplied to Execute Operation
    * request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> executeOperationAsync(final String gatewayName,
            final ApplicationGatewayOperation parameters) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return executeOperation(gatewayName, parameters);
            }
        });
    }

    /**
    * The Execute Application Gateway Operation executes specofoed operation in
    * the Application Gateway.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Name of the gateway
    * @param parameters Required. Parameters supplied to Execute Operation
    * request.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse executeOperation(String gatewayName,
            ApplicationGatewayOperation parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("gatewayName", gatewayName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "executeOperationAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginExecuteOperationAsync(gatewayName, parameters).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * The Get Application Gateway operation retrieves the application gateway
    * provisioned for the given subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @return The response body contains details of the application gateway.
    */
    @Override
    public Future<ApplicationGatewayGetResponse> getAsync(final String gatewayName) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayGetResponse>() {
            @Override
            public ApplicationGatewayGetResponse call() throws Exception {
                return get(gatewayName);
            }
        });
    }

    /**
    * The Get Application Gateway operation retrieves the application gateway
    * provisioned for the given subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @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 response body contains details of the application gateway.
    */
    @Override
    public ApplicationGatewayGetResponse get(String gatewayName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }

        // 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("gatewayName", gatewayName);
            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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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", "2015-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
            ApplicationGatewayGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ApplicationGatewayGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element applicationGatewayElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ApplicationGateway");
                if (applicationGatewayElement != null) {
                    Element descriptionElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "Description");
                    if (descriptionElement != null) {
                        String descriptionInstance;
                        descriptionInstance = descriptionElement.getTextContent();
                        result.setDescription(descriptionInstance);
                    }

                    Element dnsNameElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "DnsName");
                    if (dnsNameElement != null) {
                        String dnsNameInstance;
                        dnsNameInstance = dnsNameElement.getTextContent();
                        result.setDnsName(dnsNameInstance);
                    }

                    Element gatewaySizeElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "GatewaySize");
                    if (gatewaySizeElement != null) {
                        String gatewaySizeInstance;
                        gatewaySizeInstance = gatewaySizeElement.getTextContent();
                        result.setGatewaySize(gatewaySizeInstance);
                    }

                    Element instanceCountElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "InstanceCount");
                    if (instanceCountElement != null) {
                        long instanceCountInstance;
                        instanceCountInstance = DatatypeConverter.parseLong(instanceCountElement.getTextContent());
                        result.setInstanceCount(instanceCountInstance);
                    }

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

                    Element stateElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "State");
                    if (stateElement != null) {
                        String stateInstance;
                        stateInstance = stateElement.getTextContent();
                        result.setState(stateInstance);
                    }

                    Element subnetsSequenceElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "Subnets");
                    if (subnetsSequenceElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(subnetsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Subnet")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element subnetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(subnetsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Subnet")
                                    .get(i1));
                            result.getSubnets().add(subnetsElement.getTextContent());
                        }
                    }

                    Element vnetNameElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "VnetName");
                    if (vnetNameElement != null) {
                        String vnetNameInstance;
                        vnetNameInstance = vnetNameElement.getTextContent();
                        result.setVnetName(vnetNameInstance);
                    }

                    Element virtualIPsSequenceElement = XmlUtility.getElementByTagNameNS(applicationGatewayElement,
                            "http://schemas.microsoft.com/windowsazure", "VirtualIPs");
                    if (virtualIPsSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(virtualIPsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "VirtualIP")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element virtualIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(virtualIPsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "VirtualIP")
                                    .get(i2));
                            result.getVirtualIPs().add(virtualIPsElement.getTextContent());
                        }
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Get Application Gateway certificate operation retrieves the ssl
    * certificate provisioned for the given gateway.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @param certificateName Required. The name of the certificate.
    * @return Response of GetApplicationGatewayCertificate request.
    */
    @Override
    public Future<ApplicationGatewayGetCertificate> getCertificateAsync(final String gatewayName,
            final String certificateName) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayGetCertificate>() {
            @Override
            public ApplicationGatewayGetCertificate call() throws Exception {
                return getCertificate(gatewayName, certificateName);
            }
        });
    }

    /**
    * The Get Application Gateway certificate operation retrieves the ssl
    * certificate provisioned for the given gateway.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. The name of the gateway.
    * @param certificateName Required. The name of the certificate.
    * @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 Response of GetApplicationGatewayCertificate request.
    */
    @Override
    public ApplicationGatewayGetCertificate getCertificate(String gatewayName, String certificateName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }
        if (certificateName == null) {
            throw new NullPointerException("certificateName");
        }

        // 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("gatewayName", gatewayName);
            tracingParameters.put("certificateName", certificateName);
            CloudTracing.enter(invocationId, this, "getCertificateAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/sslcertificates/";
        url = url + URLEncoder.encode(certificateName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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", "2015-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
            ApplicationGatewayGetCertificate result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ApplicationGatewayGetCertificate();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

                    Element dataElement = XmlUtility.getElementByTagNameNS(applicationGatewayCertificateElement,
                            "http://schemas.microsoft.com/windowsazure", "Data");
                    if (dataElement != null) {
                        String dataInstance;
                        dataInstance = dataElement.getTextContent();
                        result.setData(dataInstance);
                    }

                    Element stateElement = XmlUtility.getElementByTagNameNS(applicationGatewayCertificateElement,
                            "http://schemas.microsoft.com/windowsazure", "State");
                    if (stateElement != null) {
                        String stateInstance;
                        stateInstance = stateElement.getTextContent();
                        result.setState(stateInstance);
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Get Application Gateway Configuration operation retrieves the
    * configuration of the gateway.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. The id  of the gateway.
    * @return The response to a GetApplicationGatewayConfiguation  request.
    */
    @Override
    public Future<ApplicationGatewayGetConfiguration> getConfigAsync(final String gatewayName) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayGetConfiguration>() {
            @Override
            public ApplicationGatewayGetConfiguration call() throws Exception {
                return getConfig(gatewayName);
            }
        });
    }

    /**
    * The Get Application Gateway Configuration operation retrieves the
    * configuration of the gateway.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. The id  of the gateway.
    * @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 response to a GetApplicationGatewayConfiguation  request.
    */
    @Override
    public ApplicationGatewayGetConfiguration getConfig(String gatewayName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }

        // 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("gatewayName", gatewayName);
            CloudTracing.enter(invocationId, this, "getConfigAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/configuration";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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", "2015-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
            ApplicationGatewayGetConfiguration result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ApplicationGatewayGetConfiguration();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element applicationGatewayConfigurationElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ApplicationGatewayConfiguration");
                if (applicationGatewayConfigurationElement != null) {
                    Element frontendIPConfigurationsSequenceElement = XmlUtility.getElementByTagNameNS(
                            applicationGatewayConfigurationElement, "http://schemas.microsoft.com/windowsazure",
                            "FrontendIPConfigurations");
                    if (frontendIPConfigurationsSequenceElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(frontendIPConfigurationsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "FrontendIPConfiguration")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element frontendIPConfigurationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(frontendIPConfigurationsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "FrontendIPConfiguration")
                                    .get(i1));
                            FrontendIPConfiguration frontendIPConfigurationInstance = new FrontendIPConfiguration();
                            result.getFrontendIPConfigurations().add(frontendIPConfigurationInstance);

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

                            Element typeElement = XmlUtility.getElementByTagNameNS(frontendIPConfigurationsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Type");
                            if (typeElement != null) {
                                String typeInstance;
                                typeInstance = typeElement.getTextContent();
                                frontendIPConfigurationInstance.setType(typeInstance);
                            }

                            Element staticIPAddressElement = XmlUtility.getElementByTagNameNS(
                                    frontendIPConfigurationsElement, "http://schemas.microsoft.com/windowsazure",
                                    "StaticIPAddress");
                            if (staticIPAddressElement != null) {
                                String staticIPAddressInstance;
                                staticIPAddressInstance = staticIPAddressElement.getTextContent();
                                frontendIPConfigurationInstance.setStaticIPAddress(staticIPAddressInstance);
                            }
                        }
                    }

                    Element frontendPortsSequenceElement = XmlUtility.getElementByTagNameNS(
                            applicationGatewayConfigurationElement, "http://schemas.microsoft.com/windowsazure",
                            "FrontendPorts");
                    if (frontendPortsSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(frontendPortsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "FrontendPort")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element frontendPortsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(frontendPortsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "FrontendPort")
                                    .get(i2));
                            FrontendPort frontendPortInstance = new FrontendPort();
                            result.getFrontendPorts().add(frontendPortInstance);

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

                            Element portElement = XmlUtility.getElementByTagNameNS(frontendPortsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Port");
                            if (portElement != null) {
                                int portInstance;
                                portInstance = DatatypeConverter.parseInt(portElement.getTextContent());
                                frontendPortInstance.setPort(portInstance);
                            }
                        }
                    }

                    Element backendAddressPoolsSequenceElement = XmlUtility.getElementByTagNameNS(
                            applicationGatewayConfigurationElement, "http://schemas.microsoft.com/windowsazure",
                            "BackendAddressPools");
                    if (backendAddressPoolsSequenceElement != null) {
                        for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(backendAddressPoolsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "BackendAddressPool")
                                .size(); i3 = i3 + 1) {
                            org.w3c.dom.Element backendAddressPoolsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(backendAddressPoolsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "BackendAddressPool")
                                    .get(i3));
                            BackendAddressPool backendAddressPoolInstance = new BackendAddressPool();
                            result.getBackendAddressPools().add(backendAddressPoolInstance);

                            Element nameElement3 = XmlUtility.getElementByTagNameNS(backendAddressPoolsElement,
                                    "http://schemas.microsoft.com/windowsazure", "Name");
                            if (nameElement3 != null) {
                                String nameInstance3;
                                nameInstance3 = nameElement3.getTextContent();
                                backendAddressPoolInstance.setName(nameInstance3);
                            }

                            Element iPAddressesSequenceElement = XmlUtility.getElementByTagNameNS(
                                    backendAddressPoolsElement, "http://schemas.microsoft.com/windowsazure",
                                    "IPAddresses");
                            if (iPAddressesSequenceElement != null) {
                                for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(iPAddressesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "IPAddress")
                                        .size(); i4 = i4 + 1) {
                                    org.w3c.dom.Element iPAddressesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(iPAddressesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "IPAddress")
                                            .get(i4));
                                    BackendServer iPAddressInstance = new BackendServer();
                                    backendAddressPoolInstance.getBackendServers().add(iPAddressInstance);

                                    String iPAddressInstance2;
                                    iPAddressInstance2 = iPAddressesElement.getTextContent();
                                    iPAddressInstance.setIPAddress(iPAddressInstance2);
                                }
                            }
                        }
                    }

                    Element backendHttpSettingsListSequenceElement = XmlUtility.getElementByTagNameNS(
                            applicationGatewayConfigurationElement, "http://schemas.microsoft.com/windowsazure",
                            "BackendHttpSettingsList");
                    if (backendHttpSettingsListSequenceElement != null) {
                        for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(backendHttpSettingsListSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "BackendHttpSettings")
                                .size(); i5 = i5 + 1) {
                            org.w3c.dom.Element backendHttpSettingsListElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(backendHttpSettingsListSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "BackendHttpSettings")
                                    .get(i5));
                            BackendHttpSettings backendHttpSettingsInstance = new BackendHttpSettings();
                            result.getBackendHttpSettingsList().add(backendHttpSettingsInstance);

                            Element nameElement4 = XmlUtility.getElementByTagNameNS(backendHttpSettingsListElement,
                                    "http://schemas.microsoft.com/windowsazure", "Name");
                            if (nameElement4 != null) {
                                String nameInstance4;
                                nameInstance4 = nameElement4.getTextContent();
                                backendHttpSettingsInstance.setName(nameInstance4);
                            }

                            Element portElement2 = XmlUtility.getElementByTagNameNS(backendHttpSettingsListElement,
                                    "http://schemas.microsoft.com/windowsazure", "Port");
                            if (portElement2 != null) {
                                int portInstance2;
                                portInstance2 = DatatypeConverter.parseInt(portElement2.getTextContent());
                                backendHttpSettingsInstance.setPort(portInstance2);
                            }

                            Element protocolElement = XmlUtility.getElementByTagNameNS(
                                    backendHttpSettingsListElement, "http://schemas.microsoft.com/windowsazure",
                                    "Protocol");
                            if (protocolElement != null && protocolElement.getTextContent() != null
                                    && !protocolElement.getTextContent().isEmpty()) {
                                Protocol protocolInstance;
                                protocolInstance = Protocol.valueOf(protocolElement.getTextContent());
                                backendHttpSettingsInstance.setProtocol(protocolInstance);
                            }

                            Element cookieBasedAffinityElement = XmlUtility.getElementByTagNameNS(
                                    backendHttpSettingsListElement, "http://schemas.microsoft.com/windowsazure",
                                    "CookieBasedAffinity");
                            if (cookieBasedAffinityElement != null) {
                                String cookieBasedAffinityInstance;
                                cookieBasedAffinityInstance = cookieBasedAffinityElement.getTextContent();
                                backendHttpSettingsInstance.setCookieBasedAffinity(cookieBasedAffinityInstance);
                            }
                        }
                    }

                    Element httpListenersSequenceElement = XmlUtility.getElementByTagNameNS(
                            applicationGatewayConfigurationElement, "http://schemas.microsoft.com/windowsazure",
                            "HttpListeners");
                    if (httpListenersSequenceElement != null) {
                        for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(httpListenersSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "HttpListener")
                                .size(); i6 = i6 + 1) {
                            org.w3c.dom.Element httpListenersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(httpListenersSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "HttpListener")
                                    .get(i6));
                            AGHttpListener httpListenerInstance = new AGHttpListener();
                            result.getHttpListeners().add(httpListenerInstance);

                            Element nameElement5 = XmlUtility.getElementByTagNameNS(httpListenersElement,
                                    "http://schemas.microsoft.com/windowsazure", "Name");
                            if (nameElement5 != null) {
                                String nameInstance5;
                                nameInstance5 = nameElement5.getTextContent();
                                httpListenerInstance.setName(nameInstance5);
                            }

                            Element frontendIPElement = XmlUtility.getElementByTagNameNS(httpListenersElement,
                                    "http://schemas.microsoft.com/windowsazure", "FrontendIP");
                            if (frontendIPElement != null) {
                                String frontendIPInstance;
                                frontendIPInstance = frontendIPElement.getTextContent();
                                httpListenerInstance.setFrontendIP(frontendIPInstance);
                            }

                            Element frontendPortElement = XmlUtility.getElementByTagNameNS(httpListenersElement,
                                    "http://schemas.microsoft.com/windowsazure", "FrontendPort");
                            if (frontendPortElement != null) {
                                String frontendPortInstance2;
                                frontendPortInstance2 = frontendPortElement.getTextContent();
                                httpListenerInstance.setFrontendPort(frontendPortInstance2);
                            }

                            Element protocolElement2 = XmlUtility.getElementByTagNameNS(httpListenersElement,
                                    "http://schemas.microsoft.com/windowsazure", "Protocol");
                            if (protocolElement2 != null && protocolElement2.getTextContent() != null
                                    && !protocolElement2.getTextContent().isEmpty()) {
                                Protocol protocolInstance2;
                                protocolInstance2 = Protocol.valueOf(protocolElement2.getTextContent());
                                httpListenerInstance.setProtocol(protocolInstance2);
                            }

                            Element sslCertElement = XmlUtility.getElementByTagNameNS(httpListenersElement,
                                    "http://schemas.microsoft.com/windowsazure", "SslCert");
                            if (sslCertElement != null) {
                                String sslCertInstance;
                                sslCertInstance = sslCertElement.getTextContent();
                                httpListenerInstance.setSslCert(sslCertInstance);
                            }
                        }
                    }

                    Element httpLoadBalancingRulesSequenceElement = XmlUtility.getElementByTagNameNS(
                            applicationGatewayConfigurationElement, "http://schemas.microsoft.com/windowsazure",
                            "HttpLoadBalancingRules");
                    if (httpLoadBalancingRulesSequenceElement != null) {
                        for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(httpLoadBalancingRulesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "HttpLoadBalancingRule")
                                .size(); i7 = i7 + 1) {
                            org.w3c.dom.Element httpLoadBalancingRulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(httpLoadBalancingRulesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "HttpLoadBalancingRule")
                                    .get(i7));
                            HttpLoadBalancingRule httpLoadBalancingRuleInstance = new HttpLoadBalancingRule();
                            result.getHttpLoadBalancingRules().add(httpLoadBalancingRuleInstance);

                            Element nameElement6 = XmlUtility.getElementByTagNameNS(httpLoadBalancingRulesElement,
                                    "http://schemas.microsoft.com/windowsazure", "Name");
                            if (nameElement6 != null) {
                                String nameInstance6;
                                nameInstance6 = nameElement6.getTextContent();
                                httpLoadBalancingRuleInstance.setName(nameInstance6);
                            }

                            Element typeElement2 = XmlUtility.getElementByTagNameNS(httpLoadBalancingRulesElement,
                                    "http://schemas.microsoft.com/windowsazure", "Type");
                            if (typeElement2 != null) {
                                String typeInstance2;
                                typeInstance2 = typeElement2.getTextContent();
                                httpLoadBalancingRuleInstance.setType(typeInstance2);
                            }

                            Element backendHttpSettingsElement = XmlUtility.getElementByTagNameNS(
                                    httpLoadBalancingRulesElement, "http://schemas.microsoft.com/windowsazure",
                                    "BackendHttpSettings");
                            if (backendHttpSettingsElement != null) {
                                String backendHttpSettingsInstance2;
                                backendHttpSettingsInstance2 = backendHttpSettingsElement.getTextContent();
                                httpLoadBalancingRuleInstance.setBackendHttpSettings(backendHttpSettingsInstance2);
                            }

                            Element listenerElement = XmlUtility.getElementByTagNameNS(
                                    httpLoadBalancingRulesElement, "http://schemas.microsoft.com/windowsazure",
                                    "Listener");
                            if (listenerElement != null) {
                                String listenerInstance;
                                listenerInstance = listenerElement.getTextContent();
                                httpLoadBalancingRuleInstance.setListener(listenerInstance);
                            }

                            Element backendAddressPoolElement = XmlUtility.getElementByTagNameNS(
                                    httpLoadBalancingRulesElement, "http://schemas.microsoft.com/windowsazure",
                                    "BackendAddressPool");
                            if (backendAddressPoolElement != null) {
                                String backendAddressPoolInstance2;
                                backendAddressPoolInstance2 = backendAddressPoolElement.getTextContent();
                                httpLoadBalancingRuleInstance.setBackendAddressPool(backendAddressPoolInstance2);
                            }
                        }
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Get Operation Status operation returns the status of the specified
    * operation. After calling an asynchronous operation, you can call Get
    * Operation Status to determine whether the operation has succeeded,
    * failed, or is still in progress.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for
    * more information)
    *
    * @param requestId Required. The request ID for the request you wish to
    * track. The request ID is returned in the x-ms-request-id response header
    * for every request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> getOperationStatusAsync(final String requestId) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return getOperationStatus(requestId);
            }
        });
    }

    /**
    * The Get Operation Status operation returns the status of the specified
    * operation. After calling an asynchronous operation, you can call Get
    * Operation Status to determine whether the operation has succeeded,
    * failed, or is still in progress.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx for
    * more information)
    *
    * @param requestId Required. The request ID for the request you wish to
    * track. The request ID is returned in the x-ms-request-id response header
    * for every request.
    * @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 response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse getOperationStatus(String requestId)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (requestId == null) {
            throw new NullPointerException("requestId");
        }

        // 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("requestId", requestId);
            CloudTracing.enter(invocationId, this, "getOperationStatusAsync", 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/networking/operation/";
        url = url + URLEncoder.encode(requestId, "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", "2015-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
            ApplicationGatewayOperationResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ApplicationGatewayOperationResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element gatewayOperationElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "GatewayOperation");
                if (gatewayOperationElement != null) {
                    Element idElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement,
                            "http://schemas.microsoft.com/windowsazure", "ID");
                    if (idElement != null) {
                        String idInstance;
                        idInstance = idElement.getTextContent();
                        result.setId(idInstance);
                    }

                    Element statusElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement,
                            "http://schemas.microsoft.com/windowsazure", "Status");
                    if (statusElement != null && statusElement.getTextContent() != null
                            && !statusElement.getTextContent().isEmpty()) {
                        AsyncOperationStatus statusInstance;
                        statusInstance = AsyncOperationStatus.valueOf(statusElement.getTextContent());
                        result.setStatus(statusInstance);
                    }

                    Element httpStatusCodeElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement,
                            "http://schemas.microsoft.com/windowsazure", "HttpStatusCode");
                    if (httpStatusCodeElement != null && httpStatusCodeElement.getTextContent() != null
                            && !httpStatusCodeElement.getTextContent().isEmpty()) {
                        Integer httpStatusCodeInstance;
                        httpStatusCodeInstance = Integer.valueOf(httpStatusCodeElement.getTextContent());
                        result.setHttpStatusCode(httpStatusCodeInstance);
                    }

                    Element dataElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement,
                            "http://schemas.microsoft.com/windowsazure", "Data");
                    if (dataElement != null) {
                        String dataInstance;
                        dataInstance = dataElement.getTextContent();
                        result.setData(dataInstance);
                    }

                    Element errorElement = XmlUtility.getElementByTagNameNS(gatewayOperationElement,
                            "http://schemas.microsoft.com/windowsazure", "Error");
                    if (errorElement != null) {
                        ApplicationGatewayOperationResponse.ErrorDetails errorInstance = new ApplicationGatewayOperationResponse.ErrorDetails();
                        result.setError(errorInstance);

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

                        Element messageElement = XmlUtility.getElementByTagNameNS(errorElement,
                                "http://schemas.microsoft.com/windowsazure", "Message");
                        if (messageElement != null) {
                            String messageInstance;
                            messageInstance = messageElement.getTextContent();
                            errorInstance.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();
            }
        }
    }

    /**
    * The List Application Gateway operation retrieves all application gateays
    * for the given subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @return The response of ListApplicationGateways request.
    */
    @Override
    public Future<ApplicationGatewayListResponse> listAsync() {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayListResponse>() {
            @Override
            public ApplicationGatewayListResponse call() throws Exception {
                return list();
            }
        });
    }

    /**
    * The List Application Gateway operation retrieves all application gateays
    * for the given subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @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 response of ListApplicationGateways request.
    */
    @Override
    public ApplicationGatewayListResponse list()
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate

        // Tracing
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            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/networking/ApplicationGateways";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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", "2015-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
            ApplicationGatewayListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ApplicationGatewayListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element applicationGatewaysSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ApplicationGateways");
                if (applicationGatewaysSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(applicationGatewaysSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ApplicationGateway")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element applicationGatewaysElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(applicationGatewaysSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ApplicationGateway")
                                .get(i1));
                        ApplicationGatewayGetResponse applicationGatewayInstance = new ApplicationGatewayGetResponse();
                        result.getApplicationGateways().add(applicationGatewayInstance);

                        Element descriptionElement = XmlUtility.getElementByTagNameNS(applicationGatewaysElement,
                                "http://schemas.microsoft.com/windowsazure", "Description");
                        if (descriptionElement != null) {
                            String descriptionInstance;
                            descriptionInstance = descriptionElement.getTextContent();
                            applicationGatewayInstance.setDescription(descriptionInstance);
                        }

                        Element dnsNameElement = XmlUtility.getElementByTagNameNS(applicationGatewaysElement,
                                "http://schemas.microsoft.com/windowsazure", "DnsName");
                        if (dnsNameElement != null) {
                            String dnsNameInstance;
                            dnsNameInstance = dnsNameElement.getTextContent();
                            applicationGatewayInstance.setDnsName(dnsNameInstance);
                        }

                        Element gatewaySizeElement = XmlUtility.getElementByTagNameNS(applicationGatewaysElement,
                                "http://schemas.microsoft.com/windowsazure", "GatewaySize");
                        if (gatewaySizeElement != null) {
                            String gatewaySizeInstance;
                            gatewaySizeInstance = gatewaySizeElement.getTextContent();
                            applicationGatewayInstance.setGatewaySize(gatewaySizeInstance);
                        }

                        Element instanceCountElement = XmlUtility.getElementByTagNameNS(applicationGatewaysElement,
                                "http://schemas.microsoft.com/windowsazure", "InstanceCount");
                        if (instanceCountElement != null) {
                            long instanceCountInstance;
                            instanceCountInstance = DatatypeConverter
                                    .parseLong(instanceCountElement.getTextContent());
                            applicationGatewayInstance.setInstanceCount(instanceCountInstance);
                        }

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

                        Element stateElement = XmlUtility.getElementByTagNameNS(applicationGatewaysElement,
                                "http://schemas.microsoft.com/windowsazure", "State");
                        if (stateElement != null) {
                            String stateInstance;
                            stateInstance = stateElement.getTextContent();
                            applicationGatewayInstance.setState(stateInstance);
                        }

                        Element subnetsSequenceElement = XmlUtility.getElementByTagNameNS(
                                applicationGatewaysElement, "http://schemas.microsoft.com/windowsazure", "Subnets");
                        if (subnetsSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(subnetsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Subnet")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element subnetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(subnetsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "Subnet")
                                        .get(i2));
                                applicationGatewayInstance.getSubnets().add(subnetsElement.getTextContent());
                            }
                        }

                        Element vnetNameElement = XmlUtility.getElementByTagNameNS(applicationGatewaysElement,
                                "http://schemas.microsoft.com/windowsazure", "VnetName");
                        if (vnetNameElement != null) {
                            String vnetNameInstance;
                            vnetNameInstance = vnetNameElement.getTextContent();
                            applicationGatewayInstance.setVnetName(vnetNameInstance);
                        }

                        Element virtualIPsSequenceElement = XmlUtility.getElementByTagNameNS(
                                applicationGatewaysElement, "http://schemas.microsoft.com/windowsazure",
                                "VirtualIPs");
                        if (virtualIPsSequenceElement != null) {
                            for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(virtualIPsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "VirtualIP")
                                    .size(); i3 = i3 + 1) {
                                org.w3c.dom.Element virtualIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(virtualIPsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "VirtualIP")
                                        .get(i3));
                                applicationGatewayInstance.getVirtualIPs().add(virtualIPsElement.getTextContent());
                            }
                        }
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The List Application Gateway certificates.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @return The response to a ListApplicationGatewayCertificate request.
    */
    @Override
    public Future<ApplicationGatewayListCertificate> listCertificateAsync(final String gatewayName) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayListCertificate>() {
            @Override
            public ApplicationGatewayListCertificate call() throws Exception {
                return listCertificate(gatewayName);
            }
        });
    }

    /**
    * The List Application Gateway certificates.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157196.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @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 response to a ListApplicationGatewayCertificate request.
    */
    @Override
    public ApplicationGatewayListCertificate listCertificate(String gatewayName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (gatewayName == null) {
            throw new NullPointerException("gatewayName");
        }

        // 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("gatewayName", gatewayName);
            CloudTracing.enter(invocationId, this, "listCertificateAsync", 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/networking/ApplicationGateways/";
        url = url + URLEncoder.encode(gatewayName, "UTF-8");
        url = url + "/sslcertificates";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("api-version=" + "2015-04-01");
        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", "2015-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
            ApplicationGatewayListCertificate result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new ApplicationGatewayListCertificate();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element applicationGatewayCertificatesSequenceElement = XmlUtility.getElementByTagNameNS(
                        responseDoc, "http://schemas.microsoft.com/windowsazure", "ApplicationGatewayCertificates");
                if (applicationGatewayCertificatesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(applicationGatewayCertificatesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ApplicationGatewayCertificate")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element applicationGatewayCertificatesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(applicationGatewayCertificatesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure",
                                        "ApplicationGatewayCertificate")
                                .get(i1));
                        ApplicationGatewayGetCertificate applicationGatewayCertificateInstance = new ApplicationGatewayGetCertificate();
                        result.getApplicationGatewayCertificates().add(applicationGatewayCertificateInstance);

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

                        Element dataElement = XmlUtility.getElementByTagNameNS(
                                applicationGatewayCertificatesElement, "http://schemas.microsoft.com/windowsazure",
                                "Data");
                        if (dataElement != null) {
                            String dataInstance;
                            dataInstance = dataElement.getTextContent();
                            applicationGatewayCertificateInstance.setData(dataInstance);
                        }

                        Element stateElement = XmlUtility.getElementByTagNameNS(
                                applicationGatewayCertificatesElement, "http://schemas.microsoft.com/windowsazure",
                                "State");
                        if (stateElement != null) {
                            String stateInstance;
                            stateInstance = stateElement.getTextContent();
                            applicationGatewayCertificateInstance.setState(stateInstance);
                        }
                    }
                }

            }
            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();
            }
        }
    }

    /**
    * The Set Application Gateway Config operation  sets the specified config
    * on the application gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param config Required. Parameters supplied to Set Application Gateway
    * config request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> setConfigAsync(final String gatewayName,
            final ApplicationGatewaySetConfiguration config) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return setConfig(gatewayName, config);
            }
        });
    }

    /**
    * The Set Application Gateway Config operation  sets the specified config
    * on the application gateway  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param config Required. Parameters supplied to Set Application Gateway
    * config request.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse setConfig(String gatewayName,
            ApplicationGatewaySetConfiguration config)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("gatewayName", gatewayName);
            tracingParameters.put("config", config);
            CloudTracing.enter(invocationId, this, "setConfigAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginSetConfigAsync(gatewayName, config).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }

    /**
    * The Update Application Gateway operation  updates Application Gateway
    * with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param updateParameters Required. Parameters supplied to
    * UpdateApplication Gateway request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public Future<ApplicationGatewayOperationResponse> updateAsync(final String gatewayName,
            final UpdateApplicationGatewayParameters updateParameters) {
        return this.getClient().getExecutorService().submit(new Callable<ApplicationGatewayOperationResponse>() {
            @Override
            public ApplicationGatewayOperationResponse call() throws Exception {
                return update(gatewayName, updateParameters);
            }
        });
    }

    /**
    * The Update Application Gateway operation  updates Application Gateway
    * with the specified  parameters.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj154114.aspx for
    * more information)
    *
    * @param gatewayName Required. Gateway name
    * @param updateParameters Required. Parameters supplied to
    * UpdateApplication Gateway request.
    * @throws InterruptedException Thrown when a thread is waiting, sleeping,
    * or otherwise occupied, and the thread is interrupted, either before or
    * during the activity. Occasionally a method may wish to test whether the
    * current thread has been interrupted, and if so, to immediately throw
    * this exception. The following code can be used to achieve this effect:
    * @throws ExecutionException Thrown when attempting to retrieve the result
    * of a task that aborted by throwing an exception. This exception can be
    * inspected using the Throwable.getCause() method.
    * @throws ServiceException Thrown if the server returned an error for the
    * request.
    * @throws IOException Thrown if there was an error setting up tracing for
    * the request.
    * @return The response body contains the status of the specified
    * asynchronous operation, indicating whether it has succeeded, is
    * inprogress, or has failed. Note that this status is distinct from the
    * HTTP status code returned for the Get Operation Status operation itself.
    * If the asynchronous operation succeeded, the response body includes the
    * HTTP status code for the successful request.  If the asynchronous
    * operation failed, the response body includes the HTTP status code for
    * the failed request, and also includes error information regarding the
    * failure.
    */
    @Override
    public ApplicationGatewayOperationResponse update(String gatewayName,
            UpdateApplicationGatewayParameters updateParameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        NetworkManagementClient client2 = this.getClient();
        boolean shouldTrace = CloudTracing.getIsEnabled();
        String invocationId = null;
        if (shouldTrace) {
            invocationId = Long.toString(CloudTracing.getNextInvocationId());
            HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
            tracingParameters.put("gatewayName", gatewayName);
            tracingParameters.put("updateParameters", updateParameters);
            CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            GatewayOperationResponse response = client2.getApplicationGatewaysOperations()
                    .beginUpdateApplicationGatewayAsync(gatewayName, updateParameters).get();
            ApplicationGatewayOperationResponse result = client2.getApplicationGatewaysOperations()
                    .getOperationStatusAsync(response.getOperationId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(AsyncOperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getApplicationGatewaysOperations()
                        .getOperationStatusAsync(response.getOperationId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

            if (shouldTrace) {
                CloudTracing.exit(invocationId, result);
            }

            if (result.getStatus() != AsyncOperationStatus.Successful) {
                if (result.getError() != null) {
                    ServiceException ex = new ServiceException(
                            result.getError().getCode() + " : " + result.getError().getMessage());
                    ex.setError(new CloudError());
                    ex.getError().setCode(result.getError().getCode());
                    ex.getError().setMessage(result.getError().getMessage());
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                } else {
                    ServiceException ex = new ServiceException("");
                    if (shouldTrace) {
                        CloudTracing.error(invocationId, ex);
                    }
                    throw ex;
                }
            }

            return result;
        } finally {
            if (client2 != null && shouldTrace) {
                client2.close();
            }
        }
    }
}