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

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.network.ReservedIPOperationsImpl.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.OperationResponse;
import com.microsoft.windowsazure.core.OperationStatus;
import com.microsoft.windowsazure.core.OperationStatusResponse;
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.XmlUtility;
import com.microsoft.windowsazure.exception.CloudError;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.network.models.NetworkReservedIPCreateParameters;
import com.microsoft.windowsazure.management.network.models.NetworkReservedIPGetResponse;
import com.microsoft.windowsazure.management.network.models.NetworkReservedIPListResponse;
import com.microsoft.windowsazure.management.network.models.NetworkReservedIPMobilityParameters;
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.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.InetAddress;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
* The Network Management API includes operations for managing the reserved IPs
* for your subscription.
*/
public class ReservedIPOperationsImpl
        implements ServiceOperations<NetworkManagementClientImpl>, ReservedIPOperations {
    /**
    * Initializes a new instance of the ReservedIPOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    ReservedIPOperationsImpl(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 Associate Reserved IP operation associates a Reserved IP with a
    * service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to associate Reserved IP.
    * @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<OperationStatusResponse> associateAsync(final String reservedIpName,
            final NetworkReservedIPMobilityParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return associate(reservedIpName, parameters);
            }
        });
    }

    /**
    * The Associate Reserved IP operation associates a Reserved IP with a
    * service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to associate Reserved IP.
    * @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 OperationStatusResponse associate(String reservedIpName, NetworkReservedIPMobilityParameters 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("reservedIpName", reservedIpName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "associateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationStatusResponse response = client2.getReservedIPsOperations()
                    .beginAssociatingAsync(reservedIpName, parameters).get();
            if (response.getStatus() == OperationStatus.Succeeded) {
                return response;
            }
            OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

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

            if (result.getStatus() != OperationStatus.Succeeded) {
                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 BeginAssociate begins to associate a Reserved IP with a service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to the Begin associating
    * Reserved IP.
    * @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<OperationStatusResponse> beginAssociatingAsync(final String reservedIpName,
            final NetworkReservedIPMobilityParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return beginAssociating(reservedIpName, parameters);
            }
        });
    }

    /**
    * The BeginAssociate begins to associate a Reserved IP with a service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to the Begin associating
    * Reserved IP.
    * @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 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 OperationStatusResponse beginAssociating(String reservedIpName,
            NetworkReservedIPMobilityParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (reservedIpName == null) {
            throw new NullPointerException("reservedIpName");
        }
        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("reservedIpName", reservedIpName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginAssociatingAsync", 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/reservedips/";
        url = url + URLEncoder.encode(reservedIpName, "UTF-8");
        url = url + "/operations/associate";
        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 reservedIPAssociationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPAssociation");
        requestDoc.appendChild(reservedIPAssociationElement);

        if (parameters.getServiceName() != null) {
            Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ServiceName");
            serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
            reservedIPAssociationElement.appendChild(serviceNameElement);
        }

        if (parameters.getDeploymentName() != null) {
            Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "DeploymentName");
            deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
            reservedIPAssociationElement.appendChild(deploymentNameElement);
        }

        if (parameters.getVirtualIPName() != null) {
            Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VirtualIPName");
            virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
            reservedIPAssociationElement.appendChild(virtualIPNameElement);
        }

        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
            OperationStatusResponse result = null;
            // Deserialize Response
            result = new OperationStatusResponse();
            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 Creating Reserved IP operation creates a reserved IP from your
    * the subscription.
    *
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Reserved IP operation.
    * @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<OperationStatusResponse> beginCreatingAsync(final NetworkReservedIPCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return beginCreating(parameters);
            }
        });
    }

    /**
    * The Begin Creating Reserved IP operation creates a reserved IP from your
    * the subscription.
    *
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Reserved IP operation.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @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 OperationStatusResponse beginCreating(NetworkReservedIPCreateParameters 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, "beginCreatingAsync", 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/reservedips";
        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 reservedIPElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ReservedIP");
        requestDoc.appendChild(reservedIPElement);

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

        if (parameters.getLabel() != null) {
            Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
            labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
            reservedIPElement.appendChild(labelElement);
        }

        if (parameters.getServiceName() != null) {
            Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ServiceName");
            serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
            reservedIPElement.appendChild(serviceNameElement);
        }

        if (parameters.getDeploymentName() != null) {
            Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "DeploymentName");
            deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
            reservedIPElement.appendChild(deploymentNameElement);
        }

        if (parameters.getLocation() != null) {
            Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Location");
            locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
            reservedIPElement.appendChild(locationElement);
        }

        if (parameters.getVirtualIPName() != null) {
            Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VirtualIPName");
            virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
            reservedIPElement.appendChild(virtualIPNameElement);
        }

        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
            OperationStatusResponse result = null;
            // Deserialize Response
            result = new OperationStatusResponse();
            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 Deleting Reserved IP operation removes a reserved IP from your
    * the subscription.
    *
    * @param ipName Required. The name of the reserved IP.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginDeletingAsync(final String ipName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginDeleting(ipName);
            }
        });
    }

    /**
    * The Begin Deleting Reserved IP operation removes a reserved IP from your
    * the subscription.
    *
    * @param ipName Required. The name of the reserved IP.
    * @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 OperationResponse beginDeleting(String ipName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (ipName == null) {
            throw new NullPointerException("ipName");
        }

        // 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("ipName", ipName);
            CloudTracing.enter(invocationId, this, "beginDeletingAsync", 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/reservedips/";
        url = url + URLEncoder.encode(ipName, "UTF-8");
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

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

        // Set Headers
        httpRequest.setHeader("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
            OperationResponse result = null;
            // Deserialize Response
            result = new OperationResponse();
            result.setStatusCode(statusCode);
            if (httpResponse.getHeaders("x-ms-request-id").length > 0) {
                result.setRequestId(httpResponse.getFirstHeader("x-ms-request-id").getValue());
            }

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

    /**
    * The BeginDisassociate begins to disassociate a Reserved IP from a service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to the Begin
    * disassociating Reserved IP.
    * @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<OperationStatusResponse> beginDisassociatingAsync(final String reservedIpName,
            final NetworkReservedIPMobilityParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return beginDisassociating(reservedIpName, parameters);
            }
        });
    }

    /**
    * The BeginDisassociate begins to disassociate a Reserved IP from a service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to the Begin
    * disassociating Reserved IP.
    * @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 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 OperationStatusResponse beginDisassociating(String reservedIpName,
            NetworkReservedIPMobilityParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (reservedIpName == null) {
            throw new NullPointerException("reservedIpName");
        }
        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("reservedIpName", reservedIpName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginDisassociatingAsync", 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/reservedips/";
        url = url + URLEncoder.encode(reservedIpName, "UTF-8");
        url = url + "/operations/disassociate";
        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 reservedIPAssociationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReservedIPAssociation");
        requestDoc.appendChild(reservedIPAssociationElement);

        if (parameters.getServiceName() != null) {
            Element serviceNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ServiceName");
            serviceNameElement.appendChild(requestDoc.createTextNode(parameters.getServiceName()));
            reservedIPAssociationElement.appendChild(serviceNameElement);
        }

        if (parameters.getDeploymentName() != null) {
            Element deploymentNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "DeploymentName");
            deploymentNameElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentName()));
            reservedIPAssociationElement.appendChild(deploymentNameElement);
        }

        if (parameters.getVirtualIPName() != null) {
            Element virtualIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VirtualIPName");
            virtualIPNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualIPName()));
            reservedIPAssociationElement.appendChild(virtualIPNameElement);
        }

        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
            OperationStatusResponse result = null;
            // Deserialize Response
            result = new OperationStatusResponse();
            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 Reserved IP operation creates a reserved IP from your the
    * subscription.
    *
    * @param parameters Required. Parameters supplied to the Create Reserved IP
    * operation.
    * @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<OperationStatusResponse> createAsync(final NetworkReservedIPCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return create(parameters);
            }
        });
    }

    /**
    * The Create Reserved IP operation creates a reserved IP from your the
    * subscription.
    *
    * @param parameters Required. Parameters supplied to the Create Reserved IP
    * operation.
    * @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 OperationStatusResponse create(NetworkReservedIPCreateParameters 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));
            }

            OperationStatusResponse response = client2.getReservedIPsOperations().beginCreatingAsync(parameters)
                    .get();
            if (response.getStatus() == OperationStatus.Succeeded) {
                return response;
            }
            OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

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

            if (result.getStatus() != OperationStatus.Succeeded) {
                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 Reserved IP operation removes a reserved IP from your the
    * subscription.
    *
    * @param ipName Required. The name of the reserved IP.
    * @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<OperationStatusResponse> deleteAsync(final String ipName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return delete(ipName);
            }
        });
    }

    /**
    * The Delete Reserved IP operation removes a reserved IP from your the
    * subscription.
    *
    * @param ipName Required. The name of the reserved IP.
    * @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 OperationStatusResponse delete(String ipName) 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("ipName", ipName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getReservedIPsOperations().beginDeletingAsync(ipName).get();
            OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

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

            if (result.getStatus() != OperationStatus.Succeeded) {
                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 Disassociate Reserved IP operation disassociates a Reserved IP from a
    * service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to disassociate Reserved
    * IP.
    * @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<OperationStatusResponse> disassociateAsync(final String reservedIpName,
            final NetworkReservedIPMobilityParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return disassociate(reservedIpName, parameters);
            }
        });
    }

    /**
    * The Disassociate Reserved IP operation disassociates a Reserved IP from a
    * service.
    *
    * @param reservedIpName Required. The name of the reserved IP.
    * @param parameters Required. Parameters supplied to disassociate Reserved
    * IP.
    * @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 OperationStatusResponse disassociate(String reservedIpName,
            NetworkReservedIPMobilityParameters 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("reservedIpName", reservedIpName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "disassociateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationStatusResponse response = client2.getReservedIPsOperations()
                    .beginDisassociatingAsync(reservedIpName, parameters).get();
            if (response.getStatus() == OperationStatus.Succeeded) {
                return response;
            }
            OperationStatusResponse result = client2.getOperationStatusAsync(response.getRequestId()).get();
            int delayInSeconds = 30;
            if (client2.getLongRunningOperationInitialTimeout() >= 0) {
                delayInSeconds = client2.getLongRunningOperationInitialTimeout();
            }
            while (result.getStatus() != null && result.getStatus().equals(OperationStatus.InProgress)) {
                Thread.sleep(delayInSeconds * 1000);
                result = client2.getOperationStatusAsync(response.getRequestId()).get();
                delayInSeconds = 30;
                if (client2.getLongRunningOperationRetryTimeout() >= 0) {
                    delayInSeconds = client2.getLongRunningOperationRetryTimeout();
                }
            }

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

            if (result.getStatus() != OperationStatus.Succeeded) {
                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 Reserved IP operation retrieves the details for the virtual IP
    * reserved for the subscription.
    *
    * @param ipName Required. The name of the reserved IP to retrieve.
    * @return A reserved IP associated with your subscription.
    */
    @Override
    public Future<NetworkReservedIPGetResponse> getAsync(final String ipName) {
        return this.getClient().getExecutorService().submit(new Callable<NetworkReservedIPGetResponse>() {
            @Override
            public NetworkReservedIPGetResponse call() throws Exception {
                return get(ipName);
            }
        });
    }

    /**
    * The Get Reserved IP operation retrieves the details for the virtual IP
    * reserved for the subscription.
    *
    * @param ipName Required. The name of the reserved IP to retrieve.
    * @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 reserved IP associated with your subscription.
    */
    @Override
    public NetworkReservedIPGetResponse get(String ipName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate
        if (ipName == null) {
            throw new NullPointerException("ipName");
        }

        // 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("ipName", ipName);
            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/reservedips/";
        url = url + URLEncoder.encode(ipName, "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
            NetworkReservedIPGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new NetworkReservedIPGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

                    Element addressElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "Address");
                    if (addressElement != null) {
                        InetAddress addressInstance;
                        addressInstance = InetAddress.getByName(addressElement.getTextContent());
                        result.setAddress(addressInstance);
                    }

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

                    Element labelElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "Label");
                    if (labelElement != null) {
                        String labelInstance;
                        labelInstance = labelElement.getTextContent();
                        result.setLabel(labelInstance);
                    }

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

                    Element inUseElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "InUse");
                    if (inUseElement != null) {
                        boolean inUseInstance;
                        inUseInstance = DatatypeConverter.parseBoolean(inUseElement.getTextContent().toLowerCase());
                        result.setInUse(inUseInstance);
                    }

                    Element serviceNameElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "ServiceName");
                    if (serviceNameElement != null) {
                        String serviceNameInstance;
                        serviceNameInstance = serviceNameElement.getTextContent();
                        result.setServiceName(serviceNameInstance);
                    }

                    Element deploymentNameElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "DeploymentName");
                    if (deploymentNameElement != null) {
                        String deploymentNameInstance;
                        deploymentNameInstance = deploymentNameElement.getTextContent();
                        result.setDeploymentName(deploymentNameInstance);
                    }

                    Element locationElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "Location");
                    if (locationElement != null) {
                        String locationInstance;
                        locationInstance = locationElement.getTextContent();
                        result.setLocation(locationInstance);
                    }

                    Element virtualIPNameElement = XmlUtility.getElementByTagNameNS(reservedIPElement,
                            "http://schemas.microsoft.com/windowsazure", "VirtualIPName");
                    if (virtualIPNameElement != null) {
                        String virtualIPNameInstance;
                        virtualIPNameInstance = virtualIPNameElement.getTextContent();
                        result.setVirtualIPName(virtualIPNameInstance);
                    }
                }

            }
            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 Reserved IP operation retrieves all of the virtual IPs reserved
    * for the subscription.
    *
    * @return The response structure for the Server List operation.
    */
    @Override
    public Future<NetworkReservedIPListResponse> listAsync() {
        return this.getClient().getExecutorService().submit(new Callable<NetworkReservedIPListResponse>() {
            @Override
            public NetworkReservedIPListResponse call() throws Exception {
                return list();
            }
        });
    }

    /**
    * The List Reserved IP operation retrieves all of the virtual IPs reserved
    * for the subscription.
    *
    * @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 structure for the Server List operation.
    */
    @Override
    public NetworkReservedIPListResponse 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/reservedips";
        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
            NetworkReservedIPListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new NetworkReservedIPListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element reservedIPsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "ReservedIPs");
                if (reservedIPsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(reservedIPsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "ReservedIP")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element reservedIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(reservedIPsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ReservedIP")
                                .get(i1));
                        NetworkReservedIPListResponse.ReservedIP reservedIPInstance = new NetworkReservedIPListResponse.ReservedIP();
                        result.getReservedIPs().add(reservedIPInstance);

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

                        Element addressElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "Address");
                        if (addressElement != null) {
                            InetAddress addressInstance;
                            addressInstance = InetAddress.getByName(addressElement.getTextContent());
                            reservedIPInstance.setAddress(addressInstance);
                        }

                        Element idElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "Id");
                        if (idElement != null) {
                            String idInstance;
                            idInstance = idElement.getTextContent();
                            reservedIPInstance.setId(idInstance);
                        }

                        Element labelElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "Label");
                        if (labelElement != null) {
                            String labelInstance;
                            labelInstance = labelElement.getTextContent();
                            reservedIPInstance.setLabel(labelInstance);
                        }

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

                        Element inUseElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "InUse");
                        if (inUseElement != null) {
                            boolean inUseInstance;
                            inUseInstance = DatatypeConverter
                                    .parseBoolean(inUseElement.getTextContent().toLowerCase());
                            reservedIPInstance.setInUse(inUseInstance);
                        }

                        Element serviceNameElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "ServiceName");
                        if (serviceNameElement != null) {
                            String serviceNameInstance;
                            serviceNameInstance = serviceNameElement.getTextContent();
                            reservedIPInstance.setServiceName(serviceNameInstance);
                        }

                        Element deploymentNameElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "DeploymentName");
                        if (deploymentNameElement != null) {
                            String deploymentNameInstance;
                            deploymentNameInstance = deploymentNameElement.getTextContent();
                            reservedIPInstance.setDeploymentName(deploymentNameInstance);
                        }

                        Element locationElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "Location");
                        if (locationElement != null) {
                            String locationInstance;
                            locationInstance = locationElement.getTextContent();
                            reservedIPInstance.setLocation(locationInstance);
                        }

                        Element virtualIPNameElement = XmlUtility.getElementByTagNameNS(reservedIPsElement,
                                "http://schemas.microsoft.com/windowsazure", "VirtualIPName");
                        if (virtualIPNameElement != null) {
                            String virtualIPNameInstance;
                            virtualIPNameInstance = virtualIPNameElement.getTextContent();
                            reservedIPInstance.setVirtualIPName(virtualIPNameInstance);
                        }
                    }
                }

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