com.microsoft.windowsazure.management.compute.VirtualMachineOperationsImpl.java Source code

Java tutorial

Introduction

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

import com.microsoft.windowsazure.core.LazyCollection;
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.Base64;
import com.microsoft.windowsazure.core.utils.CollectionStringBuilder;
import com.microsoft.windowsazure.core.utils.StreamUtils;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.CloudError;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.compute.models.AccessControlListRule;
import com.microsoft.windowsazure.management.compute.models.AdditionalUnattendContentSettings;
import com.microsoft.windowsazure.management.compute.models.ComponentSetting;
import com.microsoft.windowsazure.management.compute.models.ConfigurationSet;
import com.microsoft.windowsazure.management.compute.models.DataDiskConfiguration;
import com.microsoft.windowsazure.management.compute.models.DataVirtualHardDisk;
import com.microsoft.windowsazure.management.compute.models.DnsServer;
import com.microsoft.windowsazure.management.compute.models.DomainJoinCredentials;
import com.microsoft.windowsazure.management.compute.models.DomainJoinProvisioning;
import com.microsoft.windowsazure.management.compute.models.DomainJoinSettings;
import com.microsoft.windowsazure.management.compute.models.EndpointAcl;
import com.microsoft.windowsazure.management.compute.models.IPConfiguration;
import com.microsoft.windowsazure.management.compute.models.InputEndpoint;
import com.microsoft.windowsazure.management.compute.models.LoadBalancer;
import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbe;
import com.microsoft.windowsazure.management.compute.models.LoadBalancerProbeTransportProtocol;
import com.microsoft.windowsazure.management.compute.models.NetworkInterface;
import com.microsoft.windowsazure.management.compute.models.OSVirtualHardDisk;
import com.microsoft.windowsazure.management.compute.models.ResourceExtensionParameterValue;
import com.microsoft.windowsazure.management.compute.models.ResourceExtensionReference;
import com.microsoft.windowsazure.management.compute.models.Role;
import com.microsoft.windowsazure.management.compute.models.SshSettingKeyPair;
import com.microsoft.windowsazure.management.compute.models.SshSettingPublicKey;
import com.microsoft.windowsazure.management.compute.models.SshSettings;
import com.microsoft.windowsazure.management.compute.models.StoredCertificateSettings;
import com.microsoft.windowsazure.management.compute.models.UnattendComponent;
import com.microsoft.windowsazure.management.compute.models.UnattendPassSettings;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureOSImageParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCaptureVMImageParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateDeploymentParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineCreateParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetRemoteDesktopFileResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineGetResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineRoleType;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineShutdownRolesParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineStartRolesParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateLoadBalancedSetParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineUpdateParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineWindowsRemoteManagementListenerType;
import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementListener;
import com.microsoft.windowsazure.management.compute.models.WindowsRemoteManagementSettings;
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.InetAddress;
import java.net.URI;
import java.net.URISyntaxException;
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 Service Management API includes operations for managing the virtual
* machines in your subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx for more
* information)
*/
public class VirtualMachineOperationsImpl
        implements ServiceOperations<ComputeManagementClientImpl>, VirtualMachineOperations {
    /**
    * Initializes a new instance of the VirtualMachineOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    VirtualMachineOperationsImpl(ComputeManagementClientImpl client) {
        this.client = client;
    }

    private ComputeManagementClientImpl client;

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

    /**
    * The Begin Capturing Role operation creates a copy of the operating system
    * virtual hard disk (VHD) that is deployed in the virtual machine, saves
    * the VHD copy in the same storage location as the operating system VHD,
    * and registers the copy as an image in your image gallery. From the
    * captured image, you can create additional customized virtual machines.
    * For more information about images and disks, see Manage Disks and Images
    * at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx.
    * For more information about capturing images, see How to Capture an Image
    * of a Virtual Machine Running Windows Server 2008 R2 at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
    * or How to Capture an Image of a Virtual Machine Running Linux at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Begin Capturing
    * Virtual Machine operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginCapturingOSImageAsync(final String serviceName,
            final String deploymentName, final String virtualMachineName,
            final VirtualMachineCaptureOSImageParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginCapturingOSImage(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * The Begin Capturing Role operation creates a copy of the operating system
    * virtual hard disk (VHD) that is deployed in the virtual machine, saves
    * the VHD copy in the same storage location as the operating system VHD,
    * and registers the copy as an image in your image gallery. From the
    * captured image, you can create additional customized virtual machines.
    * For more information about images and disks, see Manage Disks and Images
    * at http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx.
    * For more information about capturing images, see How to Capture an Image
    * of a Virtual Machine Running Windows Server 2008 R2 at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
    * or How to Capture an Image of a Virtual Machine Running Linux at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Begin Capturing
    * Virtual Machine 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginCapturingOSImage(String serviceName, String deploymentName,
            String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getPostCaptureAction() == null) {
            throw new NullPointerException("parameters.PostCaptureAction");
        }
        if (parameters.getProvisioningConfiguration() != null) {
            if (parameters.getProvisioningConfiguration().getAdditionalUnattendContent() != null) {
                if (parameters.getProvisioningConfiguration().getAdditionalUnattendContent()
                        .getUnattendPasses() != null) {
                    for (UnattendPassSettings unattendPassesParameterItem : parameters
                            .getProvisioningConfiguration().getAdditionalUnattendContent().getUnattendPasses()) {
                        if (unattendPassesParameterItem.getPassName() == null) {
                            throw new NullPointerException(
                                    "parameters.ProvisioningConfiguration.AdditionalUnattendContent.UnattendPasses.PassName");
                        }
                        if (unattendPassesParameterItem.getUnattendComponents() != null) {
                            for (UnattendComponent unattendComponentsParameterItem : unattendPassesParameterItem
                                    .getUnattendComponents()) {
                                if (unattendComponentsParameterItem.getComponentName() == null) {
                                    throw new NullPointerException(
                                            "parameters.ProvisioningConfiguration.AdditionalUnattendContent.UnattendPasses.UnattendComponents.ComponentName");
                                }
                                if (unattendComponentsParameterItem.getUnattendComponentSettings() != null) {
                                    for (ComponentSetting unattendComponentSettingsParameterItem : unattendComponentsParameterItem
                                            .getUnattendComponentSettings()) {
                                        if (unattendComponentSettingsParameterItem.getSettingName() == null) {
                                            throw new NullPointerException(
                                                    "parameters.ProvisioningConfiguration.AdditionalUnattendContent.UnattendPasses.UnattendComponents.UnattendComponentSettings.SettingName");
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            if (parameters.getProvisioningConfiguration().getDomainJoin() != null) {
                if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials() != null) {
                    if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials()
                            .getPassword() == null) {
                        throw new NullPointerException(
                                "parameters.ProvisioningConfiguration.DomainJoin.Credentials.Password");
                    }
                    if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials()
                            .getUserName() == null) {
                        throw new NullPointerException(
                                "parameters.ProvisioningConfiguration.DomainJoin.Credentials.UserName");
                    }
                }
            }
            if (parameters.getProvisioningConfiguration().getHostName() != null
                    && parameters.getProvisioningConfiguration().getHostName().length() < 1) {
                throw new IllegalArgumentException("parameters.ProvisioningConfiguration.HostName");
            }
            if (parameters.getProvisioningConfiguration().getHostName() != null
                    && parameters.getProvisioningConfiguration().getHostName().length() > 64) {
                throw new IllegalArgumentException("parameters.ProvisioningConfiguration.HostName");
            }
            if (parameters.getProvisioningConfiguration().getSshSettings() != null) {
                if (parameters.getProvisioningConfiguration().getSshSettings().getKeyPairs() != null) {
                    for (SshSettingKeyPair keyPairsParameterItem : parameters.getProvisioningConfiguration()
                            .getSshSettings().getKeyPairs()) {
                        if (keyPairsParameterItem.getFingerprint() == null) {
                            throw new NullPointerException(
                                    "parameters.ProvisioningConfiguration.SshSettings.KeyPairs.Fingerprint");
                        }
                        if (keyPairsParameterItem.getPath() == null) {
                            throw new NullPointerException(
                                    "parameters.ProvisioningConfiguration.SshSettings.KeyPairs.Path");
                        }
                    }
                }
                if (parameters.getProvisioningConfiguration().getSshSettings().getPublicKeys() != null) {
                    for (SshSettingPublicKey publicKeysParameterItem : parameters.getProvisioningConfiguration()
                            .getSshSettings().getPublicKeys()) {
                        if (publicKeysParameterItem.getFingerprint() == null) {
                            throw new NullPointerException(
                                    "parameters.ProvisioningConfiguration.SshSettings.PublicKeys.Fingerprint");
                        }
                        if (publicKeysParameterItem.getPath() == null) {
                            throw new NullPointerException(
                                    "parameters.ProvisioningConfiguration.SshSettings.PublicKeys.Path");
                        }
                    }
                }
            }
            if (parameters.getProvisioningConfiguration().getStoredCertificateSettings() != null) {
                for (StoredCertificateSettings storedCertificateSettingsParameterItem : parameters
                        .getProvisioningConfiguration().getStoredCertificateSettings()) {
                    if (storedCertificateSettingsParameterItem.getStoreName() == null) {
                        throw new NullPointerException(
                                "parameters.ProvisioningConfiguration.StoredCertificateSettings.StoreName");
                    }
                    if (storedCertificateSettingsParameterItem.getThumbprint() == null) {
                        throw new NullPointerException(
                                "parameters.ProvisioningConfiguration.StoredCertificateSettings.Thumbprint");
                    }
                }
            }
            if (parameters.getProvisioningConfiguration().getUserName() != null
                    && parameters.getProvisioningConfiguration().getUserName().length() < 1) {
                throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserName");
            }
            if (parameters.getProvisioningConfiguration().getUserName() != null
                    && parameters.getProvisioningConfiguration().getUserName().length() > 32) {
                throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserName");
            }
            if (parameters.getProvisioningConfiguration().getUserPassword() != null
                    && parameters.getProvisioningConfiguration().getUserPassword().length() < 6) {
                throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserPassword");
            }
            if (parameters.getProvisioningConfiguration().getUserPassword() != null
                    && parameters.getProvisioningConfiguration().getUserPassword().length() > 72) {
                throw new IllegalArgumentException("parameters.ProvisioningConfiguration.UserPassword");
            }
            if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement() != null) {
                if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement().getListeners() != null) {
                    for (WindowsRemoteManagementListener listenersParameterItem : parameters
                            .getProvisioningConfiguration().getWindowsRemoteManagement().getListeners()) {
                        if (listenersParameterItem.getListenerType() == null) {
                            throw new NullPointerException(
                                    "parameters.ProvisioningConfiguration.WindowsRemoteManagement.Listeners.ListenerType");
                        }
                    }
                }
            }
        }
        if (parameters.getTargetImageLabel() == null) {
            throw new NullPointerException("parameters.TargetImageLabel");
        }
        if (parameters.getTargetImageName() == null) {
            throw new NullPointerException("parameters.TargetImageName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginCapturingOSImageAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roleinstances/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        url = url + "/Operations";
        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 captureRoleOperationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CaptureRoleOperation");
        requestDoc.appendChild(captureRoleOperationElement);

        Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OperationType");
        operationTypeElement.appendChild(requestDoc.createTextNode("CaptureRoleOperation"));
        captureRoleOperationElement.appendChild(operationTypeElement);

        Element postCaptureActionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PostCaptureAction");
        postCaptureActionElement
                .appendChild(requestDoc.createTextNode(parameters.getPostCaptureAction().toString()));
        captureRoleOperationElement.appendChild(postCaptureActionElement);

        if (parameters.getProvisioningConfiguration() != null) {
            Element provisioningConfigurationElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisioningConfiguration");
            captureRoleOperationElement.appendChild(provisioningConfigurationElement);

            if (parameters.getProvisioningConfiguration().getConfigurationSetType() != null) {
                Element configurationSetTypeElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSetType");
                configurationSetTypeElement.appendChild(requestDoc
                        .createTextNode(parameters.getProvisioningConfiguration().getConfigurationSetType()));
                provisioningConfigurationElement.appendChild(configurationSetTypeElement);
            }

            if (parameters.getProvisioningConfiguration().getInputEndpoints() != null) {
                if (parameters.getProvisioningConfiguration().getInputEndpoints() instanceof LazyCollection == false
                        || ((LazyCollection) parameters.getProvisioningConfiguration().getInputEndpoints())
                                .isInitialized()) {
                    Element inputEndpointsSequenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                    for (InputEndpoint inputEndpointsItem : parameters.getProvisioningConfiguration()
                            .getInputEndpoints()) {
                        Element inputEndpointElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                        inputEndpointsSequenceElement.appendChild(inputEndpointElement);

                        if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) {
                            Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName");
                            loadBalancedEndpointSetNameElement.appendChild(
                                    requestDoc.createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName()));
                            inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement);
                        }

                        if (inputEndpointsItem.getLocalPort() != null) {
                            Element localPortElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                            localPortElement.appendChild(
                                    requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getLocalPort())));
                            inputEndpointElement.appendChild(localPortElement);
                        }

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

                        if (inputEndpointsItem.getPort() != null) {
                            Element portElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                            portElement.appendChild(
                                    requestDoc.createTextNode(Integer.toString(inputEndpointsItem.getPort())));
                            inputEndpointElement.appendChild(portElement);
                        }

                        if (inputEndpointsItem.getLoadBalancerProbe() != null) {
                            Element loadBalancerProbeElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe");
                            inputEndpointElement.appendChild(loadBalancerProbeElement);

                            if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) {
                                Element pathElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                                pathElement.appendChild(requestDoc
                                        .createTextNode(inputEndpointsItem.getLoadBalancerProbe().getPath()));
                                loadBalancerProbeElement.appendChild(pathElement);
                            }

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

                            if (inputEndpointsItem.getLoadBalancerProbe().getProtocol() != null) {
                                Element protocolElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                                protocolElement.appendChild(requestDoc.createTextNode(
                                        ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(
                                                inputEndpointsItem.getLoadBalancerProbe().getProtocol())));
                                loadBalancerProbeElement.appendChild(protocolElement);
                            }

                            if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) {
                                Element intervalInSecondsElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds");
                                intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(
                                        inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds())));
                                loadBalancerProbeElement.appendChild(intervalInSecondsElement);
                            }

                            if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) {
                                Element timeoutInSecondsElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds");
                                timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(
                                        inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds())));
                                loadBalancerProbeElement.appendChild(timeoutInSecondsElement);
                            }
                        }

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

                        if (inputEndpointsItem.getVirtualIPAddress() != null) {
                            Element vipElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Vip");
                            vipElement.appendChild(requestDoc
                                    .createTextNode(inputEndpointsItem.getVirtualIPAddress().getHostAddress()));
                            inputEndpointElement.appendChild(vipElement);
                        }

                        if (inputEndpointsItem.isEnableDirectServerReturn() != null) {
                            Element enableDirectServerReturnElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn");
                            enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean
                                    .toString(inputEndpointsItem.isEnableDirectServerReturn()).toLowerCase()));
                            inputEndpointElement.appendChild(enableDirectServerReturnElement);
                        }

                        if (inputEndpointsItem.getLoadBalancerName() != null) {
                            Element loadBalancerNameElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "LoadBalancerName");
                            loadBalancerNameElement.appendChild(
                                    requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerName()));
                            inputEndpointElement.appendChild(loadBalancerNameElement);
                        }

                        if (inputEndpointsItem.getEndpointAcl() != null) {
                            Element endpointAclElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl");
                            inputEndpointElement.appendChild(endpointAclElement);

                            if (inputEndpointsItem.getEndpointAcl().getRules() != null) {
                                if (inputEndpointsItem.getEndpointAcl()
                                        .getRules() instanceof LazyCollection == false
                                        || ((LazyCollection) inputEndpointsItem.getEndpointAcl().getRules())
                                                .isInitialized()) {
                                    Element rulesSequenceElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Rules");
                                    for (AccessControlListRule rulesItem : inputEndpointsItem.getEndpointAcl()
                                            .getRules()) {
                                        Element ruleElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Rule");
                                        rulesSequenceElement.appendChild(ruleElement);

                                        if (rulesItem.getOrder() != null) {
                                            Element orderElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Order");
                                            orderElement.appendChild(requestDoc
                                                    .createTextNode(Integer.toString(rulesItem.getOrder())));
                                            ruleElement.appendChild(orderElement);
                                        }

                                        if (rulesItem.getAction() != null) {
                                            Element actionElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Action");
                                            actionElement
                                                    .appendChild(requestDoc.createTextNode(rulesItem.getAction()));
                                            ruleElement.appendChild(actionElement);
                                        }

                                        if (rulesItem.getRemoteSubnet() != null) {
                                            Element remoteSubnetElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "RemoteSubnet");
                                            remoteSubnetElement.appendChild(
                                                    requestDoc.createTextNode(rulesItem.getRemoteSubnet()));
                                            ruleElement.appendChild(remoteSubnetElement);
                                        }

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

                        if (inputEndpointsItem.getIdleTimeoutInMinutes() != null) {
                            Element idleTimeoutInMinutesElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                            idleTimeoutInMinutesElement.appendChild(requestDoc.createTextNode(
                                    Integer.toString(inputEndpointsItem.getIdleTimeoutInMinutes())));
                            inputEndpointElement.appendChild(idleTimeoutInMinutesElement);
                        }

                        if (inputEndpointsItem.getLoadBalancerDistribution() != null) {
                            Element loadBalancerDistributionElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "LoadBalancerDistribution");
                            loadBalancerDistributionElement.appendChild(
                                    requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerDistribution()));
                            inputEndpointElement.appendChild(loadBalancerDistributionElement);
                        }

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

            if (parameters.getProvisioningConfiguration().getSubnetNames() != null) {
                if (parameters.getProvisioningConfiguration().getSubnetNames() instanceof LazyCollection == false
                        || ((LazyCollection) parameters.getProvisioningConfiguration().getSubnetNames())
                                .isInitialized()) {
                    Element subnetNamesSequenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames");
                    for (String subnetNamesItem : parameters.getProvisioningConfiguration().getSubnetNames()) {
                        Element subnetNamesItemElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName");
                        subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem));
                        subnetNamesSequenceElement.appendChild(subnetNamesItemElement);
                    }
                    provisioningConfigurationElement.appendChild(subnetNamesSequenceElement);
                }
            }

            if (parameters.getProvisioningConfiguration().getStaticVirtualNetworkIPAddress() != null) {
                Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
                staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(
                        parameters.getProvisioningConfiguration().getStaticVirtualNetworkIPAddress()));
                provisioningConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
            }

            if (parameters.getProvisioningConfiguration().getPublicIPs() != null) {
                if (parameters.getProvisioningConfiguration().getPublicIPs() instanceof LazyCollection == false
                        || ((LazyCollection) parameters.getProvisioningConfiguration().getPublicIPs())
                                .isInitialized()) {
                    Element publicIPsSequenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicIPs");
                    for (ConfigurationSet.PublicIP publicIPsItem : parameters.getProvisioningConfiguration()
                            .getPublicIPs()) {
                        Element publicIPElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicIP");
                        publicIPsSequenceElement.appendChild(publicIPElement);

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

                        if (publicIPsItem.getIdleTimeoutInMinutes() != null) {
                            Element idleTimeoutInMinutesElement2 = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                            idleTimeoutInMinutesElement2.appendChild(requestDoc
                                    .createTextNode(Integer.toString(publicIPsItem.getIdleTimeoutInMinutes())));
                            publicIPElement.appendChild(idleTimeoutInMinutesElement2);
                        }

                        if (publicIPsItem.getDomainNameLabel() != null) {
                            Element domainNameLabelElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "DomainNameLabel");
                            domainNameLabelElement
                                    .appendChild(requestDoc.createTextNode(publicIPsItem.getDomainNameLabel()));
                            publicIPElement.appendChild(domainNameLabelElement);
                        }
                    }
                    provisioningConfigurationElement.appendChild(publicIPsSequenceElement);
                }
            }

            if (parameters.getProvisioningConfiguration().getNetworkInterfaces() != null) {
                if (parameters.getProvisioningConfiguration()
                        .getNetworkInterfaces() instanceof LazyCollection == false
                        || ((LazyCollection) parameters.getProvisioningConfiguration().getNetworkInterfaces())
                                .isInitialized()) {
                    Element networkInterfacesSequenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "NetworkInterfaces");
                    for (NetworkInterface networkInterfacesItem : parameters.getProvisioningConfiguration()
                            .getNetworkInterfaces()) {
                        Element networkInterfaceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "NetworkInterface");
                        networkInterfacesSequenceElement.appendChild(networkInterfaceElement);

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

                        if (networkInterfacesItem.getIPConfigurations() != null) {
                            if (networkInterfacesItem.getIPConfigurations() instanceof LazyCollection == false
                                    || ((LazyCollection) networkInterfacesItem.getIPConfigurations())
                                            .isInitialized()) {
                                Element iPConfigurationsSequenceElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "IPConfigurations");
                                for (IPConfiguration iPConfigurationsItem : networkInterfacesItem
                                        .getIPConfigurations()) {
                                    Element iPConfigurationElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IPConfiguration");
                                    iPConfigurationsSequenceElement.appendChild(iPConfigurationElement);

                                    if (iPConfigurationsItem.getSubnetName() != null) {
                                        Element subnetNameElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "SubnetName");
                                        subnetNameElement.appendChild(
                                                requestDoc.createTextNode(iPConfigurationsItem.getSubnetName()));
                                        iPConfigurationElement.appendChild(subnetNameElement);
                                    }

                                    if (iPConfigurationsItem.getStaticVirtualNetworkIPAddress() != null) {
                                        Element staticVirtualNetworkIPAddressElement2 = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure",
                                                "StaticVirtualNetworkIPAddress");
                                        staticVirtualNetworkIPAddressElement2.appendChild(requestDoc.createTextNode(
                                                iPConfigurationsItem.getStaticVirtualNetworkIPAddress()));
                                        iPConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement2);
                                    }
                                }
                                networkInterfaceElement.appendChild(iPConfigurationsSequenceElement);
                            }
                        }

                        if (networkInterfacesItem.getNetworkSecurityGroup() != null) {
                            Element networkSecurityGroupElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                            networkSecurityGroupElement.appendChild(
                                    requestDoc.createTextNode(networkInterfacesItem.getNetworkSecurityGroup()));
                            networkInterfaceElement.appendChild(networkSecurityGroupElement);
                        }

                        if (networkInterfacesItem.getIPForwarding() != null) {
                            Element iPForwardingElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "IPForwarding");
                            iPForwardingElement.appendChild(
                                    requestDoc.createTextNode(networkInterfacesItem.getIPForwarding()));
                            networkInterfaceElement.appendChild(iPForwardingElement);
                        }
                    }
                    provisioningConfigurationElement.appendChild(networkInterfacesSequenceElement);
                }
            }

            if (parameters.getProvisioningConfiguration().getNetworkSecurityGroup() != null) {
                Element networkSecurityGroupElement2 = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                networkSecurityGroupElement2.appendChild(requestDoc
                        .createTextNode(parameters.getProvisioningConfiguration().getNetworkSecurityGroup()));
                provisioningConfigurationElement.appendChild(networkSecurityGroupElement2);
            }

            if (parameters.getProvisioningConfiguration().getIPForwarding() != null) {
                Element iPForwardingElement2 = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "IPForwarding");
                iPForwardingElement2.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getIPForwarding()));
                provisioningConfigurationElement.appendChild(iPForwardingElement2);
            }

            if (parameters.getProvisioningConfiguration().getComputerName() != null) {
                Element computerNameElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName");
                computerNameElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getComputerName()));
                provisioningConfigurationElement.appendChild(computerNameElement);
            }

            if (parameters.getProvisioningConfiguration().getAdminPassword() != null) {
                Element adminPasswordElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword");
                adminPasswordElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getAdminPassword()));
                provisioningConfigurationElement.appendChild(adminPasswordElement);
            }

            if (parameters.getProvisioningConfiguration().isResetPasswordOnFirstLogon() != null) {
                Element resetPasswordOnFirstLogonElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon");
                resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(
                        Boolean.toString(parameters.getProvisioningConfiguration().isResetPasswordOnFirstLogon())
                                .toLowerCase()));
                provisioningConfigurationElement.appendChild(resetPasswordOnFirstLogonElement);
            }

            if (parameters.getProvisioningConfiguration().isEnableAutomaticUpdates() != null) {
                Element enableAutomaticUpdatesElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates");
                enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(
                        Boolean.toString(parameters.getProvisioningConfiguration().isEnableAutomaticUpdates())
                                .toLowerCase()));
                provisioningConfigurationElement.appendChild(enableAutomaticUpdatesElement);
            }

            if (parameters.getProvisioningConfiguration().getTimeZone() != null) {
                Element timeZoneElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "TimeZone");
                timeZoneElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getTimeZone()));
                provisioningConfigurationElement.appendChild(timeZoneElement);
            }

            if (parameters.getProvisioningConfiguration().getDomainJoin() != null) {
                Element domainJoinElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "DomainJoin");
                provisioningConfigurationElement.appendChild(domainJoinElement);

                if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials() != null) {
                    Element credentialsElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials");
                    domainJoinElement.appendChild(credentialsElement);

                    if (parameters.getProvisioningConfiguration().getDomainJoin().getCredentials()
                            .getDomain() != null) {
                        Element domainElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Domain");
                        domainElement.appendChild(requestDoc.createTextNode(parameters
                                .getProvisioningConfiguration().getDomainJoin().getCredentials().getDomain()));
                        credentialsElement.appendChild(domainElement);
                    }

                    Element usernameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Username");
                    usernameElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration()
                            .getDomainJoin().getCredentials().getUserName()));
                    credentialsElement.appendChild(usernameElement);

                    Element passwordElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Password");
                    passwordElement.appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration()
                            .getDomainJoin().getCredentials().getPassword()));
                    credentialsElement.appendChild(passwordElement);
                }

                if (parameters.getProvisioningConfiguration().getDomainJoin().getDomainToJoin() != null) {
                    Element joinDomainElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain");
                    joinDomainElement.appendChild(requestDoc.createTextNode(
                            parameters.getProvisioningConfiguration().getDomainJoin().getDomainToJoin()));
                    domainJoinElement.appendChild(joinDomainElement);
                }

                if (parameters.getProvisioningConfiguration().getDomainJoin().getLdapMachineObjectOU() != null) {
                    Element machineObjectOUElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MachineObjectOU");
                    machineObjectOUElement.appendChild(requestDoc.createTextNode(
                            parameters.getProvisioningConfiguration().getDomainJoin().getLdapMachineObjectOU()));
                    domainJoinElement.appendChild(machineObjectOUElement);
                }

                if (parameters.getProvisioningConfiguration().getDomainJoin().getProvisioning() != null) {
                    Element provisioningElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning");
                    domainJoinElement.appendChild(provisioningElement);

                    if (parameters.getProvisioningConfiguration().getDomainJoin().getProvisioning()
                            .getAccountData() != null) {
                        Element accountDataElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "AccountData");
                        accountDataElement
                                .appendChild(requestDoc.createTextNode(parameters.getProvisioningConfiguration()
                                        .getDomainJoin().getProvisioning().getAccountData()));
                        provisioningElement.appendChild(accountDataElement);
                    }
                }
            }

            if (parameters.getProvisioningConfiguration().getStoredCertificateSettings() != null) {
                if (parameters.getProvisioningConfiguration()
                        .getStoredCertificateSettings() instanceof LazyCollection == false
                        || ((LazyCollection) parameters.getProvisioningConfiguration()
                                .getStoredCertificateSettings()).isInitialized()) {
                    Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings");
                    for (StoredCertificateSettings storedCertificateSettingsItem : parameters
                            .getProvisioningConfiguration().getStoredCertificateSettings()) {
                        Element certificateSettingElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "CertificateSetting");
                        storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement);

                        Element storeLocationElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "StoreLocation");
                        storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine"));
                        certificateSettingElement.appendChild(storeLocationElement);

                        Element storeNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName");
                        storeNameElement.appendChild(
                                requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName()));
                        certificateSettingElement.appendChild(storeNameElement);

                        Element thumbprintElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint");
                        thumbprintElement.appendChild(
                                requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint()));
                        certificateSettingElement.appendChild(thumbprintElement);
                    }
                    provisioningConfigurationElement.appendChild(storedCertificateSettingsSequenceElement);
                }
            }

            if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement() != null) {
                Element winRMElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "WinRM");
                provisioningConfigurationElement.appendChild(winRMElement);

                if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement().getListeners() != null) {
                    if (parameters.getProvisioningConfiguration().getWindowsRemoteManagement()
                            .getListeners() instanceof LazyCollection == false
                            || ((LazyCollection) parameters.getProvisioningConfiguration()
                                    .getWindowsRemoteManagement().getListeners()).isInitialized()) {
                        Element listenersSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners");
                        for (WindowsRemoteManagementListener listenersItem : parameters
                                .getProvisioningConfiguration().getWindowsRemoteManagement().getListeners()) {
                            Element listenerElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Listener");
                            listenersSequenceElement.appendChild(listenerElement);

                            if (listenersItem.getCertificateThumbprint() != null) {
                                Element certificateThumbprintElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "CertificateThumbprint");
                                certificateThumbprintElement.appendChild(
                                        requestDoc.createTextNode(listenersItem.getCertificateThumbprint()));
                                listenerElement.appendChild(certificateThumbprintElement);
                            }

                            Element protocolElement3 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                            protocolElement3.appendChild(
                                    requestDoc.createTextNode(listenersItem.getListenerType().toString()));
                            listenerElement.appendChild(protocolElement3);
                        }
                        winRMElement.appendChild(listenersSequenceElement);
                    }
                }
            }

            if (parameters.getProvisioningConfiguration().getAdminUserName() != null) {
                Element adminUsernameElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername");
                adminUsernameElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getAdminUserName()));
                provisioningConfigurationElement.appendChild(adminUsernameElement);
            }

            if (parameters.getProvisioningConfiguration().getAdditionalUnattendContent() != null) {
                Element additionalUnattendContentElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "AdditionalUnattendContent");
                provisioningConfigurationElement.appendChild(additionalUnattendContentElement);

                if (parameters.getProvisioningConfiguration().getAdditionalUnattendContent()
                        .getUnattendPasses() != null) {
                    if (parameters.getProvisioningConfiguration().getAdditionalUnattendContent()
                            .getUnattendPasses() instanceof LazyCollection == false
                            || ((LazyCollection) parameters.getProvisioningConfiguration()
                                    .getAdditionalUnattendContent().getUnattendPasses()).isInitialized()) {
                        Element passesSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Passes");
                        for (UnattendPassSettings passesItem : parameters.getProvisioningConfiguration()
                                .getAdditionalUnattendContent().getUnattendPasses()) {
                            Element unattendPassElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "UnattendPass");
                            passesSequenceElement.appendChild(unattendPassElement);

                            Element passNameElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "PassName");
                            passNameElement.appendChild(requestDoc.createTextNode(passesItem.getPassName()));
                            unattendPassElement.appendChild(passNameElement);

                            if (passesItem.getUnattendComponents() != null) {
                                if (passesItem.getUnattendComponents() instanceof LazyCollection == false
                                        || ((LazyCollection) passesItem.getUnattendComponents()).isInitialized()) {
                                    Element componentsSequenceElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Components");
                                    for (UnattendComponent componentsItem : passesItem.getUnattendComponents()) {
                                        Element unattendComponentElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "UnattendComponent");
                                        componentsSequenceElement.appendChild(unattendComponentElement);

                                        Element componentNameElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "ComponentName");
                                        componentNameElement.appendChild(
                                                requestDoc.createTextNode(componentsItem.getComponentName()));
                                        unattendComponentElement.appendChild(componentNameElement);

                                        if (componentsItem.getUnattendComponentSettings() != null) {
                                            if (componentsItem
                                                    .getUnattendComponentSettings() instanceof LazyCollection == false
                                                    || ((LazyCollection) componentsItem
                                                            .getUnattendComponentSettings()).isInitialized()) {
                                                Element componentSettingsSequenceElement = requestDoc
                                                        .createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "ComponentSettings");
                                                for (ComponentSetting componentSettingsItem : componentsItem
                                                        .getUnattendComponentSettings()) {
                                                    Element componentSettingElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "ComponentSetting");
                                                    componentSettingsSequenceElement
                                                            .appendChild(componentSettingElement);

                                                    Element settingNameElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "SettingName");
                                                    settingNameElement.appendChild(requestDoc.createTextNode(
                                                            componentSettingsItem.getSettingName()));
                                                    componentSettingElement.appendChild(settingNameElement);

                                                    if (componentSettingsItem.getContent() != null) {
                                                        Element contentElement = requestDoc.createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "Content");
                                                        contentElement.appendChild(requestDoc
                                                                .createTextNode(Base64.encode(componentSettingsItem
                                                                        .getContent().getBytes())));
                                                        componentSettingElement.appendChild(contentElement);
                                                    }
                                                }
                                                unattendComponentElement
                                                        .appendChild(componentSettingsSequenceElement);
                                            }
                                        }
                                    }
                                    unattendPassElement.appendChild(componentsSequenceElement);
                                }
                            }
                        }
                        additionalUnattendContentElement.appendChild(passesSequenceElement);
                    }
                }
            }

            if (parameters.getProvisioningConfiguration().getHostName() != null) {
                Element hostNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "HostName");
                hostNameElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getHostName()));
                provisioningConfigurationElement.appendChild(hostNameElement);
            }

            if (parameters.getProvisioningConfiguration().getUserName() != null) {
                Element userNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "UserName");
                userNameElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getUserName()));
                provisioningConfigurationElement.appendChild(userNameElement);
            }

            if (parameters.getProvisioningConfiguration().getUserPassword() != null) {
                Element userPasswordElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword");
                userPasswordElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getUserPassword()));
                provisioningConfigurationElement.appendChild(userPasswordElement);
            }

            if (parameters.getProvisioningConfiguration().isDisableSshPasswordAuthentication() != null) {
                Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication");
                disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(Boolean
                        .toString(parameters.getProvisioningConfiguration().isDisableSshPasswordAuthentication())
                        .toLowerCase()));
                provisioningConfigurationElement.appendChild(disableSshPasswordAuthenticationElement);
            }

            if (parameters.getProvisioningConfiguration().getSshSettings() != null) {
                Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "SSH");
                provisioningConfigurationElement.appendChild(sSHElement);

                if (parameters.getProvisioningConfiguration().getSshSettings().getPublicKeys() != null) {
                    if (parameters.getProvisioningConfiguration().getSshSettings()
                            .getPublicKeys() instanceof LazyCollection == false
                            || ((LazyCollection) parameters.getProvisioningConfiguration().getSshSettings()
                                    .getPublicKeys()).isInitialized()) {
                        Element publicKeysSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys");
                        for (SshSettingPublicKey publicKeysItem : parameters.getProvisioningConfiguration()
                                .getSshSettings().getPublicKeys()) {
                            Element publicKeyElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKey");
                            publicKeysSequenceElement.appendChild(publicKeyElement);

                            Element fingerprintElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint");
                            fingerprintElement
                                    .appendChild(requestDoc.createTextNode(publicKeysItem.getFingerprint()));
                            publicKeyElement.appendChild(fingerprintElement);

                            Element pathElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                            pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath()));
                            publicKeyElement.appendChild(pathElement2);
                        }
                        sSHElement.appendChild(publicKeysSequenceElement);
                    }
                }

                if (parameters.getProvisioningConfiguration().getSshSettings().getKeyPairs() != null) {
                    if (parameters.getProvisioningConfiguration().getSshSettings()
                            .getKeyPairs() instanceof LazyCollection == false
                            || ((LazyCollection) parameters.getProvisioningConfiguration().getSshSettings()
                                    .getKeyPairs()).isInitialized()) {
                        Element keyPairsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs");
                        for (SshSettingKeyPair keyPairsItem : parameters.getProvisioningConfiguration()
                                .getSshSettings().getKeyPairs()) {
                            Element keyPairElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPair");
                            keyPairsSequenceElement.appendChild(keyPairElement);

                            Element fingerprintElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Fingerprint");
                            fingerprintElement2
                                    .appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint()));
                            keyPairElement.appendChild(fingerprintElement2);

                            Element pathElement3 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                            pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath()));
                            keyPairElement.appendChild(pathElement3);
                        }
                        sSHElement.appendChild(keyPairsSequenceElement);
                    }
                }
            }

            if (parameters.getProvisioningConfiguration().getCustomData() != null) {
                Element customDataElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "CustomData");
                customDataElement.appendChild(
                        requestDoc.createTextNode(parameters.getProvisioningConfiguration().getCustomData()));
                provisioningConfigurationElement.appendChild(customDataElement);
            }
        }

        Element targetImageLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "TargetImageLabel");
        targetImageLabelElement.appendChild(requestDoc.createTextNode(parameters.getTargetImageLabel()));
        captureRoleOperationElement.appendChild(targetImageLabelElement);

        Element targetImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "TargetImageName");
        targetImageNameElement.appendChild(requestDoc.createTextNode(parameters.getTargetImageName()));
        captureRoleOperationElement.appendChild(targetImageNameElement);

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

    /**
    * Begin capturing role as VM template.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Capture Virtual
    * Machine operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginCapturingVMImageAsync(final String serviceName,
            final String deploymentName, final String virtualMachineName,
            final VirtualMachineCaptureVMImageParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginCapturingVMImage(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * Begin capturing role as VM template.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Capture Virtual
    * Machine 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginCapturingVMImage(String serviceName, String deploymentName,
            String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }
        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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginCapturingVMImageAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roleinstances/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        url = url + "/Operations";
        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 captureRoleAsVMImageOperationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CaptureRoleAsVMImageOperation");
        requestDoc.appendChild(captureRoleAsVMImageOperationElement);

        Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OperationType");
        operationTypeElement.appendChild(requestDoc.createTextNode("CaptureRoleAsVMImageOperation"));
        captureRoleAsVMImageOperationElement.appendChild(operationTypeElement);

        if (parameters.getOSState() != null) {
            Element oSStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "OSState");
            oSStateElement.appendChild(requestDoc.createTextNode(parameters.getOSState()));
            captureRoleAsVMImageOperationElement.appendChild(oSStateElement);
        }

        if (parameters.getVMImageName() != null) {
            Element vMImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VMImageName");
            vMImageNameElement.appendChild(requestDoc.createTextNode(parameters.getVMImageName()));
            captureRoleAsVMImageOperationElement.appendChild(vMImageNameElement);
        }

        if (parameters.getVMImageLabel() != null) {
            Element vMImageLabelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VMImageLabel");
            vMImageLabelElement.appendChild(requestDoc.createTextNode(parameters.getVMImageLabel()));
            captureRoleAsVMImageOperationElement.appendChild(vMImageLabelElement);
        }

        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
            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 Begin Creating Role operation adds a virtual machine to an existing
    * deployment. You can refer to the OSDisk in the Add Role operation in the
    * following ways: Platform/User Image - Set the SourceImageName to a
    * platform or user image. You can optionally specify the DiskName and
    * MediaLink values as part the operation to control the name and location
    * of target disk. When DiskName and MediaLink are specified in this mode,
    * they must not already exist in the system, otherwise a conflict fault is
    * returned; UserDisk - Set DiskName to a user supplied image in image
    * repository. SourceImageName must be set to NULL. All other properties
    * are ignored; or Blob in a Storage Account - Set MediaLink to a blob
    * containing the image. SourceImageName and DiskName are set to NULL.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Virtual Machine operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginCreatingAsync(final String serviceName, final String deploymentName,
            final VirtualMachineCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginCreating(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Begin Creating Role operation adds a virtual machine to an existing
    * deployment. You can refer to the OSDisk in the Add Role operation in the
    * following ways: Platform/User Image - Set the SourceImageName to a
    * platform or user image. You can optionally specify the DiskName and
    * MediaLink values as part the operation to control the name and location
    * of target disk. When DiskName and MediaLink are specified in this mode,
    * they must not already exist in the system, otherwise a conflict fault is
    * returned; UserDisk - Set DiskName to a user supplied image in image
    * repository. SourceImageName must be set to NULL. All other properties
    * are ignored; or Blob in a Storage Account - Set MediaLink to a blob
    * containing the image. SourceImageName and DiskName are set to NULL.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Virtual Machine 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginCreating(String serviceName, String deploymentName,
            VirtualMachineCreateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getConfigurationSets() != null) {
            for (ConfigurationSet configurationSetsParameterItem : parameters.getConfigurationSets()) {
                if (configurationSetsParameterItem.getAdditionalUnattendContent() != null) {
                    if (configurationSetsParameterItem.getAdditionalUnattendContent().getUnattendPasses() != null) {
                        for (UnattendPassSettings unattendPassesParameterItem : configurationSetsParameterItem
                                .getAdditionalUnattendContent().getUnattendPasses()) {
                            if (unattendPassesParameterItem.getPassName() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.PassName");
                            }
                            if (unattendPassesParameterItem.getUnattendComponents() != null) {
                                for (UnattendComponent unattendComponentsParameterItem : unattendPassesParameterItem
                                        .getUnattendComponents()) {
                                    if (unattendComponentsParameterItem.getComponentName() == null) {
                                        throw new NullPointerException(
                                                "parameters.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.UnattendComponents.ComponentName");
                                    }
                                    if (unattendComponentsParameterItem.getUnattendComponentSettings() != null) {
                                        for (ComponentSetting unattendComponentSettingsParameterItem : unattendComponentsParameterItem
                                                .getUnattendComponentSettings()) {
                                            if (unattendComponentSettingsParameterItem.getSettingName() == null) {
                                                throw new NullPointerException(
                                                        "parameters.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.UnattendComponents.UnattendComponentSettings.SettingName");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (configurationSetsParameterItem.getDomainJoin() != null) {
                    if (configurationSetsParameterItem.getDomainJoin().getCredentials() != null) {
                        if (configurationSetsParameterItem.getDomainJoin().getCredentials().getPassword() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.DomainJoin.Credentials.Password");
                        }
                        if (configurationSetsParameterItem.getDomainJoin().getCredentials().getUserName() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.DomainJoin.Credentials.UserName");
                        }
                    }
                }
                if (configurationSetsParameterItem.getHostName() != null
                        && configurationSetsParameterItem.getHostName().length() < 1) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.HostName");
                }
                if (configurationSetsParameterItem.getHostName() != null
                        && configurationSetsParameterItem.getHostName().length() > 64) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.HostName");
                }
                if (configurationSetsParameterItem.getSshSettings() != null) {
                    if (configurationSetsParameterItem.getSshSettings().getKeyPairs() != null) {
                        for (SshSettingKeyPair keyPairsParameterItem : configurationSetsParameterItem
                                .getSshSettings().getKeyPairs()) {
                            if (keyPairsParameterItem.getFingerprint() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.KeyPairs.Fingerprint");
                            }
                            if (keyPairsParameterItem.getPath() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.KeyPairs.Path");
                            }
                        }
                    }
                    if (configurationSetsParameterItem.getSshSettings().getPublicKeys() != null) {
                        for (SshSettingPublicKey publicKeysParameterItem : configurationSetsParameterItem
                                .getSshSettings().getPublicKeys()) {
                            if (publicKeysParameterItem.getFingerprint() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.PublicKeys.Fingerprint");
                            }
                            if (publicKeysParameterItem.getPath() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.PublicKeys.Path");
                            }
                        }
                    }
                }
                if (configurationSetsParameterItem.getStoredCertificateSettings() != null) {
                    for (StoredCertificateSettings storedCertificateSettingsParameterItem : configurationSetsParameterItem
                            .getStoredCertificateSettings()) {
                        if (storedCertificateSettingsParameterItem.getStoreName() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.StoredCertificateSettings.StoreName");
                        }
                        if (storedCertificateSettingsParameterItem.getThumbprint() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.StoredCertificateSettings.Thumbprint");
                        }
                    }
                }
                if (configurationSetsParameterItem.getUserName() != null
                        && configurationSetsParameterItem.getUserName().length() < 1) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserName");
                }
                if (configurationSetsParameterItem.getUserName() != null
                        && configurationSetsParameterItem.getUserName().length() > 32) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserName");
                }
                if (configurationSetsParameterItem.getUserPassword() != null
                        && configurationSetsParameterItem.getUserPassword().length() < 6) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword");
                }
                if (configurationSetsParameterItem.getUserPassword() != null
                        && configurationSetsParameterItem.getUserPassword().length() > 72) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword");
                }
                if (configurationSetsParameterItem.getWindowsRemoteManagement() != null) {
                    if (configurationSetsParameterItem.getWindowsRemoteManagement().getListeners() != null) {
                        for (WindowsRemoteManagementListener listenersParameterItem : configurationSetsParameterItem
                                .getWindowsRemoteManagement().getListeners()) {
                            if (listenersParameterItem.getListenerType() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.WindowsRemoteManagement.Listeners.ListenerType");
                            }
                        }
                    }
                }
            }
        }
        if (parameters.getRoleName() == null) {
            throw new NullPointerException("parameters.RoleName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roles";
        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 persistentVMRoleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "PersistentVMRole");
        requestDoc.appendChild(persistentVMRoleElement);

        Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RoleName");
        roleNameElement.appendChild(requestDoc.createTextNode(parameters.getRoleName()));
        persistentVMRoleElement.appendChild(roleNameElement);

        Element roleTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RoleType");
        roleTypeElement.appendChild(requestDoc.createTextNode("PersistentVMRole"));
        persistentVMRoleElement.appendChild(roleTypeElement);

        if (parameters.getConfigurationSets() != null) {
            if (parameters.getConfigurationSets() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getConfigurationSets()).isInitialized()) {
                Element configurationSetsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSets");
                for (ConfigurationSet configurationSetsItem : parameters.getConfigurationSets()) {
                    Element configurationSetElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSet");
                    configurationSetsSequenceElement.appendChild(configurationSetElement);

                    if (configurationSetsItem.getConfigurationSetType() != null) {
                        Element configurationSetTypeElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType");
                        configurationSetTypeElement.appendChild(
                                requestDoc.createTextNode(configurationSetsItem.getConfigurationSetType()));
                        configurationSetElement.appendChild(configurationSetTypeElement);
                    }

                    if (configurationSetsItem.getInputEndpoints() != null) {
                        if (configurationSetsItem.getInputEndpoints() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getInputEndpoints()).isInitialized()) {
                            Element inputEndpointsSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                            for (InputEndpoint inputEndpointsItem : configurationSetsItem.getInputEndpoints()) {
                                Element inputEndpointElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                                inputEndpointsSequenceElement.appendChild(inputEndpointElement);

                                if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) {
                                    Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancedEndpointSetName");
                                    loadBalancedEndpointSetNameElement.appendChild(requestDoc
                                            .createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName()));
                                    inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement);
                                }

                                if (inputEndpointsItem.getLocalPort() != null) {
                                    Element localPortElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "LocalPort");
                                    localPortElement.appendChild(requestDoc
                                            .createTextNode(Integer.toString(inputEndpointsItem.getLocalPort())));
                                    inputEndpointElement.appendChild(localPortElement);
                                }

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

                                if (inputEndpointsItem.getPort() != null) {
                                    Element portElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                                    portElement.appendChild(requestDoc
                                            .createTextNode(Integer.toString(inputEndpointsItem.getPort())));
                                    inputEndpointElement.appendChild(portElement);
                                }

                                if (inputEndpointsItem.getLoadBalancerProbe() != null) {
                                    Element loadBalancerProbeElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe");
                                    inputEndpointElement.appendChild(loadBalancerProbeElement);

                                    if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) {
                                        Element pathElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Path");
                                        pathElement.appendChild(requestDoc.createTextNode(
                                                inputEndpointsItem.getLoadBalancerProbe().getPath()));
                                        loadBalancerProbeElement.appendChild(pathElement);
                                    }

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

                                    if (inputEndpointsItem.getLoadBalancerProbe().getProtocol() != null) {
                                        Element protocolElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Protocol");
                                        protocolElement
                                                .appendChild(requestDoc.createTextNode(ComputeManagementClientImpl
                                                        .loadBalancerProbeTransportProtocolToString(
                                                                inputEndpointsItem.getLoadBalancerProbe()
                                                                        .getProtocol())));
                                        loadBalancerProbeElement.appendChild(protocolElement);
                                    }

                                    if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) {
                                        Element intervalInSecondsElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds");
                                        intervalInSecondsElement.appendChild(
                                                requestDoc.createTextNode(Integer.toString(inputEndpointsItem
                                                        .getLoadBalancerProbe().getIntervalInSeconds())));
                                        loadBalancerProbeElement.appendChild(intervalInSecondsElement);
                                    }

                                    if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) {
                                        Element timeoutInSecondsElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds");
                                        timeoutInSecondsElement.appendChild(
                                                requestDoc.createTextNode(Integer.toString(inputEndpointsItem
                                                        .getLoadBalancerProbe().getTimeoutInSeconds())));
                                        loadBalancerProbeElement.appendChild(timeoutInSecondsElement);
                                    }
                                }

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

                                if (inputEndpointsItem.getVirtualIPAddress() != null) {
                                    Element vipElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Vip");
                                    vipElement.appendChild(requestDoc.createTextNode(
                                            inputEndpointsItem.getVirtualIPAddress().getHostAddress()));
                                    inputEndpointElement.appendChild(vipElement);
                                }

                                if (inputEndpointsItem.isEnableDirectServerReturn() != null) {
                                    Element enableDirectServerReturnElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "EnableDirectServerReturn");
                                    enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(
                                            Boolean.toString(inputEndpointsItem.isEnableDirectServerReturn())
                                                    .toLowerCase()));
                                    inputEndpointElement.appendChild(enableDirectServerReturnElement);
                                }

                                if (inputEndpointsItem.getLoadBalancerName() != null) {
                                    Element loadBalancerNameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "LoadBalancerName");
                                    loadBalancerNameElement.appendChild(
                                            requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerName()));
                                    inputEndpointElement.appendChild(loadBalancerNameElement);
                                }

                                if (inputEndpointsItem.getEndpointAcl() != null) {
                                    Element endpointAclElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "EndpointAcl");
                                    inputEndpointElement.appendChild(endpointAclElement);

                                    if (inputEndpointsItem.getEndpointAcl().getRules() != null) {
                                        if (inputEndpointsItem.getEndpointAcl()
                                                .getRules() instanceof LazyCollection == false
                                                || ((LazyCollection) inputEndpointsItem.getEndpointAcl().getRules())
                                                        .isInitialized()) {
                                            Element rulesSequenceElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Rules");
                                            for (AccessControlListRule rulesItem : inputEndpointsItem
                                                    .getEndpointAcl().getRules()) {
                                                Element ruleElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure", "Rule");
                                                rulesSequenceElement.appendChild(ruleElement);

                                                if (rulesItem.getOrder() != null) {
                                                    Element orderElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure", "Order");
                                                    orderElement.appendChild(requestDoc.createTextNode(
                                                            Integer.toString(rulesItem.getOrder())));
                                                    ruleElement.appendChild(orderElement);
                                                }

                                                if (rulesItem.getAction() != null) {
                                                    Element actionElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure", "Action");
                                                    actionElement.appendChild(
                                                            requestDoc.createTextNode(rulesItem.getAction()));
                                                    ruleElement.appendChild(actionElement);
                                                }

                                                if (rulesItem.getRemoteSubnet() != null) {
                                                    Element remoteSubnetElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "RemoteSubnet");
                                                    remoteSubnetElement.appendChild(
                                                            requestDoc.createTextNode(rulesItem.getRemoteSubnet()));
                                                    ruleElement.appendChild(remoteSubnetElement);
                                                }

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

                                if (inputEndpointsItem.getIdleTimeoutInMinutes() != null) {
                                    Element idleTimeoutInMinutesElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                                    idleTimeoutInMinutesElement.appendChild(requestDoc.createTextNode(
                                            Integer.toString(inputEndpointsItem.getIdleTimeoutInMinutes())));
                                    inputEndpointElement.appendChild(idleTimeoutInMinutesElement);
                                }

                                if (inputEndpointsItem.getLoadBalancerDistribution() != null) {
                                    Element loadBalancerDistributionElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancerDistribution");
                                    loadBalancerDistributionElement.appendChild(requestDoc
                                            .createTextNode(inputEndpointsItem.getLoadBalancerDistribution()));
                                    inputEndpointElement.appendChild(loadBalancerDistributionElement);
                                }

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

                    if (configurationSetsItem.getSubnetNames() != null) {
                        if (configurationSetsItem.getSubnetNames() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getSubnetNames()).isInitialized()) {
                            Element subnetNamesSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames");
                            for (String subnetNamesItem : configurationSetsItem.getSubnetNames()) {
                                Element subnetNamesItemElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName");
                                subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem));
                                subnetNamesSequenceElement.appendChild(subnetNamesItemElement);
                            }
                            configurationSetElement.appendChild(subnetNamesSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getStaticVirtualNetworkIPAddress() != null) {
                        Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
                        staticVirtualNetworkIPAddressElement.appendChild(requestDoc
                                .createTextNode(configurationSetsItem.getStaticVirtualNetworkIPAddress()));
                        configurationSetElement.appendChild(staticVirtualNetworkIPAddressElement);
                    }

                    if (configurationSetsItem.getPublicIPs() != null) {
                        if (configurationSetsItem.getPublicIPs() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getPublicIPs()).isInitialized()) {
                            Element publicIPsSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicIPs");
                            for (ConfigurationSet.PublicIP publicIPsItem : configurationSetsItem.getPublicIPs()) {
                                Element publicIPElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicIP");
                                publicIPsSequenceElement.appendChild(publicIPElement);

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

                                if (publicIPsItem.getIdleTimeoutInMinutes() != null) {
                                    Element idleTimeoutInMinutesElement2 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                                    idleTimeoutInMinutesElement2.appendChild(requestDoc.createTextNode(
                                            Integer.toString(publicIPsItem.getIdleTimeoutInMinutes())));
                                    publicIPElement.appendChild(idleTimeoutInMinutesElement2);
                                }

                                if (publicIPsItem.getDomainNameLabel() != null) {
                                    Element domainNameLabelElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "DomainNameLabel");
                                    domainNameLabelElement.appendChild(
                                            requestDoc.createTextNode(publicIPsItem.getDomainNameLabel()));
                                    publicIPElement.appendChild(domainNameLabelElement);
                                }
                            }
                            configurationSetElement.appendChild(publicIPsSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getNetworkInterfaces() != null) {
                        if (configurationSetsItem.getNetworkInterfaces() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getNetworkInterfaces())
                                        .isInitialized()) {
                            Element networkInterfacesSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "NetworkInterfaces");
                            for (NetworkInterface networkInterfacesItem : configurationSetsItem
                                    .getNetworkInterfaces()) {
                                Element networkInterfaceElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "NetworkInterface");
                                networkInterfacesSequenceElement.appendChild(networkInterfaceElement);

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

                                if (networkInterfacesItem.getIPConfigurations() != null) {
                                    if (networkInterfacesItem
                                            .getIPConfigurations() instanceof LazyCollection == false
                                            || ((LazyCollection) networkInterfacesItem.getIPConfigurations())
                                                    .isInitialized()) {
                                        Element iPConfigurationsSequenceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "IPConfigurations");
                                        for (IPConfiguration iPConfigurationsItem : networkInterfacesItem
                                                .getIPConfigurations()) {
                                            Element iPConfigurationElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "IPConfiguration");
                                            iPConfigurationsSequenceElement.appendChild(iPConfigurationElement);

                                            if (iPConfigurationsItem.getSubnetName() != null) {
                                                Element subnetNameElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure", "SubnetName");
                                                subnetNameElement.appendChild(requestDoc
                                                        .createTextNode(iPConfigurationsItem.getSubnetName()));
                                                iPConfigurationElement.appendChild(subnetNameElement);
                                            }

                                            if (iPConfigurationsItem.getStaticVirtualNetworkIPAddress() != null) {
                                                Element staticVirtualNetworkIPAddressElement2 = requestDoc
                                                        .createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "StaticVirtualNetworkIPAddress");
                                                staticVirtualNetworkIPAddressElement2
                                                        .appendChild(requestDoc.createTextNode(iPConfigurationsItem
                                                                .getStaticVirtualNetworkIPAddress()));
                                                iPConfigurationElement
                                                        .appendChild(staticVirtualNetworkIPAddressElement2);
                                            }
                                        }
                                        networkInterfaceElement.appendChild(iPConfigurationsSequenceElement);
                                    }
                                }

                                if (networkInterfacesItem.getNetworkSecurityGroup() != null) {
                                    Element networkSecurityGroupElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                                    networkSecurityGroupElement.appendChild(requestDoc
                                            .createTextNode(networkInterfacesItem.getNetworkSecurityGroup()));
                                    networkInterfaceElement.appendChild(networkSecurityGroupElement);
                                }

                                if (networkInterfacesItem.getIPForwarding() != null) {
                                    Element iPForwardingElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IPForwarding");
                                    iPForwardingElement.appendChild(
                                            requestDoc.createTextNode(networkInterfacesItem.getIPForwarding()));
                                    networkInterfaceElement.appendChild(iPForwardingElement);
                                }
                            }
                            configurationSetElement.appendChild(networkInterfacesSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getNetworkSecurityGroup() != null) {
                        Element networkSecurityGroupElement2 = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                        networkSecurityGroupElement2.appendChild(
                                requestDoc.createTextNode(configurationSetsItem.getNetworkSecurityGroup()));
                        configurationSetElement.appendChild(networkSecurityGroupElement2);
                    }

                    if (configurationSetsItem.getIPForwarding() != null) {
                        Element iPForwardingElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "IPForwarding");
                        iPForwardingElement2
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getIPForwarding()));
                        configurationSetElement.appendChild(iPForwardingElement2);
                    }

                    if (configurationSetsItem.getComputerName() != null) {
                        Element computerNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName");
                        computerNameElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getComputerName()));
                        configurationSetElement.appendChild(computerNameElement);
                    }

                    if (configurationSetsItem.getAdminPassword() != null) {
                        Element adminPasswordElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword");
                        adminPasswordElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminPassword()));
                        configurationSetElement.appendChild(adminPasswordElement);
                    }

                    if (configurationSetsItem.isResetPasswordOnFirstLogon() != null) {
                        Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon");
                        resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(Boolean
                                .toString(configurationSetsItem.isResetPasswordOnFirstLogon()).toLowerCase()));
                        configurationSetElement.appendChild(resetPasswordOnFirstLogonElement);
                    }

                    if (configurationSetsItem.isEnableAutomaticUpdates() != null) {
                        Element enableAutomaticUpdatesElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates");
                        enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(
                                Boolean.toString(configurationSetsItem.isEnableAutomaticUpdates()).toLowerCase()));
                        configurationSetElement.appendChild(enableAutomaticUpdatesElement);
                    }

                    if (configurationSetsItem.getTimeZone() != null) {
                        Element timeZoneElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone");
                        timeZoneElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getTimeZone()));
                        configurationSetElement.appendChild(timeZoneElement);
                    }

                    if (configurationSetsItem.getDomainJoin() != null) {
                        Element domainJoinElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin");
                        configurationSetElement.appendChild(domainJoinElement);

                        if (configurationSetsItem.getDomainJoin().getCredentials() != null) {
                            Element credentialsElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials");
                            domainJoinElement.appendChild(credentialsElement);

                            if (configurationSetsItem.getDomainJoin().getCredentials().getDomain() != null) {
                                Element domainElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Domain");
                                domainElement.appendChild(requestDoc.createTextNode(
                                        configurationSetsItem.getDomainJoin().getCredentials().getDomain()));
                                credentialsElement.appendChild(domainElement);
                            }

                            Element usernameElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Username");
                            usernameElement.appendChild(requestDoc.createTextNode(
                                    configurationSetsItem.getDomainJoin().getCredentials().getUserName()));
                            credentialsElement.appendChild(usernameElement);

                            Element passwordElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Password");
                            passwordElement.appendChild(requestDoc.createTextNode(
                                    configurationSetsItem.getDomainJoin().getCredentials().getPassword()));
                            credentialsElement.appendChild(passwordElement);
                        }

                        if (configurationSetsItem.getDomainJoin().getDomainToJoin() != null) {
                            Element joinDomainElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain");
                            joinDomainElement.appendChild(requestDoc
                                    .createTextNode(configurationSetsItem.getDomainJoin().getDomainToJoin()));
                            domainJoinElement.appendChild(joinDomainElement);
                        }

                        if (configurationSetsItem.getDomainJoin().getLdapMachineObjectOU() != null) {
                            Element machineObjectOUElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "MachineObjectOU");
                            machineObjectOUElement.appendChild(requestDoc.createTextNode(
                                    configurationSetsItem.getDomainJoin().getLdapMachineObjectOU()));
                            domainJoinElement.appendChild(machineObjectOUElement);
                        }

                        if (configurationSetsItem.getDomainJoin().getProvisioning() != null) {
                            Element provisioningElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning");
                            domainJoinElement.appendChild(provisioningElement);

                            if (configurationSetsItem.getDomainJoin().getProvisioning().getAccountData() != null) {
                                Element accountDataElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "AccountData");
                                accountDataElement.appendChild(requestDoc.createTextNode(
                                        configurationSetsItem.getDomainJoin().getProvisioning().getAccountData()));
                                provisioningElement.appendChild(accountDataElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getStoredCertificateSettings() != null) {
                        if (configurationSetsItem.getStoredCertificateSettings() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getStoredCertificateSettings())
                                        .isInitialized()) {
                            Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings");
                            for (StoredCertificateSettings storedCertificateSettingsItem : configurationSetsItem
                                    .getStoredCertificateSettings()) {
                                Element certificateSettingElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "CertificateSetting");
                                storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement);

                                Element storeLocationElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "StoreLocation");
                                storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine"));
                                certificateSettingElement.appendChild(storeLocationElement);

                                Element storeNameElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName");
                                storeNameElement.appendChild(
                                        requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName()));
                                certificateSettingElement.appendChild(storeNameElement);

                                Element thumbprintElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint");
                                thumbprintElement.appendChild(
                                        requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint()));
                                certificateSettingElement.appendChild(thumbprintElement);
                            }
                            configurationSetElement.appendChild(storedCertificateSettingsSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getWindowsRemoteManagement() != null) {
                        Element winRMElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM");
                        configurationSetElement.appendChild(winRMElement);

                        if (configurationSetsItem.getWindowsRemoteManagement().getListeners() != null) {
                            if (configurationSetsItem.getWindowsRemoteManagement()
                                    .getListeners() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getWindowsRemoteManagement()
                                            .getListeners()).isInitialized()) {
                                Element listenersSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners");
                                for (WindowsRemoteManagementListener listenersItem : configurationSetsItem
                                        .getWindowsRemoteManagement().getListeners()) {
                                    Element listenerElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Listener");
                                    listenersSequenceElement.appendChild(listenerElement);

                                    if (listenersItem.getCertificateThumbprint() != null) {
                                        Element certificateThumbprintElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure",
                                                "CertificateThumbprint");
                                        certificateThumbprintElement.appendChild(requestDoc
                                                .createTextNode(listenersItem.getCertificateThumbprint()));
                                        listenerElement.appendChild(certificateThumbprintElement);
                                    }

                                    Element protocolElement3 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Protocol");
                                    protocolElement3.appendChild(
                                            requestDoc.createTextNode(listenersItem.getListenerType().toString()));
                                    listenerElement.appendChild(protocolElement3);
                                }
                                winRMElement.appendChild(listenersSequenceElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getAdminUserName() != null) {
                        Element adminUsernameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername");
                        adminUsernameElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminUserName()));
                        configurationSetElement.appendChild(adminUsernameElement);
                    }

                    if (configurationSetsItem.getAdditionalUnattendContent() != null) {
                        Element additionalUnattendContentElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "AdditionalUnattendContent");
                        configurationSetElement.appendChild(additionalUnattendContentElement);

                        if (configurationSetsItem.getAdditionalUnattendContent().getUnattendPasses() != null) {
                            if (configurationSetsItem.getAdditionalUnattendContent()
                                    .getUnattendPasses() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getAdditionalUnattendContent()
                                            .getUnattendPasses()).isInitialized()) {
                                Element passesSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Passes");
                                for (UnattendPassSettings passesItem : configurationSetsItem
                                        .getAdditionalUnattendContent().getUnattendPasses()) {
                                    Element unattendPassElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "UnattendPass");
                                    passesSequenceElement.appendChild(unattendPassElement);

                                    Element passNameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "PassName");
                                    passNameElement
                                            .appendChild(requestDoc.createTextNode(passesItem.getPassName()));
                                    unattendPassElement.appendChild(passNameElement);

                                    if (passesItem.getUnattendComponents() != null) {
                                        if (passesItem.getUnattendComponents() instanceof LazyCollection == false
                                                || ((LazyCollection) passesItem.getUnattendComponents())
                                                        .isInitialized()) {
                                            Element componentsSequenceElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Components");
                                            for (UnattendComponent componentsItem : passesItem
                                                    .getUnattendComponents()) {
                                                Element unattendComponentElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "UnattendComponent");
                                                componentsSequenceElement.appendChild(unattendComponentElement);

                                                Element componentNameElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "ComponentName");
                                                componentNameElement.appendChild(requestDoc
                                                        .createTextNode(componentsItem.getComponentName()));
                                                unattendComponentElement.appendChild(componentNameElement);

                                                if (componentsItem.getUnattendComponentSettings() != null) {
                                                    if (componentsItem
                                                            .getUnattendComponentSettings() instanceof LazyCollection == false
                                                            || ((LazyCollection) componentsItem
                                                                    .getUnattendComponentSettings())
                                                                            .isInitialized()) {
                                                        Element componentSettingsSequenceElement = requestDoc
                                                                .createElementNS(
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "ComponentSettings");
                                                        for (ComponentSetting componentSettingsItem : componentsItem
                                                                .getUnattendComponentSettings()) {
                                                            Element componentSettingElement = requestDoc
                                                                    .createElementNS(
                                                                            "http://schemas.microsoft.com/windowsazure",
                                                                            "ComponentSetting");
                                                            componentSettingsSequenceElement
                                                                    .appendChild(componentSettingElement);

                                                            Element settingNameElement = requestDoc.createElementNS(
                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                    "SettingName");
                                                            settingNameElement.appendChild(
                                                                    requestDoc.createTextNode(componentSettingsItem
                                                                            .getSettingName()));
                                                            componentSettingElement.appendChild(settingNameElement);

                                                            if (componentSettingsItem.getContent() != null) {
                                                                Element contentElement = requestDoc.createElementNS(
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "Content");
                                                                contentElement
                                                                        .appendChild(requestDoc.createTextNode(
                                                                                Base64.encode(componentSettingsItem
                                                                                        .getContent().getBytes())));
                                                                componentSettingElement.appendChild(contentElement);
                                                            }
                                                        }
                                                        unattendComponentElement
                                                                .appendChild(componentSettingsSequenceElement);
                                                    }
                                                }
                                            }
                                            unattendPassElement.appendChild(componentsSequenceElement);
                                        }
                                    }
                                }
                                additionalUnattendContentElement.appendChild(passesSequenceElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getHostName() != null) {
                        Element hostNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostName");
                        hostNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getHostName()));
                        configurationSetElement.appendChild(hostNameElement);
                    }

                    if (configurationSetsItem.getUserName() != null) {
                        Element userNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "UserName");
                        userNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserName()));
                        configurationSetElement.appendChild(userNameElement);
                    }

                    if (configurationSetsItem.getUserPassword() != null) {
                        Element userPasswordElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword");
                        userPasswordElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getUserPassword()));
                        configurationSetElement.appendChild(userPasswordElement);
                    }

                    if (configurationSetsItem.isDisableSshPasswordAuthentication() != null) {
                        Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication");
                        disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(
                                Boolean.toString(configurationSetsItem.isDisableSshPasswordAuthentication())
                                        .toLowerCase()));
                        configurationSetElement.appendChild(disableSshPasswordAuthenticationElement);
                    }

                    if (configurationSetsItem.getSshSettings() != null) {
                        Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                                "SSH");
                        configurationSetElement.appendChild(sSHElement);

                        if (configurationSetsItem.getSshSettings().getPublicKeys() != null) {
                            if (configurationSetsItem.getSshSettings()
                                    .getPublicKeys() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getSshSettings().getPublicKeys())
                                            .isInitialized()) {
                                Element publicKeysSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys");
                                for (SshSettingPublicKey publicKeysItem : configurationSetsItem.getSshSettings()
                                        .getPublicKeys()) {
                                    Element publicKeyElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "PublicKey");
                                    publicKeysSequenceElement.appendChild(publicKeyElement);

                                    Element fingerprintElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Fingerprint");
                                    fingerprintElement.appendChild(
                                            requestDoc.createTextNode(publicKeysItem.getFingerprint()));
                                    publicKeyElement.appendChild(fingerprintElement);

                                    Element pathElement2 = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                                    pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath()));
                                    publicKeyElement.appendChild(pathElement2);
                                }
                                sSHElement.appendChild(publicKeysSequenceElement);
                            }
                        }

                        if (configurationSetsItem.getSshSettings().getKeyPairs() != null) {
                            if (configurationSetsItem.getSshSettings()
                                    .getKeyPairs() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getSshSettings().getKeyPairs())
                                            .isInitialized()) {
                                Element keyPairsSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs");
                                for (SshSettingKeyPair keyPairsItem : configurationSetsItem.getSshSettings()
                                        .getKeyPairs()) {
                                    Element keyPairElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "KeyPair");
                                    keyPairsSequenceElement.appendChild(keyPairElement);

                                    Element fingerprintElement2 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Fingerprint");
                                    fingerprintElement2
                                            .appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint()));
                                    keyPairElement.appendChild(fingerprintElement2);

                                    Element pathElement3 = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                                    pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath()));
                                    keyPairElement.appendChild(pathElement3);
                                }
                                sSHElement.appendChild(keyPairsSequenceElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getCustomData() != null) {
                        Element customDataElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData");
                        customDataElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getCustomData()));
                        configurationSetElement.appendChild(customDataElement);
                    }
                }
                persistentVMRoleElement.appendChild(configurationSetsSequenceElement);
            }
        }

        if (parameters.getResourceExtensionReferences() != null) {
            if (parameters.getResourceExtensionReferences() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getResourceExtensionReferences()).isInitialized()) {
                Element resourceExtensionReferencesSequenceElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences");
                for (ResourceExtensionReference resourceExtensionReferencesItem : parameters
                        .getResourceExtensionReferences()) {
                    Element resourceExtensionReferenceElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference");
                    resourceExtensionReferencesSequenceElement.appendChild(resourceExtensionReferenceElement);

                    if (resourceExtensionReferencesItem.getReferenceName() != null) {
                        Element referenceNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReferenceName");
                        referenceNameElement.appendChild(
                                requestDoc.createTextNode(resourceExtensionReferencesItem.getReferenceName()));
                        resourceExtensionReferenceElement.appendChild(referenceNameElement);
                    }

                    if (resourceExtensionReferencesItem.getPublisher() != null) {
                        Element publisherElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Publisher");
                        publisherElement.appendChild(
                                requestDoc.createTextNode(resourceExtensionReferencesItem.getPublisher()));
                        resourceExtensionReferenceElement.appendChild(publisherElement);
                    }

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

                    if (resourceExtensionReferencesItem.getVersion() != null) {
                        Element versionElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
                        versionElement.appendChild(
                                requestDoc.createTextNode(resourceExtensionReferencesItem.getVersion()));
                        resourceExtensionReferenceElement.appendChild(versionElement);
                    }

                    if (resourceExtensionReferencesItem.getResourceExtensionParameterValues() != null) {
                        if (resourceExtensionReferencesItem
                                .getResourceExtensionParameterValues() instanceof LazyCollection == false
                                || ((LazyCollection) resourceExtensionReferencesItem
                                        .getResourceExtensionParameterValues()).isInitialized()) {
                            Element resourceExtensionParameterValuesSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure",
                                    "ResourceExtensionParameterValues");
                            for (ResourceExtensionParameterValue resourceExtensionParameterValuesItem : resourceExtensionReferencesItem
                                    .getResourceExtensionParameterValues()) {
                                Element resourceExtensionParameterValueElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure",
                                        "ResourceExtensionParameterValue");
                                resourceExtensionParameterValuesSequenceElement
                                        .appendChild(resourceExtensionParameterValueElement);

                                if (resourceExtensionParameterValuesItem.getKey() != null) {
                                    Element keyElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Key");
                                    keyElement.appendChild(requestDoc
                                            .createTextNode(resourceExtensionParameterValuesItem.getKey()));
                                    resourceExtensionParameterValueElement.appendChild(keyElement);
                                }

                                if (resourceExtensionParameterValuesItem.getValue() != null) {
                                    Element valueElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                                    valueElement.appendChild(requestDoc.createTextNode(Base64
                                            .encode(resourceExtensionParameterValuesItem.getValue().getBytes())));
                                    resourceExtensionParameterValueElement.appendChild(valueElement);
                                }

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

                    if (resourceExtensionReferencesItem.getState() != null) {
                        Element stateElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "State");
                        stateElement
                                .appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getState()));
                        resourceExtensionReferenceElement.appendChild(stateElement);
                    }

                    if (resourceExtensionReferencesItem.isForceUpdate() != null) {
                        Element forceUpdateElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ForceUpdate");
                        forceUpdateElement.appendChild(requestDoc.createTextNode(
                                Boolean.toString(resourceExtensionReferencesItem.isForceUpdate()).toLowerCase()));
                        resourceExtensionReferenceElement.appendChild(forceUpdateElement);
                    }
                }
                persistentVMRoleElement.appendChild(resourceExtensionReferencesSequenceElement);
            }
        }

        if (parameters.getVMImageName() != null) {
            Element vMImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VMImageName");
            vMImageNameElement.appendChild(requestDoc.createTextNode(parameters.getVMImageName()));
            persistentVMRoleElement.appendChild(vMImageNameElement);
        }

        if (parameters.getMediaLocation() != null) {
            Element mediaLocationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "MediaLocation");
            mediaLocationElement.appendChild(requestDoc.createTextNode(parameters.getMediaLocation().toString()));
            persistentVMRoleElement.appendChild(mediaLocationElement);
        }

        if (parameters.getAvailabilitySetName() != null) {
            Element availabilitySetNameElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilitySetName");
            availabilitySetNameElement.appendChild(requestDoc.createTextNode(parameters.getAvailabilitySetName()));
            persistentVMRoleElement.appendChild(availabilitySetNameElement);
        }

        if (parameters.getDataVirtualHardDisks() != null) {
            if (parameters.getDataVirtualHardDisks() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getDataVirtualHardDisks()).isInitialized()) {
                Element dataVirtualHardDisksSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks");
                for (DataVirtualHardDisk dataVirtualHardDisksItem : parameters.getDataVirtualHardDisks()) {
                    Element dataVirtualHardDiskElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk");
                    dataVirtualHardDisksSequenceElement.appendChild(dataVirtualHardDiskElement);

                    if (dataVirtualHardDisksItem.getHostCaching() != null) {
                        Element hostCachingElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching");
                        hostCachingElement
                                .appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getHostCaching()));
                        dataVirtualHardDiskElement.appendChild(hostCachingElement);
                    }

                    if (dataVirtualHardDisksItem.getLabel() != null) {
                        Element diskLabelElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel");
                        diskLabelElement
                                .appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getLabel()));
                        dataVirtualHardDiskElement.appendChild(diskLabelElement);
                    }

                    if (dataVirtualHardDisksItem.getName() != null) {
                        Element diskNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName");
                        diskNameElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getName()));
                        dataVirtualHardDiskElement.appendChild(diskNameElement);
                    }

                    if (dataVirtualHardDisksItem.getLogicalUnitNumber() != null) {
                        Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                                "Lun");
                        lunElement.appendChild(requestDoc
                                .createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalUnitNumber())));
                        dataVirtualHardDiskElement.appendChild(lunElement);
                    }

                    if (dataVirtualHardDisksItem.getLogicalDiskSizeInGB() != null) {
                        Element logicalDiskSizeInGBElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB");
                        logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(
                                Integer.toString(dataVirtualHardDisksItem.getLogicalDiskSizeInGB())));
                        dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement);
                    }

                    if (dataVirtualHardDisksItem.getMediaLink() != null) {
                        Element mediaLinkElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink");
                        mediaLinkElement.appendChild(
                                requestDoc.createTextNode(dataVirtualHardDisksItem.getMediaLink().toString()));
                        dataVirtualHardDiskElement.appendChild(mediaLinkElement);
                    }

                    if (dataVirtualHardDisksItem.getSourceMediaLink() != null) {
                        Element sourceMediaLinkElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceMediaLink");
                        sourceMediaLinkElement.appendChild(requestDoc
                                .createTextNode(dataVirtualHardDisksItem.getSourceMediaLink().toString()));
                        dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement);
                    }

                    if (dataVirtualHardDisksItem.getIOType() != null) {
                        Element iOTypeElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "IOType");
                        iOTypeElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getIOType()));
                        dataVirtualHardDiskElement.appendChild(iOTypeElement);
                    }
                }
                persistentVMRoleElement.appendChild(dataVirtualHardDisksSequenceElement);
            }
        }

        if (parameters.getOSVirtualHardDisk() != null) {
            Element oSVirtualHardDiskElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk");
            persistentVMRoleElement.appendChild(oSVirtualHardDiskElement);

            if (parameters.getOSVirtualHardDisk().getHostCaching() != null) {
                Element hostCachingElement2 = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching");
                hostCachingElement2
                        .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getHostCaching()));
                oSVirtualHardDiskElement.appendChild(hostCachingElement2);
            }

            if (parameters.getOSVirtualHardDisk().getLabel() != null) {
                Element diskLabelElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "DiskLabel");
                diskLabelElement2
                        .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getLabel()));
                oSVirtualHardDiskElement.appendChild(diskLabelElement2);
            }

            if (parameters.getOSVirtualHardDisk().getName() != null) {
                Element diskNameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "DiskName");
                diskNameElement2
                        .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getName()));
                oSVirtualHardDiskElement.appendChild(diskNameElement2);
            }

            if (parameters.getOSVirtualHardDisk().getMediaLink() != null) {
                Element mediaLinkElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "MediaLink");
                mediaLinkElement2.appendChild(
                        requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getMediaLink().toString()));
                oSVirtualHardDiskElement.appendChild(mediaLinkElement2);
            }

            if (parameters.getOSVirtualHardDisk().getSourceImageName() != null) {
                Element sourceImageNameElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceImageName");
                sourceImageNameElement.appendChild(
                        requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getSourceImageName()));
                oSVirtualHardDiskElement.appendChild(sourceImageNameElement);
            }

            if (parameters.getOSVirtualHardDisk().getOperatingSystem() != null) {
                Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
                osElement.appendChild(
                        requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getOperatingSystem()));
                oSVirtualHardDiskElement.appendChild(osElement);
            }

            if (parameters.getOSVirtualHardDisk().getRemoteSourceImageLink() != null) {
                Element remoteSourceImageLinkElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSourceImageLink");
                remoteSourceImageLinkElement.appendChild(requestDoc
                        .createTextNode(parameters.getOSVirtualHardDisk().getRemoteSourceImageLink().toString()));
                oSVirtualHardDiskElement.appendChild(remoteSourceImageLinkElement);
            }

            if (parameters.getOSVirtualHardDisk().getIOType() != null) {
                Element iOTypeElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "IOType");
                iOTypeElement2
                        .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getIOType()));
                oSVirtualHardDiskElement.appendChild(iOTypeElement2);
            }

            if (parameters.getOSVirtualHardDisk().getResizedSizeInGB() != null) {
                Element resizedSizeInGBElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ResizedSizeInGB");
                resizedSizeInGBElement.appendChild(requestDoc
                        .createTextNode(Integer.toString(parameters.getOSVirtualHardDisk().getResizedSizeInGB())));
                oSVirtualHardDiskElement.appendChild(resizedSizeInGBElement);
            }
        }

        if (parameters.getRoleSize() != null) {
            Element roleSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "RoleSize");
            roleSizeElement.appendChild(requestDoc.createTextNode(parameters.getRoleSize()));
            persistentVMRoleElement.appendChild(roleSizeElement);
        }

        if (parameters.isProvisionGuestAgent() != null) {
            Element provisionGuestAgentElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent");
            provisionGuestAgentElement.appendChild(
                    requestDoc.createTextNode(Boolean.toString(parameters.isProvisionGuestAgent()).toLowerCase()));
            persistentVMRoleElement.appendChild(provisionGuestAgentElement);
        }

        if (parameters.getVMImageInput() != null) {
            Element vMImageInputElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "VMImageInput");
            persistentVMRoleElement.appendChild(vMImageInputElement);
        }

        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
            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 Begin Creating Virtual Machine Deployment operation provisions a
    * virtual machine based on the supplied configuration. When you create a
    * deployment of a virtual machine, you should make sure that the cloud
    * service and the disk or image that you use are located in the same
    * region. For example, if the cloud service was created in the West US
    * region, the disk or image that you use should also be located in a
    * storage account in the West US region.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Virtual Machine Deployment operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginCreatingDeploymentAsync(final String serviceName,
            final VirtualMachineCreateDeploymentParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginCreatingDeployment(serviceName, parameters);
            }
        });
    }

    /**
    * The Begin Creating Virtual Machine Deployment operation provisions a
    * virtual machine based on the supplied configuration. When you create a
    * deployment of a virtual machine, you should make sure that the cloud
    * service and the disk or image that you use are located in the same
    * region. For example, if the cloud service was created in the West US
    * region, the disk or image that you use should also be located in a
    * storage account in the West US region.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param parameters Required. Parameters supplied to the Begin Creating
    * Virtual Machine Deployment 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginCreatingDeployment(String serviceName,
            VirtualMachineCreateDeploymentParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getDeploymentSlot() == null) {
            throw new NullPointerException("parameters.DeploymentSlot");
        }
        if (parameters.getLabel() == null) {
            throw new NullPointerException("parameters.Label");
        }
        if (parameters.getLabel().length() > 100) {
            throw new IllegalArgumentException("parameters.Label");
        }
        if (parameters.getName() == null) {
            throw new NullPointerException("parameters.Name");
        }
        if (parameters.getRoles() == null) {
            throw new NullPointerException("parameters.Roles");
        }
        if (parameters.getRoles() != null) {
            for (Role rolesParameterItem : parameters.getRoles()) {
                if (rolesParameterItem.getConfigurationSets() != null) {
                    for (ConfigurationSet configurationSetsParameterItem : rolesParameterItem
                            .getConfigurationSets()) {
                        if (configurationSetsParameterItem.getAdditionalUnattendContent() != null) {
                            if (configurationSetsParameterItem.getAdditionalUnattendContent()
                                    .getUnattendPasses() != null) {
                                for (UnattendPassSettings unattendPassesParameterItem : configurationSetsParameterItem
                                        .getAdditionalUnattendContent().getUnattendPasses()) {
                                    if (unattendPassesParameterItem.getPassName() == null) {
                                        throw new NullPointerException(
                                                "parameters.Roles.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.PassName");
                                    }
                                    if (unattendPassesParameterItem.getUnattendComponents() != null) {
                                        for (UnattendComponent unattendComponentsParameterItem : unattendPassesParameterItem
                                                .getUnattendComponents()) {
                                            if (unattendComponentsParameterItem.getComponentName() == null) {
                                                throw new NullPointerException(
                                                        "parameters.Roles.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.UnattendComponents.ComponentName");
                                            }
                                            if (unattendComponentsParameterItem
                                                    .getUnattendComponentSettings() != null) {
                                                for (ComponentSetting unattendComponentSettingsParameterItem : unattendComponentsParameterItem
                                                        .getUnattendComponentSettings()) {
                                                    if (unattendComponentSettingsParameterItem
                                                            .getSettingName() == null) {
                                                        throw new NullPointerException(
                                                                "parameters.Roles.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.UnattendComponents.UnattendComponentSettings.SettingName");
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        if (configurationSetsParameterItem.getDomainJoin() != null) {
                            if (configurationSetsParameterItem.getDomainJoin().getCredentials() != null) {
                                if (configurationSetsParameterItem.getDomainJoin().getCredentials()
                                        .getPassword() == null) {
                                    throw new NullPointerException(
                                            "parameters.Roles.ConfigurationSets.DomainJoin.Credentials.Password");
                                }
                                if (configurationSetsParameterItem.getDomainJoin().getCredentials()
                                        .getUserName() == null) {
                                    throw new NullPointerException(
                                            "parameters.Roles.ConfigurationSets.DomainJoin.Credentials.UserName");
                                }
                            }
                        }
                        if (configurationSetsParameterItem.getHostName() != null
                                && configurationSetsParameterItem.getHostName().length() < 1) {
                            throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.HostName");
                        }
                        if (configurationSetsParameterItem.getHostName() != null
                                && configurationSetsParameterItem.getHostName().length() > 64) {
                            throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.HostName");
                        }
                        if (configurationSetsParameterItem.getSshSettings() != null) {
                            if (configurationSetsParameterItem.getSshSettings().getKeyPairs() != null) {
                                for (SshSettingKeyPair keyPairsParameterItem : configurationSetsParameterItem
                                        .getSshSettings().getKeyPairs()) {
                                    if (keyPairsParameterItem.getFingerprint() == null) {
                                        throw new NullPointerException(
                                                "parameters.Roles.ConfigurationSets.SshSettings.KeyPairs.Fingerprint");
                                    }
                                    if (keyPairsParameterItem.getPath() == null) {
                                        throw new NullPointerException(
                                                "parameters.Roles.ConfigurationSets.SshSettings.KeyPairs.Path");
                                    }
                                }
                            }
                            if (configurationSetsParameterItem.getSshSettings().getPublicKeys() != null) {
                                for (SshSettingPublicKey publicKeysParameterItem : configurationSetsParameterItem
                                        .getSshSettings().getPublicKeys()) {
                                    if (publicKeysParameterItem.getFingerprint() == null) {
                                        throw new NullPointerException(
                                                "parameters.Roles.ConfigurationSets.SshSettings.PublicKeys.Fingerprint");
                                    }
                                    if (publicKeysParameterItem.getPath() == null) {
                                        throw new NullPointerException(
                                                "parameters.Roles.ConfigurationSets.SshSettings.PublicKeys.Path");
                                    }
                                }
                            }
                        }
                        if (configurationSetsParameterItem.getStoredCertificateSettings() != null) {
                            for (StoredCertificateSettings storedCertificateSettingsParameterItem : configurationSetsParameterItem
                                    .getStoredCertificateSettings()) {
                                if (storedCertificateSettingsParameterItem.getStoreName() == null) {
                                    throw new NullPointerException(
                                            "parameters.Roles.ConfigurationSets.StoredCertificateSettings.StoreName");
                                }
                                if (storedCertificateSettingsParameterItem.getThumbprint() == null) {
                                    throw new NullPointerException(
                                            "parameters.Roles.ConfigurationSets.StoredCertificateSettings.Thumbprint");
                                }
                            }
                        }
                        if (configurationSetsParameterItem.getUserName() != null
                                && configurationSetsParameterItem.getUserName().length() < 1) {
                            throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserName");
                        }
                        if (configurationSetsParameterItem.getUserName() != null
                                && configurationSetsParameterItem.getUserName().length() > 32) {
                            throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserName");
                        }
                        if (configurationSetsParameterItem.getUserPassword() != null
                                && configurationSetsParameterItem.getUserPassword().length() < 6) {
                            throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserPassword");
                        }
                        if (configurationSetsParameterItem.getUserPassword() != null
                                && configurationSetsParameterItem.getUserPassword().length() > 72) {
                            throw new IllegalArgumentException("parameters.Roles.ConfigurationSets.UserPassword");
                        }
                        if (configurationSetsParameterItem.getWindowsRemoteManagement() != null) {
                            if (configurationSetsParameterItem.getWindowsRemoteManagement()
                                    .getListeners() != null) {
                                for (WindowsRemoteManagementListener listenersParameterItem : configurationSetsParameterItem
                                        .getWindowsRemoteManagement().getListeners()) {
                                    if (listenersParameterItem.getListenerType() == null) {
                                        throw new NullPointerException(
                                                "parameters.Roles.ConfigurationSets.WindowsRemoteManagement.Listeners.ListenerType");
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginCreatingDeploymentAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments";
        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 deploymentElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Deployment");
        requestDoc.appendChild(deploymentElement);

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

        Element deploymentSlotElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "DeploymentSlot");
        deploymentSlotElement.appendChild(requestDoc.createTextNode(parameters.getDeploymentSlot().toString()));
        deploymentElement.appendChild(deploymentSlotElement);

        Element labelElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Label");
        labelElement.appendChild(requestDoc.createTextNode(parameters.getLabel()));
        deploymentElement.appendChild(labelElement);

        if (parameters.getRoles() instanceof LazyCollection == false
                || ((LazyCollection) parameters.getRoles()).isInitialized()) {
            Element roleListSequenceElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleList");
            for (Role roleListItem : parameters.getRoles()) {
                Element roleElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                        "Role");
                roleListSequenceElement.appendChild(roleElement);

                if (roleListItem.getRoleName() != null) {
                    Element roleNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleName");
                    roleNameElement.appendChild(requestDoc.createTextNode(roleListItem.getRoleName()));
                    roleElement.appendChild(roleNameElement);
                }

                if (roleListItem.getOSVersion() != null) {
                    Element osVersionElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "OsVersion");
                    osVersionElement.appendChild(requestDoc.createTextNode(roleListItem.getOSVersion()));
                    roleElement.appendChild(osVersionElement);
                }

                if (roleListItem.getRoleType() != null) {
                    Element roleTypeElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleType");
                    roleTypeElement.appendChild(requestDoc.createTextNode(roleListItem.getRoleType()));
                    roleElement.appendChild(roleTypeElement);
                }

                if (roleListItem.getConfigurationSets() != null) {
                    if (roleListItem.getConfigurationSets() instanceof LazyCollection == false
                            || ((LazyCollection) roleListItem.getConfigurationSets()).isInitialized()) {
                        Element configurationSetsSequenceElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSets");
                        for (ConfigurationSet configurationSetsItem : roleListItem.getConfigurationSets()) {
                            Element configurationSetElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "ConfigurationSet");
                            configurationSetsSequenceElement.appendChild(configurationSetElement);

                            if (configurationSetsItem.getConfigurationSetType() != null) {
                                Element configurationSetTypeElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType");
                                configurationSetTypeElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getConfigurationSetType()));
                                configurationSetElement.appendChild(configurationSetTypeElement);
                            }

                            if (configurationSetsItem.getInputEndpoints() != null) {
                                if (configurationSetsItem.getInputEndpoints() instanceof LazyCollection == false
                                        || ((LazyCollection) configurationSetsItem.getInputEndpoints())
                                                .isInitialized()) {
                                    Element inputEndpointsSequenceElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                                    for (InputEndpoint inputEndpointsItem : configurationSetsItem
                                            .getInputEndpoints()) {
                                        Element inputEndpointElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                                        inputEndpointsSequenceElement.appendChild(inputEndpointElement);

                                        if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) {
                                            Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "LoadBalancedEndpointSetName");
                                            loadBalancedEndpointSetNameElement
                                                    .appendChild(requestDoc.createTextNode(
                                                            inputEndpointsItem.getLoadBalancedEndpointSetName()));
                                            inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement);
                                        }

                                        if (inputEndpointsItem.getLocalPort() != null) {
                                            Element localPortElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "LocalPort");
                                            localPortElement.appendChild(requestDoc.createTextNode(
                                                    Integer.toString(inputEndpointsItem.getLocalPort())));
                                            inputEndpointElement.appendChild(localPortElement);
                                        }

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

                                        if (inputEndpointsItem.getPort() != null) {
                                            Element portElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Port");
                                            portElement.appendChild(requestDoc.createTextNode(
                                                    Integer.toString(inputEndpointsItem.getPort())));
                                            inputEndpointElement.appendChild(portElement);
                                        }

                                        if (inputEndpointsItem.getLoadBalancerProbe() != null) {
                                            Element loadBalancerProbeElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "LoadBalancerProbe");
                                            inputEndpointElement.appendChild(loadBalancerProbeElement);

                                            if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) {
                                                Element pathElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure", "Path");
                                                pathElement.appendChild(requestDoc.createTextNode(
                                                        inputEndpointsItem.getLoadBalancerProbe().getPath()));
                                                loadBalancerProbeElement.appendChild(pathElement);
                                            }

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

                                            if (inputEndpointsItem.getLoadBalancerProbe().getProtocol() != null) {
                                                Element protocolElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure", "Protocol");
                                                protocolElement.appendChild(
                                                        requestDoc.createTextNode(ComputeManagementClientImpl
                                                                .loadBalancerProbeTransportProtocolToString(
                                                                        inputEndpointsItem.getLoadBalancerProbe()
                                                                                .getProtocol())));
                                                loadBalancerProbeElement.appendChild(protocolElement);
                                            }

                                            if (inputEndpointsItem.getLoadBalancerProbe()
                                                    .getIntervalInSeconds() != null) {
                                                Element intervalInSecondsElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "IntervalInSeconds");
                                                intervalInSecondsElement.appendChild(requestDoc
                                                        .createTextNode(Integer.toString(inputEndpointsItem
                                                                .getLoadBalancerProbe().getIntervalInSeconds())));
                                                loadBalancerProbeElement.appendChild(intervalInSecondsElement);
                                            }

                                            if (inputEndpointsItem.getLoadBalancerProbe()
                                                    .getTimeoutInSeconds() != null) {
                                                Element timeoutInSecondsElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "TimeoutInSeconds");
                                                timeoutInSecondsElement.appendChild(requestDoc
                                                        .createTextNode(Integer.toString(inputEndpointsItem
                                                                .getLoadBalancerProbe().getTimeoutInSeconds())));
                                                loadBalancerProbeElement.appendChild(timeoutInSecondsElement);
                                            }
                                        }

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

                                        if (inputEndpointsItem.getVirtualIPAddress() != null) {
                                            Element vipElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Vip");
                                            vipElement.appendChild(requestDoc.createTextNode(
                                                    inputEndpointsItem.getVirtualIPAddress().getHostAddress()));
                                            inputEndpointElement.appendChild(vipElement);
                                        }

                                        if (inputEndpointsItem.isEnableDirectServerReturn() != null) {
                                            Element enableDirectServerReturnElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "EnableDirectServerReturn");
                                            enableDirectServerReturnElement
                                                    .appendChild(requestDoc.createTextNode(Boolean
                                                            .toString(
                                                                    inputEndpointsItem.isEnableDirectServerReturn())
                                                            .toLowerCase()));
                                            inputEndpointElement.appendChild(enableDirectServerReturnElement);
                                        }

                                        if (inputEndpointsItem.getLoadBalancerName() != null) {
                                            Element loadBalancerNameElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "LoadBalancerName");
                                            loadBalancerNameElement.appendChild(requestDoc
                                                    .createTextNode(inputEndpointsItem.getLoadBalancerName()));
                                            inputEndpointElement.appendChild(loadBalancerNameElement);
                                        }

                                        if (inputEndpointsItem.getEndpointAcl() != null) {
                                            Element endpointAclElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "EndpointAcl");
                                            inputEndpointElement.appendChild(endpointAclElement);

                                            if (inputEndpointsItem.getEndpointAcl().getRules() != null) {
                                                if (inputEndpointsItem.getEndpointAcl()
                                                        .getRules() instanceof LazyCollection == false
                                                        || ((LazyCollection) inputEndpointsItem.getEndpointAcl()
                                                                .getRules()).isInitialized()) {
                                                    Element rulesSequenceElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure", "Rules");
                                                    for (AccessControlListRule rulesItem : inputEndpointsItem
                                                            .getEndpointAcl().getRules()) {
                                                        Element ruleElement = requestDoc.createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "Rule");
                                                        rulesSequenceElement.appendChild(ruleElement);

                                                        if (rulesItem.getOrder() != null) {
                                                            Element orderElement = requestDoc.createElementNS(
                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                    "Order");
                                                            orderElement.appendChild(requestDoc.createTextNode(
                                                                    Integer.toString(rulesItem.getOrder())));
                                                            ruleElement.appendChild(orderElement);
                                                        }

                                                        if (rulesItem.getAction() != null) {
                                                            Element actionElement = requestDoc.createElementNS(
                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                    "Action");
                                                            actionElement.appendChild(requestDoc
                                                                    .createTextNode(rulesItem.getAction()));
                                                            ruleElement.appendChild(actionElement);
                                                        }

                                                        if (rulesItem.getRemoteSubnet() != null) {
                                                            Element remoteSubnetElement = requestDoc
                                                                    .createElementNS(
                                                                            "http://schemas.microsoft.com/windowsazure",
                                                                            "RemoteSubnet");
                                                            remoteSubnetElement.appendChild(requestDoc
                                                                    .createTextNode(rulesItem.getRemoteSubnet()));
                                                            ruleElement.appendChild(remoteSubnetElement);
                                                        }

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

                                        if (inputEndpointsItem.getIdleTimeoutInMinutes() != null) {
                                            Element idleTimeoutInMinutesElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "IdleTimeoutInMinutes");
                                            idleTimeoutInMinutesElement
                                                    .appendChild(requestDoc.createTextNode(Integer.toString(
                                                            inputEndpointsItem.getIdleTimeoutInMinutes())));
                                            inputEndpointElement.appendChild(idleTimeoutInMinutesElement);
                                        }

                                        if (inputEndpointsItem.getLoadBalancerDistribution() != null) {
                                            Element loadBalancerDistributionElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "LoadBalancerDistribution");
                                            loadBalancerDistributionElement.appendChild(requestDoc.createTextNode(
                                                    inputEndpointsItem.getLoadBalancerDistribution()));
                                            inputEndpointElement.appendChild(loadBalancerDistributionElement);
                                        }

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

                            if (configurationSetsItem.getSubnetNames() != null) {
                                if (configurationSetsItem.getSubnetNames() instanceof LazyCollection == false
                                        || ((LazyCollection) configurationSetsItem.getSubnetNames())
                                                .isInitialized()) {
                                    Element subnetNamesSequenceElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "SubnetNames");
                                    for (String subnetNamesItem : configurationSetsItem.getSubnetNames()) {
                                        Element subnetNamesItemElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "SubnetName");
                                        subnetNamesItemElement
                                                .appendChild(requestDoc.createTextNode(subnetNamesItem));
                                        subnetNamesSequenceElement.appendChild(subnetNamesItemElement);
                                    }
                                    configurationSetElement.appendChild(subnetNamesSequenceElement);
                                }
                            }

                            if (configurationSetsItem.getStaticVirtualNetworkIPAddress() != null) {
                                Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure",
                                        "StaticVirtualNetworkIPAddress");
                                staticVirtualNetworkIPAddressElement.appendChild(requestDoc
                                        .createTextNode(configurationSetsItem.getStaticVirtualNetworkIPAddress()));
                                configurationSetElement.appendChild(staticVirtualNetworkIPAddressElement);
                            }

                            if (configurationSetsItem.getPublicIPs() != null) {
                                if (configurationSetsItem.getPublicIPs() instanceof LazyCollection == false
                                        || ((LazyCollection) configurationSetsItem.getPublicIPs())
                                                .isInitialized()) {
                                    Element publicIPsSequenceElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "PublicIPs");
                                    for (ConfigurationSet.PublicIP publicIPsItem : configurationSetsItem
                                            .getPublicIPs()) {
                                        Element publicIPElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "PublicIP");
                                        publicIPsSequenceElement.appendChild(publicIPElement);

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

                                        if (publicIPsItem.getIdleTimeoutInMinutes() != null) {
                                            Element idleTimeoutInMinutesElement2 = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "IdleTimeoutInMinutes");
                                            idleTimeoutInMinutesElement2.appendChild(requestDoc.createTextNode(
                                                    Integer.toString(publicIPsItem.getIdleTimeoutInMinutes())));
                                            publicIPElement.appendChild(idleTimeoutInMinutesElement2);
                                        }

                                        if (publicIPsItem.getDomainNameLabel() != null) {
                                            Element domainNameLabelElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "DomainNameLabel");
                                            domainNameLabelElement.appendChild(
                                                    requestDoc.createTextNode(publicIPsItem.getDomainNameLabel()));
                                            publicIPElement.appendChild(domainNameLabelElement);
                                        }
                                    }
                                    configurationSetElement.appendChild(publicIPsSequenceElement);
                                }
                            }

                            if (configurationSetsItem.getNetworkInterfaces() != null) {
                                if (configurationSetsItem.getNetworkInterfaces() instanceof LazyCollection == false
                                        || ((LazyCollection) configurationSetsItem.getNetworkInterfaces())
                                                .isInitialized()) {
                                    Element networkInterfacesSequenceElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "NetworkInterfaces");
                                    for (NetworkInterface networkInterfacesItem : configurationSetsItem
                                            .getNetworkInterfaces()) {
                                        Element networkInterfaceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "NetworkInterface");
                                        networkInterfacesSequenceElement.appendChild(networkInterfaceElement);

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

                                        if (networkInterfacesItem.getIPConfigurations() != null) {
                                            if (networkInterfacesItem
                                                    .getIPConfigurations() instanceof LazyCollection == false
                                                    || ((LazyCollection) networkInterfacesItem
                                                            .getIPConfigurations()).isInitialized()) {
                                                Element iPConfigurationsSequenceElement = requestDoc
                                                        .createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "IPConfigurations");
                                                for (IPConfiguration iPConfigurationsItem : networkInterfacesItem
                                                        .getIPConfigurations()) {
                                                    Element iPConfigurationElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "IPConfiguration");
                                                    iPConfigurationsSequenceElement
                                                            .appendChild(iPConfigurationElement);

                                                    if (iPConfigurationsItem.getSubnetName() != null) {
                                                        Element subnetNameElement = requestDoc.createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "SubnetName");
                                                        subnetNameElement.appendChild(requestDoc.createTextNode(
                                                                iPConfigurationsItem.getSubnetName()));
                                                        iPConfigurationElement.appendChild(subnetNameElement);
                                                    }

                                                    if (iPConfigurationsItem
                                                            .getStaticVirtualNetworkIPAddress() != null) {
                                                        Element staticVirtualNetworkIPAddressElement2 = requestDoc
                                                                .createElementNS(
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "StaticVirtualNetworkIPAddress");
                                                        staticVirtualNetworkIPAddressElement2.appendChild(
                                                                requestDoc.createTextNode(iPConfigurationsItem
                                                                        .getStaticVirtualNetworkIPAddress()));
                                                        iPConfigurationElement
                                                                .appendChild(staticVirtualNetworkIPAddressElement2);
                                                    }
                                                }
                                                networkInterfaceElement
                                                        .appendChild(iPConfigurationsSequenceElement);
                                            }
                                        }

                                        if (networkInterfacesItem.getNetworkSecurityGroup() != null) {
                                            Element networkSecurityGroupElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "NetworkSecurityGroup");
                                            networkSecurityGroupElement.appendChild(requestDoc.createTextNode(
                                                    networkInterfacesItem.getNetworkSecurityGroup()));
                                            networkInterfaceElement.appendChild(networkSecurityGroupElement);
                                        }

                                        if (networkInterfacesItem.getIPForwarding() != null) {
                                            Element iPForwardingElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "IPForwarding");
                                            iPForwardingElement.appendChild(requestDoc
                                                    .createTextNode(networkInterfacesItem.getIPForwarding()));
                                            networkInterfaceElement.appendChild(iPForwardingElement);
                                        }
                                    }
                                    configurationSetElement.appendChild(networkInterfacesSequenceElement);
                                }
                            }

                            if (configurationSetsItem.getNetworkSecurityGroup() != null) {
                                Element networkSecurityGroupElement2 = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                                networkSecurityGroupElement2.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getNetworkSecurityGroup()));
                                configurationSetElement.appendChild(networkSecurityGroupElement2);
                            }

                            if (configurationSetsItem.getIPForwarding() != null) {
                                Element iPForwardingElement2 = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "IPForwarding");
                                iPForwardingElement2.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getIPForwarding()));
                                configurationSetElement.appendChild(iPForwardingElement2);
                            }

                            if (configurationSetsItem.getComputerName() != null) {
                                Element computerNameElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "ComputerName");
                                computerNameElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getComputerName()));
                                configurationSetElement.appendChild(computerNameElement);
                            }

                            if (configurationSetsItem.getAdminPassword() != null) {
                                Element adminPasswordElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "AdminPassword");
                                adminPasswordElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getAdminPassword()));
                                configurationSetElement.appendChild(adminPasswordElement);
                            }

                            if (configurationSetsItem.isResetPasswordOnFirstLogon() != null) {
                                Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon");
                                resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(
                                        Boolean.toString(configurationSetsItem.isResetPasswordOnFirstLogon())
                                                .toLowerCase()));
                                configurationSetElement.appendChild(resetPasswordOnFirstLogonElement);
                            }

                            if (configurationSetsItem.isEnableAutomaticUpdates() != null) {
                                Element enableAutomaticUpdatesElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates");
                                enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(Boolean
                                        .toString(configurationSetsItem.isEnableAutomaticUpdates()).toLowerCase()));
                                configurationSetElement.appendChild(enableAutomaticUpdatesElement);
                            }

                            if (configurationSetsItem.getTimeZone() != null) {
                                Element timeZoneElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone");
                                timeZoneElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getTimeZone()));
                                configurationSetElement.appendChild(timeZoneElement);
                            }

                            if (configurationSetsItem.getDomainJoin() != null) {
                                Element domainJoinElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin");
                                configurationSetElement.appendChild(domainJoinElement);

                                if (configurationSetsItem.getDomainJoin().getCredentials() != null) {
                                    Element credentialsElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Credentials");
                                    domainJoinElement.appendChild(credentialsElement);

                                    if (configurationSetsItem.getDomainJoin().getCredentials()
                                            .getDomain() != null) {
                                        Element domainElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Domain");
                                        domainElement.appendChild(requestDoc.createTextNode(configurationSetsItem
                                                .getDomainJoin().getCredentials().getDomain()));
                                        credentialsElement.appendChild(domainElement);
                                    }

                                    Element usernameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Username");
                                    usernameElement.appendChild(requestDoc.createTextNode(
                                            configurationSetsItem.getDomainJoin().getCredentials().getUserName()));
                                    credentialsElement.appendChild(usernameElement);

                                    Element passwordElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Password");
                                    passwordElement.appendChild(requestDoc.createTextNode(
                                            configurationSetsItem.getDomainJoin().getCredentials().getPassword()));
                                    credentialsElement.appendChild(passwordElement);
                                }

                                if (configurationSetsItem.getDomainJoin().getDomainToJoin() != null) {
                                    Element joinDomainElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "JoinDomain");
                                    joinDomainElement.appendChild(requestDoc.createTextNode(
                                            configurationSetsItem.getDomainJoin().getDomainToJoin()));
                                    domainJoinElement.appendChild(joinDomainElement);
                                }

                                if (configurationSetsItem.getDomainJoin().getLdapMachineObjectOU() != null) {
                                    Element machineObjectOUElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "MachineObjectOU");
                                    machineObjectOUElement.appendChild(requestDoc.createTextNode(
                                            configurationSetsItem.getDomainJoin().getLdapMachineObjectOU()));
                                    domainJoinElement.appendChild(machineObjectOUElement);
                                }

                                if (configurationSetsItem.getDomainJoin().getProvisioning() != null) {
                                    Element provisioningElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Provisioning");
                                    domainJoinElement.appendChild(provisioningElement);

                                    if (configurationSetsItem.getDomainJoin().getProvisioning()
                                            .getAccountData() != null) {
                                        Element accountDataElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "AccountData");
                                        accountDataElement
                                                .appendChild(requestDoc.createTextNode(configurationSetsItem
                                                        .getDomainJoin().getProvisioning().getAccountData()));
                                        provisioningElement.appendChild(accountDataElement);
                                    }
                                }
                            }

                            if (configurationSetsItem.getStoredCertificateSettings() != null) {
                                if (configurationSetsItem
                                        .getStoredCertificateSettings() instanceof LazyCollection == false
                                        || ((LazyCollection) configurationSetsItem.getStoredCertificateSettings())
                                                .isInitialized()) {
                                    Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "StoredCertificateSettings");
                                    for (StoredCertificateSettings storedCertificateSettingsItem : configurationSetsItem
                                            .getStoredCertificateSettings()) {
                                        Element certificateSettingElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "CertificateSetting");
                                        storedCertificateSettingsSequenceElement
                                                .appendChild(certificateSettingElement);

                                        Element storeLocationElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "StoreLocation");
                                        storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine"));
                                        certificateSettingElement.appendChild(storeLocationElement);

                                        Element storeNameElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "StoreName");
                                        storeNameElement.appendChild(requestDoc
                                                .createTextNode(storedCertificateSettingsItem.getStoreName()));
                                        certificateSettingElement.appendChild(storeNameElement);

                                        Element thumbprintElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                                        thumbprintElement.appendChild(requestDoc
                                                .createTextNode(storedCertificateSettingsItem.getThumbprint()));
                                        certificateSettingElement.appendChild(thumbprintElement);
                                    }
                                    configurationSetElement.appendChild(storedCertificateSettingsSequenceElement);
                                }
                            }

                            if (configurationSetsItem.getWindowsRemoteManagement() != null) {
                                Element winRMElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM");
                                configurationSetElement.appendChild(winRMElement);

                                if (configurationSetsItem.getWindowsRemoteManagement().getListeners() != null) {
                                    if (configurationSetsItem.getWindowsRemoteManagement()
                                            .getListeners() instanceof LazyCollection == false
                                            || ((LazyCollection) configurationSetsItem.getWindowsRemoteManagement()
                                                    .getListeners()).isInitialized()) {
                                        Element listenersSequenceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Listeners");
                                        for (WindowsRemoteManagementListener listenersItem : configurationSetsItem
                                                .getWindowsRemoteManagement().getListeners()) {
                                            Element listenerElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Listener");
                                            listenersSequenceElement.appendChild(listenerElement);

                                            if (listenersItem.getCertificateThumbprint() != null) {
                                                Element certificateThumbprintElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "CertificateThumbprint");
                                                certificateThumbprintElement.appendChild(requestDoc
                                                        .createTextNode(listenersItem.getCertificateThumbprint()));
                                                listenerElement.appendChild(certificateThumbprintElement);
                                            }

                                            Element protocolElement3 = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Protocol");
                                            protocolElement3.appendChild(requestDoc
                                                    .createTextNode(listenersItem.getListenerType().toString()));
                                            listenerElement.appendChild(protocolElement3);
                                        }
                                        winRMElement.appendChild(listenersSequenceElement);
                                    }
                                }
                            }

                            if (configurationSetsItem.getAdminUserName() != null) {
                                Element adminUsernameElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "AdminUsername");
                                adminUsernameElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getAdminUserName()));
                                configurationSetElement.appendChild(adminUsernameElement);
                            }

                            if (configurationSetsItem.getAdditionalUnattendContent() != null) {
                                Element additionalUnattendContentElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "AdditionalUnattendContent");
                                configurationSetElement.appendChild(additionalUnattendContentElement);

                                if (configurationSetsItem.getAdditionalUnattendContent()
                                        .getUnattendPasses() != null) {
                                    if (configurationSetsItem.getAdditionalUnattendContent()
                                            .getUnattendPasses() instanceof LazyCollection == false
                                            || ((LazyCollection) configurationSetsItem
                                                    .getAdditionalUnattendContent().getUnattendPasses())
                                                            .isInitialized()) {
                                        Element passesSequenceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Passes");
                                        for (UnattendPassSettings passesItem : configurationSetsItem
                                                .getAdditionalUnattendContent().getUnattendPasses()) {
                                            Element unattendPassElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "UnattendPass");
                                            passesSequenceElement.appendChild(unattendPassElement);

                                            Element passNameElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "PassName");
                                            passNameElement.appendChild(
                                                    requestDoc.createTextNode(passesItem.getPassName()));
                                            unattendPassElement.appendChild(passNameElement);

                                            if (passesItem.getUnattendComponents() != null) {
                                                if (passesItem
                                                        .getUnattendComponents() instanceof LazyCollection == false
                                                        || ((LazyCollection) passesItem.getUnattendComponents())
                                                                .isInitialized()) {
                                                    Element componentsSequenceElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "Components");
                                                    for (UnattendComponent componentsItem : passesItem
                                                            .getUnattendComponents()) {
                                                        Element unattendComponentElement = requestDoc
                                                                .createElementNS(
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "UnattendComponent");
                                                        componentsSequenceElement
                                                                .appendChild(unattendComponentElement);

                                                        Element componentNameElement = requestDoc.createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "ComponentName");
                                                        componentNameElement.appendChild(requestDoc
                                                                .createTextNode(componentsItem.getComponentName()));
                                                        unattendComponentElement.appendChild(componentNameElement);

                                                        if (componentsItem.getUnattendComponentSettings() != null) {
                                                            if (componentsItem
                                                                    .getUnattendComponentSettings() instanceof LazyCollection == false
                                                                    || ((LazyCollection) componentsItem
                                                                            .getUnattendComponentSettings())
                                                                                    .isInitialized()) {
                                                                Element componentSettingsSequenceElement = requestDoc
                                                                        .createElementNS(
                                                                                "http://schemas.microsoft.com/windowsazure",
                                                                                "ComponentSettings");
                                                                for (ComponentSetting componentSettingsItem : componentsItem
                                                                        .getUnattendComponentSettings()) {
                                                                    Element componentSettingElement = requestDoc
                                                                            .createElementNS(
                                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                                    "ComponentSetting");
                                                                    componentSettingsSequenceElement
                                                                            .appendChild(componentSettingElement);

                                                                    Element settingNameElement = requestDoc
                                                                            .createElementNS(
                                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                                    "SettingName");
                                                                    settingNameElement.appendChild(requestDoc
                                                                            .createTextNode(componentSettingsItem
                                                                                    .getSettingName()));
                                                                    componentSettingElement
                                                                            .appendChild(settingNameElement);

                                                                    if (componentSettingsItem
                                                                            .getContent() != null) {
                                                                        Element contentElement = requestDoc
                                                                                .createElementNS(
                                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                                        "Content");
                                                                        contentElement.appendChild(requestDoc
                                                                                .createTextNode(Base64.encode(
                                                                                        componentSettingsItem
                                                                                                .getContent()
                                                                                                .getBytes())));
                                                                        componentSettingElement
                                                                                .appendChild(contentElement);
                                                                    }
                                                                }
                                                                unattendComponentElement.appendChild(
                                                                        componentSettingsSequenceElement);
                                                            }
                                                        }
                                                    }
                                                    unattendPassElement.appendChild(componentsSequenceElement);
                                                }
                                            }
                                        }
                                        additionalUnattendContentElement.appendChild(passesSequenceElement);
                                    }
                                }
                            }

                            if (configurationSetsItem.getHostName() != null) {
                                Element hostNameElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "HostName");
                                hostNameElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getHostName()));
                                configurationSetElement.appendChild(hostNameElement);
                            }

                            if (configurationSetsItem.getUserName() != null) {
                                Element userNameElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "UserName");
                                userNameElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getUserName()));
                                configurationSetElement.appendChild(userNameElement);
                            }

                            if (configurationSetsItem.getUserPassword() != null) {
                                Element userPasswordElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "UserPassword");
                                userPasswordElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getUserPassword()));
                                configurationSetElement.appendChild(userPasswordElement);
                            }

                            if (configurationSetsItem.isDisableSshPasswordAuthentication() != null) {
                                Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure",
                                        "DisableSshPasswordAuthentication");
                                disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(
                                        Boolean.toString(configurationSetsItem.isDisableSshPasswordAuthentication())
                                                .toLowerCase()));
                                configurationSetElement.appendChild(disableSshPasswordAuthenticationElement);
                            }

                            if (configurationSetsItem.getSshSettings() != null) {
                                Element sSHElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SSH");
                                configurationSetElement.appendChild(sSHElement);

                                if (configurationSetsItem.getSshSettings().getPublicKeys() != null) {
                                    if (configurationSetsItem.getSshSettings()
                                            .getPublicKeys() instanceof LazyCollection == false
                                            || ((LazyCollection) configurationSetsItem.getSshSettings()
                                                    .getPublicKeys()).isInitialized()) {
                                        Element publicKeysSequenceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "PublicKeys");
                                        for (SshSettingPublicKey publicKeysItem : configurationSetsItem
                                                .getSshSettings().getPublicKeys()) {
                                            Element publicKeyElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "PublicKey");
                                            publicKeysSequenceElement.appendChild(publicKeyElement);

                                            Element fingerprintElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Fingerprint");
                                            fingerprintElement.appendChild(
                                                    requestDoc.createTextNode(publicKeysItem.getFingerprint()));
                                            publicKeyElement.appendChild(fingerprintElement);

                                            Element pathElement2 = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Path");
                                            pathElement2.appendChild(
                                                    requestDoc.createTextNode(publicKeysItem.getPath()));
                                            publicKeyElement.appendChild(pathElement2);
                                        }
                                        sSHElement.appendChild(publicKeysSequenceElement);
                                    }
                                }

                                if (configurationSetsItem.getSshSettings().getKeyPairs() != null) {
                                    if (configurationSetsItem.getSshSettings()
                                            .getKeyPairs() instanceof LazyCollection == false
                                            || ((LazyCollection) configurationSetsItem.getSshSettings()
                                                    .getKeyPairs()).isInitialized()) {
                                        Element keyPairsSequenceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "KeyPairs");
                                        for (SshSettingKeyPair keyPairsItem : configurationSetsItem.getSshSettings()
                                                .getKeyPairs()) {
                                            Element keyPairElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "KeyPair");
                                            keyPairsSequenceElement.appendChild(keyPairElement);

                                            Element fingerprintElement2 = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Fingerprint");
                                            fingerprintElement2.appendChild(
                                                    requestDoc.createTextNode(keyPairsItem.getFingerprint()));
                                            keyPairElement.appendChild(fingerprintElement2);

                                            Element pathElement3 = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Path");
                                            pathElement3
                                                    .appendChild(requestDoc.createTextNode(keyPairsItem.getPath()));
                                            keyPairElement.appendChild(pathElement3);
                                        }
                                        sSHElement.appendChild(keyPairsSequenceElement);
                                    }
                                }
                            }

                            if (configurationSetsItem.getCustomData() != null) {
                                Element customDataElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData");
                                customDataElement.appendChild(
                                        requestDoc.createTextNode(configurationSetsItem.getCustomData()));
                                configurationSetElement.appendChild(customDataElement);
                            }
                        }
                        roleElement.appendChild(configurationSetsSequenceElement);
                    }
                }

                if (roleListItem.getResourceExtensionReferences() != null) {
                    if (roleListItem.getResourceExtensionReferences() instanceof LazyCollection == false
                            || ((LazyCollection) roleListItem.getResourceExtensionReferences()).isInitialized()) {
                        Element resourceExtensionReferencesSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences");
                        for (ResourceExtensionReference resourceExtensionReferencesItem : roleListItem
                                .getResourceExtensionReferences()) {
                            Element resourceExtensionReferenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference");
                            resourceExtensionReferencesSequenceElement
                                    .appendChild(resourceExtensionReferenceElement);

                            if (resourceExtensionReferencesItem.getReferenceName() != null) {
                                Element referenceNameElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "ReferenceName");
                                referenceNameElement.appendChild(requestDoc
                                        .createTextNode(resourceExtensionReferencesItem.getReferenceName()));
                                resourceExtensionReferenceElement.appendChild(referenceNameElement);
                            }

                            if (resourceExtensionReferencesItem.getPublisher() != null) {
                                Element publisherElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Publisher");
                                publisherElement.appendChild(
                                        requestDoc.createTextNode(resourceExtensionReferencesItem.getPublisher()));
                                resourceExtensionReferenceElement.appendChild(publisherElement);
                            }

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

                            if (resourceExtensionReferencesItem.getVersion() != null) {
                                Element versionElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
                                versionElement.appendChild(
                                        requestDoc.createTextNode(resourceExtensionReferencesItem.getVersion()));
                                resourceExtensionReferenceElement.appendChild(versionElement);
                            }

                            if (resourceExtensionReferencesItem.getResourceExtensionParameterValues() != null) {
                                if (resourceExtensionReferencesItem
                                        .getResourceExtensionParameterValues() instanceof LazyCollection == false
                                        || ((LazyCollection) resourceExtensionReferencesItem
                                                .getResourceExtensionParameterValues()).isInitialized()) {
                                    Element resourceExtensionParameterValuesSequenceElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure",
                                                    "ResourceExtensionParameterValues");
                                    for (ResourceExtensionParameterValue resourceExtensionParameterValuesItem : resourceExtensionReferencesItem
                                            .getResourceExtensionParameterValues()) {
                                        Element resourceExtensionParameterValueElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure",
                                                "ResourceExtensionParameterValue");
                                        resourceExtensionParameterValuesSequenceElement
                                                .appendChild(resourceExtensionParameterValueElement);

                                        if (resourceExtensionParameterValuesItem.getKey() != null) {
                                            Element keyElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Key");
                                            keyElement.appendChild(requestDoc
                                                    .createTextNode(resourceExtensionParameterValuesItem.getKey()));
                                            resourceExtensionParameterValueElement.appendChild(keyElement);
                                        }

                                        if (resourceExtensionParameterValuesItem.getValue() != null) {
                                            Element valueElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Value");
                                            valueElement.appendChild(requestDoc.createTextNode(Base64.encode(
                                                    resourceExtensionParameterValuesItem.getValue().getBytes())));
                                            resourceExtensionParameterValueElement.appendChild(valueElement);
                                        }

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

                            if (resourceExtensionReferencesItem.getState() != null) {
                                Element stateElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "State");
                                stateElement.appendChild(
                                        requestDoc.createTextNode(resourceExtensionReferencesItem.getState()));
                                resourceExtensionReferenceElement.appendChild(stateElement);
                            }

                            if (resourceExtensionReferencesItem.isForceUpdate() != null) {
                                Element forceUpdateElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "ForceUpdate");
                                forceUpdateElement.appendChild(requestDoc.createTextNode(Boolean
                                        .toString(resourceExtensionReferencesItem.isForceUpdate()).toLowerCase()));
                                resourceExtensionReferenceElement.appendChild(forceUpdateElement);
                            }
                        }
                        roleElement.appendChild(resourceExtensionReferencesSequenceElement);
                    }
                }

                if (roleListItem.getVMImageName() != null) {
                    Element vMImageNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "VMImageName");
                    vMImageNameElement.appendChild(requestDoc.createTextNode(roleListItem.getVMImageName()));
                    roleElement.appendChild(vMImageNameElement);
                }

                if (roleListItem.getMediaLocation() != null) {
                    Element mediaLocationElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLocation");
                    mediaLocationElement
                            .appendChild(requestDoc.createTextNode(roleListItem.getMediaLocation().toString()));
                    roleElement.appendChild(mediaLocationElement);
                }

                if (roleListItem.getAvailabilitySetName() != null) {
                    Element availabilitySetNameElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilitySetName");
                    availabilitySetNameElement
                            .appendChild(requestDoc.createTextNode(roleListItem.getAvailabilitySetName()));
                    roleElement.appendChild(availabilitySetNameElement);
                }

                if (roleListItem.getDataVirtualHardDisks() != null) {
                    if (roleListItem.getDataVirtualHardDisks() instanceof LazyCollection == false
                            || ((LazyCollection) roleListItem.getDataVirtualHardDisks()).isInitialized()) {
                        Element dataVirtualHardDisksSequenceElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks");
                        for (DataVirtualHardDisk dataVirtualHardDisksItem : roleListItem
                                .getDataVirtualHardDisks()) {
                            Element dataVirtualHardDiskElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk");
                            dataVirtualHardDisksSequenceElement.appendChild(dataVirtualHardDiskElement);

                            if (dataVirtualHardDisksItem.getHostCaching() != null) {
                                Element hostCachingElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "HostCaching");
                                hostCachingElement.appendChild(
                                        requestDoc.createTextNode(dataVirtualHardDisksItem.getHostCaching()));
                                dataVirtualHardDiskElement.appendChild(hostCachingElement);
                            }

                            if (dataVirtualHardDisksItem.getLabel() != null) {
                                Element diskLabelElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel");
                                diskLabelElement.appendChild(
                                        requestDoc.createTextNode(dataVirtualHardDisksItem.getLabel()));
                                dataVirtualHardDiskElement.appendChild(diskLabelElement);
                            }

                            if (dataVirtualHardDisksItem.getName() != null) {
                                Element diskNameElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName");
                                diskNameElement
                                        .appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getName()));
                                dataVirtualHardDiskElement.appendChild(diskNameElement);
                            }

                            if (dataVirtualHardDisksItem.getLogicalUnitNumber() != null) {
                                Element lunElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Lun");
                                lunElement.appendChild(requestDoc.createTextNode(
                                        Integer.toString(dataVirtualHardDisksItem.getLogicalUnitNumber())));
                                dataVirtualHardDiskElement.appendChild(lunElement);
                            }

                            if (dataVirtualHardDisksItem.getLogicalDiskSizeInGB() != null) {
                                Element logicalDiskSizeInGBElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB");
                                logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(
                                        Integer.toString(dataVirtualHardDisksItem.getLogicalDiskSizeInGB())));
                                dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement);
                            }

                            if (dataVirtualHardDisksItem.getMediaLink() != null) {
                                Element mediaLinkElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink");
                                mediaLinkElement.appendChild(requestDoc
                                        .createTextNode(dataVirtualHardDisksItem.getMediaLink().toString()));
                                dataVirtualHardDiskElement.appendChild(mediaLinkElement);
                            }

                            if (dataVirtualHardDisksItem.getSourceMediaLink() != null) {
                                Element sourceMediaLinkElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "SourceMediaLink");
                                sourceMediaLinkElement.appendChild(requestDoc
                                        .createTextNode(dataVirtualHardDisksItem.getSourceMediaLink().toString()));
                                dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement);
                            }

                            if (dataVirtualHardDisksItem.getIOType() != null) {
                                Element iOTypeElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "IOType");
                                iOTypeElement.appendChild(
                                        requestDoc.createTextNode(dataVirtualHardDisksItem.getIOType()));
                                dataVirtualHardDiskElement.appendChild(iOTypeElement);
                            }
                        }
                        roleElement.appendChild(dataVirtualHardDisksSequenceElement);
                    }
                }

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

                if (roleListItem.getOSVirtualHardDisk() != null) {
                    Element oSVirtualHardDiskElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk");
                    roleElement.appendChild(oSVirtualHardDiskElement);

                    if (roleListItem.getOSVirtualHardDisk().getHostCaching() != null) {
                        Element hostCachingElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching");
                        hostCachingElement2.appendChild(
                                requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getHostCaching()));
                        oSVirtualHardDiskElement.appendChild(hostCachingElement2);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getLabel() != null) {
                        Element diskLabelElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel");
                        diskLabelElement2.appendChild(
                                requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getLabel()));
                        oSVirtualHardDiskElement.appendChild(diskLabelElement2);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getName() != null) {
                        Element diskNameElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName");
                        diskNameElement2.appendChild(
                                requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getName()));
                        oSVirtualHardDiskElement.appendChild(diskNameElement2);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getMediaLink() != null) {
                        Element mediaLinkElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink");
                        mediaLinkElement2.appendChild(requestDoc
                                .createTextNode(roleListItem.getOSVirtualHardDisk().getMediaLink().toString()));
                        oSVirtualHardDiskElement.appendChild(mediaLinkElement2);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getSourceImageName() != null) {
                        Element sourceImageNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceImageName");
                        sourceImageNameElement.appendChild(requestDoc
                                .createTextNode(roleListItem.getOSVirtualHardDisk().getSourceImageName()));
                        oSVirtualHardDiskElement.appendChild(sourceImageNameElement);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getOperatingSystem() != null) {
                        Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                                "OS");
                        osElement.appendChild(requestDoc
                                .createTextNode(roleListItem.getOSVirtualHardDisk().getOperatingSystem()));
                        oSVirtualHardDiskElement.appendChild(osElement);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getRemoteSourceImageLink() != null) {
                        Element remoteSourceImageLinkElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "RemoteSourceImageLink");
                        remoteSourceImageLinkElement.appendChild(requestDoc.createTextNode(
                                roleListItem.getOSVirtualHardDisk().getRemoteSourceImageLink().toString()));
                        oSVirtualHardDiskElement.appendChild(remoteSourceImageLinkElement);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getIOType() != null) {
                        Element iOTypeElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "IOType");
                        iOTypeElement2.appendChild(
                                requestDoc.createTextNode(roleListItem.getOSVirtualHardDisk().getIOType()));
                        oSVirtualHardDiskElement.appendChild(iOTypeElement2);
                    }

                    if (roleListItem.getOSVirtualHardDisk().getResizedSizeInGB() != null) {
                        Element resizedSizeInGBElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ResizedSizeInGB");
                        resizedSizeInGBElement.appendChild(requestDoc.createTextNode(
                                Integer.toString(roleListItem.getOSVirtualHardDisk().getResizedSizeInGB())));
                        oSVirtualHardDiskElement.appendChild(resizedSizeInGBElement);
                    }
                }

                if (roleListItem.getRoleSize() != null) {
                    Element roleSizeElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "RoleSize");
                    roleSizeElement.appendChild(requestDoc.createTextNode(roleListItem.getRoleSize()));
                    roleElement.appendChild(roleSizeElement);
                }

                if (roleListItem.getDefaultWinRmCertificateThumbprint() != null) {
                    Element defaultWinRmCertificateThumbprintElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "DefaultWinRmCertificateThumbprint");
                    defaultWinRmCertificateThumbprintElement.appendChild(
                            requestDoc.createTextNode(roleListItem.getDefaultWinRmCertificateThumbprint()));
                    roleElement.appendChild(defaultWinRmCertificateThumbprintElement);
                }

                if (roleListItem.isProvisionGuestAgent() != null) {
                    Element provisionGuestAgentElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent");
                    provisionGuestAgentElement.appendChild(requestDoc
                            .createTextNode(Boolean.toString(roleListItem.isProvisionGuestAgent()).toLowerCase()));
                    roleElement.appendChild(provisionGuestAgentElement);
                }

                if (roleListItem.getVMImageInput() != null) {
                    Element vMImageInputElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "VMImageInput");
                    roleElement.appendChild(vMImageInputElement);

                    if (roleListItem.getVMImageInput().getOSDiskConfiguration() != null) {
                        Element oSDiskConfigurationElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "OSDiskConfiguration");
                        vMImageInputElement.appendChild(oSDiskConfigurationElement);

                        if (roleListItem.getVMImageInput().getOSDiskConfiguration().getResizedSizeInGB() != null) {
                            Element resizedSizeInGBElement2 = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "ResizedSizeInGB");
                            resizedSizeInGBElement2.appendChild(requestDoc.createTextNode(Integer.toString(
                                    roleListItem.getVMImageInput().getOSDiskConfiguration().getResizedSizeInGB())));
                            oSDiskConfigurationElement.appendChild(resizedSizeInGBElement2);
                        }
                    }

                    if (roleListItem.getVMImageInput().getDataDiskConfigurations() != null) {
                        if (roleListItem.getVMImageInput()
                                .getDataDiskConfigurations() instanceof LazyCollection == false
                                || ((LazyCollection) roleListItem.getVMImageInput().getDataDiskConfigurations())
                                        .isInitialized()) {
                            Element dataDiskConfigurationsSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "DataDiskConfigurations");
                            for (DataDiskConfiguration dataDiskConfigurationsItem : roleListItem.getVMImageInput()
                                    .getDataDiskConfigurations()) {
                                Element dataDiskConfigurationElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "DataDiskConfiguration");
                                dataDiskConfigurationsSequenceElement.appendChild(dataDiskConfigurationElement);

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

                                if (dataDiskConfigurationsItem.getResizedSizeInGB() != null) {
                                    Element resizedSizeInGBElement3 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "ResizedSizeInGB");
                                    resizedSizeInGBElement3.appendChild(requestDoc.createTextNode(
                                            Integer.toString(dataDiskConfigurationsItem.getResizedSizeInGB())));
                                    dataDiskConfigurationElement.appendChild(resizedSizeInGBElement3);
                                }
                            }
                            vMImageInputElement.appendChild(dataDiskConfigurationsSequenceElement);
                        }
                    }
                }
            }
            deploymentElement.appendChild(roleListSequenceElement);
        }

        if (parameters.getVirtualNetworkName() != null) {
            Element virtualNetworkNameElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "VirtualNetworkName");
            virtualNetworkNameElement.appendChild(requestDoc.createTextNode(parameters.getVirtualNetworkName()));
            deploymentElement.appendChild(virtualNetworkNameElement);
        }

        if (parameters.getDnsSettings() != null) {
            Element dnsElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Dns");
            deploymentElement.appendChild(dnsElement);

            if (parameters.getDnsSettings().getDnsServers() != null) {
                if (parameters.getDnsSettings().getDnsServers() instanceof LazyCollection == false
                        || ((LazyCollection) parameters.getDnsSettings().getDnsServers()).isInitialized()) {
                    Element dnsServersSequenceElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DnsServers");
                    for (DnsServer dnsServersItem : parameters.getDnsSettings().getDnsServers()) {
                        Element dnsServerElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DnsServer");
                        dnsServersSequenceElement.appendChild(dnsServerElement);

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

                        if (dnsServersItem.getAddress() != null) {
                            Element addressElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Address");
                            addressElement.appendChild(
                                    requestDoc.createTextNode(dnsServersItem.getAddress().getHostAddress()));
                            dnsServerElement.appendChild(addressElement);
                        }
                    }
                    dnsElement.appendChild(dnsServersSequenceElement);
                }
            }
        }

        if (parameters.getReservedIPName() != null) {
            Element reservedIPNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ReservedIPName");
            reservedIPNameElement.appendChild(requestDoc.createTextNode(parameters.getReservedIPName()));
            deploymentElement.appendChild(reservedIPNameElement);
        }

        if (parameters.getLoadBalancers() != null) {
            if (parameters.getLoadBalancers() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getLoadBalancers()).isInitialized()) {
                Element loadBalancersSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancers");
                for (LoadBalancer loadBalancersItem : parameters.getLoadBalancers()) {
                    Element loadBalancerElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancer");
                    loadBalancersSequenceElement.appendChild(loadBalancerElement);

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

                    if (loadBalancersItem.getFrontendIPConfiguration() != null) {
                        Element frontendIpConfigurationElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
                        loadBalancerElement.appendChild(frontendIpConfigurationElement);

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

                        if (loadBalancersItem.getFrontendIPConfiguration().getSubnetName() != null) {
                            Element subnetNameElement2 = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName");
                            subnetNameElement2.appendChild(requestDoc.createTextNode(
                                    loadBalancersItem.getFrontendIPConfiguration().getSubnetName()));
                            frontendIpConfigurationElement.appendChild(subnetNameElement2);
                        }

                        if (loadBalancersItem.getFrontendIPConfiguration()
                                .getStaticVirtualNetworkIPAddress() != null) {
                            Element staticVirtualNetworkIPAddressElement3 = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
                            staticVirtualNetworkIPAddressElement3.appendChild(
                                    requestDoc.createTextNode(loadBalancersItem.getFrontendIPConfiguration()
                                            .getStaticVirtualNetworkIPAddress().getHostAddress()));
                            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement3);
                        }
                    }
                }
                deploymentElement.appendChild(loadBalancersSequenceElement);
            }
        }

        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
            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 Begin Deleting Role operation deletes the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * delete.
    * @param deleteFromStorage Required. Specifies that the source blob(s) for
    * the virtual machine should also be deleted from storage.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginDeletingAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName, final boolean deleteFromStorage) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginDeleting(serviceName, deploymentName, virtualMachineName, deleteFromStorage);
            }
        });
    }

    /**
    * The Begin Deleting Role operation deletes the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * delete.
    * @param deleteFromStorage Required. Specifies that the source blob(s) for
    * the virtual machine should also be deleted from storage.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginDeleting(String serviceName, String deploymentName, String virtualMachineName,
            boolean deleteFromStorage) throws IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("deleteFromStorage", deleteFromStorage);
            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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roles/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        if (deleteFromStorage == true) {
            queryParameters.add("comp=" + "media");
        }
        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("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 Begin Restarting role operation restarts the specified virtual
    * machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginRestartingAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginRestarting(serviceName, deploymentName, virtualMachineName);
            }
        });
    }

    /**
    * The Begin Restarting role operation restarts the specified virtual
    * machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginRestarting(String serviceName, String deploymentName, String virtualMachineName)
            throws IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            CloudTracing.enter(invocationId, this, "beginRestartingAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roleinstances/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        url = url + "/Operations";
        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 = "<RestartRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\"><OperationType>RestartRoleOperation</OperationType></RestartRoleOperation>";
        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
            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 Shutdown Role operation shuts down the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * shutdown.
    * @param parameters Required. The parameters for the shutdown vm operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginShutdownAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName, final VirtualMachineShutdownParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginShutdown(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * The Shutdown Role operation shuts down the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * shutdown.
    * @param parameters Required. The parameters for the shutdown vm 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginShutdown(String serviceName, String deploymentName, String virtualMachineName,
            VirtualMachineShutdownParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }
        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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginShutdownAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roleinstances/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        url = url + "/Operations";
        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 shutdownRoleOperationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ShutdownRoleOperation");
        requestDoc.appendChild(shutdownRoleOperationElement);

        Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OperationType");
        operationTypeElement.appendChild(requestDoc.createTextNode("ShutdownRoleOperation"));
        shutdownRoleOperationElement.appendChild(operationTypeElement);

        if (parameters.getPostShutdownAction() != null) {
            Element postShutdownActionElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "PostShutdownAction");
            postShutdownActionElement
                    .appendChild(requestDoc.createTextNode(parameters.getPostShutdownAction().toString()));
            shutdownRoleOperationElement.appendChild(postShutdownActionElement);
        }

        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
            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 Begin Shutting Down Roles operation stops the specified set of
    * virtual machines.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Begin Shutting Down
    * Roles operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginShuttingDownRolesAsync(final String serviceName,
            final String deploymentName, final VirtualMachineShutdownRolesParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginShuttingDownRoles(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Begin Shutting Down Roles operation stops the specified set of
    * virtual machines.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn469421.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Begin Shutting Down
    * Roles 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginShuttingDownRoles(String serviceName, String deploymentName,
            VirtualMachineShutdownRolesParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginShuttingDownRolesAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/Roles/Operations";
        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 shutdownRolesOperationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ShutdownRolesOperation");
        requestDoc.appendChild(shutdownRolesOperationElement);

        Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OperationType");
        operationTypeElement.appendChild(requestDoc.createTextNode("ShutdownRolesOperation"));
        shutdownRolesOperationElement.appendChild(operationTypeElement);

        if (parameters.getRoles() != null) {
            if (parameters.getRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getRoles()).isInitialized()) {
                Element rolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Roles");
                for (String rolesItem : parameters.getRoles()) {
                    Element rolesItemElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    rolesItemElement.appendChild(requestDoc.createTextNode(rolesItem));
                    rolesSequenceElement.appendChild(rolesItemElement);
                }
                shutdownRolesOperationElement.appendChild(rolesSequenceElement);
            }
        }

        if (parameters.getPostShutdownAction() != null) {
            Element postShutdownActionElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "PostShutdownAction");
            postShutdownActionElement
                    .appendChild(requestDoc.createTextNode(parameters.getPostShutdownAction().toString()));
            shutdownRolesOperationElement.appendChild(postShutdownActionElement);
        }

        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
            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 Begin Starting Role operation starts the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * start.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginStartingAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginStarting(serviceName, deploymentName, virtualMachineName);
            }
        });
    }

    /**
    * The Begin Starting Role operation starts the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * start.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginStarting(String serviceName, String deploymentName, String virtualMachineName)
            throws IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            CloudTracing.enter(invocationId, this, "beginStartingAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roleinstances/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        url = url + "/Operations";
        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 = "<StartRoleOperation xmlns=\"http://schemas.microsoft.com/windowsazure\"><OperationType>StartRoleOperation</OperationType></StartRoleOperation>";
        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
            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 Begin Starting Roles operation starts the specified set of virtual
    * machines.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Begin Starting
    * Roles operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginStartingRolesAsync(final String serviceName, final String deploymentName,
            final VirtualMachineStartRolesParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginStartingRoles(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Begin Starting Roles operation starts the specified set of virtual
    * machines.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn469419.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Begin Starting
    * Roles 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginStartingRoles(String serviceName, String deploymentName,
            VirtualMachineStartRolesParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginStartingRolesAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/Roles/Operations";
        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 startRolesOperationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "StartRolesOperation");
        requestDoc.appendChild(startRolesOperationElement);

        Element operationTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OperationType");
        operationTypeElement.appendChild(requestDoc.createTextNode("StartRolesOperation"));
        startRolesOperationElement.appendChild(operationTypeElement);

        if (parameters.getRoles() != null) {
            if (parameters.getRoles() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getRoles()).isInitialized()) {
                Element rolesSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Roles");
                for (String rolesItem : parameters.getRoles()) {
                    Element rolesItemElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Name");
                    rolesItemElement.appendChild(requestDoc.createTextNode(rolesItem));
                    rolesSequenceElement.appendChild(rolesItemElement);
                }
                startRolesOperationElement.appendChild(rolesSequenceElement);
            }
        }

        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
            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 Begin Updating Role operation adds a virtual machine to an existing
    * deployment.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of your virtual machine.
    * @param parameters Required. Parameters supplied to the Begin Updating
    * Virtual Machine operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginUpdatingAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName, final VirtualMachineUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginUpdating(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * The Begin Updating Role operation adds a virtual machine to an existing
    * deployment.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of your virtual machine.
    * @param parameters Required. Parameters supplied to the Begin Updating
    * Virtual Machine 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginUpdating(String serviceName, String deploymentName, String virtualMachineName,
            VirtualMachineUpdateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getConfigurationSets() != null) {
            for (ConfigurationSet configurationSetsParameterItem : parameters.getConfigurationSets()) {
                if (configurationSetsParameterItem.getAdditionalUnattendContent() != null) {
                    if (configurationSetsParameterItem.getAdditionalUnattendContent().getUnattendPasses() != null) {
                        for (UnattendPassSettings unattendPassesParameterItem : configurationSetsParameterItem
                                .getAdditionalUnattendContent().getUnattendPasses()) {
                            if (unattendPassesParameterItem.getPassName() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.PassName");
                            }
                            if (unattendPassesParameterItem.getUnattendComponents() != null) {
                                for (UnattendComponent unattendComponentsParameterItem : unattendPassesParameterItem
                                        .getUnattendComponents()) {
                                    if (unattendComponentsParameterItem.getComponentName() == null) {
                                        throw new NullPointerException(
                                                "parameters.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.UnattendComponents.ComponentName");
                                    }
                                    if (unattendComponentsParameterItem.getUnattendComponentSettings() != null) {
                                        for (ComponentSetting unattendComponentSettingsParameterItem : unattendComponentsParameterItem
                                                .getUnattendComponentSettings()) {
                                            if (unattendComponentSettingsParameterItem.getSettingName() == null) {
                                                throw new NullPointerException(
                                                        "parameters.ConfigurationSets.AdditionalUnattendContent.UnattendPasses.UnattendComponents.UnattendComponentSettings.SettingName");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (configurationSetsParameterItem.getDomainJoin() != null) {
                    if (configurationSetsParameterItem.getDomainJoin().getCredentials() != null) {
                        if (configurationSetsParameterItem.getDomainJoin().getCredentials().getPassword() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.DomainJoin.Credentials.Password");
                        }
                        if (configurationSetsParameterItem.getDomainJoin().getCredentials().getUserName() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.DomainJoin.Credentials.UserName");
                        }
                    }
                }
                if (configurationSetsParameterItem.getHostName() != null
                        && configurationSetsParameterItem.getHostName().length() < 1) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.HostName");
                }
                if (configurationSetsParameterItem.getHostName() != null
                        && configurationSetsParameterItem.getHostName().length() > 64) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.HostName");
                }
                if (configurationSetsParameterItem.getSshSettings() != null) {
                    if (configurationSetsParameterItem.getSshSettings().getKeyPairs() != null) {
                        for (SshSettingKeyPair keyPairsParameterItem : configurationSetsParameterItem
                                .getSshSettings().getKeyPairs()) {
                            if (keyPairsParameterItem.getFingerprint() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.KeyPairs.Fingerprint");
                            }
                            if (keyPairsParameterItem.getPath() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.KeyPairs.Path");
                            }
                        }
                    }
                    if (configurationSetsParameterItem.getSshSettings().getPublicKeys() != null) {
                        for (SshSettingPublicKey publicKeysParameterItem : configurationSetsParameterItem
                                .getSshSettings().getPublicKeys()) {
                            if (publicKeysParameterItem.getFingerprint() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.PublicKeys.Fingerprint");
                            }
                            if (publicKeysParameterItem.getPath() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.SshSettings.PublicKeys.Path");
                            }
                        }
                    }
                }
                if (configurationSetsParameterItem.getStoredCertificateSettings() != null) {
                    for (StoredCertificateSettings storedCertificateSettingsParameterItem : configurationSetsParameterItem
                            .getStoredCertificateSettings()) {
                        if (storedCertificateSettingsParameterItem.getStoreName() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.StoredCertificateSettings.StoreName");
                        }
                        if (storedCertificateSettingsParameterItem.getThumbprint() == null) {
                            throw new NullPointerException(
                                    "parameters.ConfigurationSets.StoredCertificateSettings.Thumbprint");
                        }
                    }
                }
                if (configurationSetsParameterItem.getUserName() != null
                        && configurationSetsParameterItem.getUserName().length() < 1) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserName");
                }
                if (configurationSetsParameterItem.getUserName() != null
                        && configurationSetsParameterItem.getUserName().length() > 32) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserName");
                }
                if (configurationSetsParameterItem.getUserPassword() != null
                        && configurationSetsParameterItem.getUserPassword().length() < 6) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword");
                }
                if (configurationSetsParameterItem.getUserPassword() != null
                        && configurationSetsParameterItem.getUserPassword().length() > 72) {
                    throw new IllegalArgumentException("parameters.ConfigurationSets.UserPassword");
                }
                if (configurationSetsParameterItem.getWindowsRemoteManagement() != null) {
                    if (configurationSetsParameterItem.getWindowsRemoteManagement().getListeners() != null) {
                        for (WindowsRemoteManagementListener listenersParameterItem : configurationSetsParameterItem
                                .getWindowsRemoteManagement().getListeners()) {
                            if (listenersParameterItem.getListenerType() == null) {
                                throw new NullPointerException(
                                        "parameters.ConfigurationSets.WindowsRemoteManagement.Listeners.ListenerType");
                            }
                        }
                    }
                }
            }
        }
        if (parameters.getOSVirtualHardDisk() == null) {
            throw new NullPointerException("parameters.OSVirtualHardDisk");
        }
        if (parameters.getRoleName() == null) {
            throw new NullPointerException("parameters.RoleName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginUpdatingAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roles/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

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

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

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

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

        Element roleNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RoleName");
        roleNameElement.appendChild(requestDoc.createTextNode(parameters.getRoleName()));
        persistentVMRoleElement.appendChild(roleNameElement);

        Element roleTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RoleType");
        roleTypeElement.appendChild(requestDoc.createTextNode("PersistentVMRole"));
        persistentVMRoleElement.appendChild(roleTypeElement);

        if (parameters.getConfigurationSets() != null) {
            if (parameters.getConfigurationSets() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getConfigurationSets()).isInitialized()) {
                Element configurationSetsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSets");
                for (ConfigurationSet configurationSetsItem : parameters.getConfigurationSets()) {
                    Element configurationSetElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "ConfigurationSet");
                    configurationSetsSequenceElement.appendChild(configurationSetElement);

                    if (configurationSetsItem.getConfigurationSetType() != null) {
                        Element configurationSetTypeElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "ConfigurationSetType");
                        configurationSetTypeElement.appendChild(
                                requestDoc.createTextNode(configurationSetsItem.getConfigurationSetType()));
                        configurationSetElement.appendChild(configurationSetTypeElement);
                    }

                    if (configurationSetsItem.getInputEndpoints() != null) {
                        if (configurationSetsItem.getInputEndpoints() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getInputEndpoints()).isInitialized()) {
                            Element inputEndpointsSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoints");
                            for (InputEndpoint inputEndpointsItem : configurationSetsItem.getInputEndpoints()) {
                                Element inputEndpointElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                                inputEndpointsSequenceElement.appendChild(inputEndpointElement);

                                if (inputEndpointsItem.getLoadBalancedEndpointSetName() != null) {
                                    Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancedEndpointSetName");
                                    loadBalancedEndpointSetNameElement.appendChild(requestDoc
                                            .createTextNode(inputEndpointsItem.getLoadBalancedEndpointSetName()));
                                    inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement);
                                }

                                if (inputEndpointsItem.getLocalPort() != null) {
                                    Element localPortElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "LocalPort");
                                    localPortElement.appendChild(requestDoc
                                            .createTextNode(Integer.toString(inputEndpointsItem.getLocalPort())));
                                    inputEndpointElement.appendChild(localPortElement);
                                }

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

                                if (inputEndpointsItem.getPort() != null) {
                                    Element portElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                                    portElement.appendChild(requestDoc
                                            .createTextNode(Integer.toString(inputEndpointsItem.getPort())));
                                    inputEndpointElement.appendChild(portElement);
                                }

                                if (inputEndpointsItem.getLoadBalancerProbe() != null) {
                                    Element loadBalancerProbeElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe");
                                    inputEndpointElement.appendChild(loadBalancerProbeElement);

                                    if (inputEndpointsItem.getLoadBalancerProbe().getPath() != null) {
                                        Element pathElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Path");
                                        pathElement.appendChild(requestDoc.createTextNode(
                                                inputEndpointsItem.getLoadBalancerProbe().getPath()));
                                        loadBalancerProbeElement.appendChild(pathElement);
                                    }

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

                                    if (inputEndpointsItem.getLoadBalancerProbe().getProtocol() != null) {
                                        Element protocolElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "Protocol");
                                        protocolElement
                                                .appendChild(requestDoc.createTextNode(ComputeManagementClientImpl
                                                        .loadBalancerProbeTransportProtocolToString(
                                                                inputEndpointsItem.getLoadBalancerProbe()
                                                                        .getProtocol())));
                                        loadBalancerProbeElement.appendChild(protocolElement);
                                    }

                                    if (inputEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) {
                                        Element intervalInSecondsElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds");
                                        intervalInSecondsElement.appendChild(
                                                requestDoc.createTextNode(Integer.toString(inputEndpointsItem
                                                        .getLoadBalancerProbe().getIntervalInSeconds())));
                                        loadBalancerProbeElement.appendChild(intervalInSecondsElement);
                                    }

                                    if (inputEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) {
                                        Element timeoutInSecondsElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds");
                                        timeoutInSecondsElement.appendChild(
                                                requestDoc.createTextNode(Integer.toString(inputEndpointsItem
                                                        .getLoadBalancerProbe().getTimeoutInSeconds())));
                                        loadBalancerProbeElement.appendChild(timeoutInSecondsElement);
                                    }
                                }

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

                                if (inputEndpointsItem.getVirtualIPAddress() != null) {
                                    Element vipElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Vip");
                                    vipElement.appendChild(requestDoc.createTextNode(
                                            inputEndpointsItem.getVirtualIPAddress().getHostAddress()));
                                    inputEndpointElement.appendChild(vipElement);
                                }

                                if (inputEndpointsItem.isEnableDirectServerReturn() != null) {
                                    Element enableDirectServerReturnElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "EnableDirectServerReturn");
                                    enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(
                                            Boolean.toString(inputEndpointsItem.isEnableDirectServerReturn())
                                                    .toLowerCase()));
                                    inputEndpointElement.appendChild(enableDirectServerReturnElement);
                                }

                                if (inputEndpointsItem.getLoadBalancerName() != null) {
                                    Element loadBalancerNameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "LoadBalancerName");
                                    loadBalancerNameElement.appendChild(
                                            requestDoc.createTextNode(inputEndpointsItem.getLoadBalancerName()));
                                    inputEndpointElement.appendChild(loadBalancerNameElement);
                                }

                                if (inputEndpointsItem.getEndpointAcl() != null) {
                                    Element endpointAclElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "EndpointAcl");
                                    inputEndpointElement.appendChild(endpointAclElement);

                                    if (inputEndpointsItem.getEndpointAcl().getRules() != null) {
                                        if (inputEndpointsItem.getEndpointAcl()
                                                .getRules() instanceof LazyCollection == false
                                                || ((LazyCollection) inputEndpointsItem.getEndpointAcl().getRules())
                                                        .isInitialized()) {
                                            Element rulesSequenceElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Rules");
                                            for (AccessControlListRule rulesItem : inputEndpointsItem
                                                    .getEndpointAcl().getRules()) {
                                                Element ruleElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure", "Rule");
                                                rulesSequenceElement.appendChild(ruleElement);

                                                if (rulesItem.getOrder() != null) {
                                                    Element orderElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure", "Order");
                                                    orderElement.appendChild(requestDoc.createTextNode(
                                                            Integer.toString(rulesItem.getOrder())));
                                                    ruleElement.appendChild(orderElement);
                                                }

                                                if (rulesItem.getAction() != null) {
                                                    Element actionElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure", "Action");
                                                    actionElement.appendChild(
                                                            requestDoc.createTextNode(rulesItem.getAction()));
                                                    ruleElement.appendChild(actionElement);
                                                }

                                                if (rulesItem.getRemoteSubnet() != null) {
                                                    Element remoteSubnetElement = requestDoc.createElementNS(
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "RemoteSubnet");
                                                    remoteSubnetElement.appendChild(
                                                            requestDoc.createTextNode(rulesItem.getRemoteSubnet()));
                                                    ruleElement.appendChild(remoteSubnetElement);
                                                }

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

                                if (inputEndpointsItem.getIdleTimeoutInMinutes() != null) {
                                    Element idleTimeoutInMinutesElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                                    idleTimeoutInMinutesElement.appendChild(requestDoc.createTextNode(
                                            Integer.toString(inputEndpointsItem.getIdleTimeoutInMinutes())));
                                    inputEndpointElement.appendChild(idleTimeoutInMinutesElement);
                                }

                                if (inputEndpointsItem.getLoadBalancerDistribution() != null) {
                                    Element loadBalancerDistributionElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancerDistribution");
                                    loadBalancerDistributionElement.appendChild(requestDoc
                                            .createTextNode(inputEndpointsItem.getLoadBalancerDistribution()));
                                    inputEndpointElement.appendChild(loadBalancerDistributionElement);
                                }

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

                    if (configurationSetsItem.getSubnetNames() != null) {
                        if (configurationSetsItem.getSubnetNames() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getSubnetNames()).isInitialized()) {
                            Element subnetNamesSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetNames");
                            for (String subnetNamesItem : configurationSetsItem.getSubnetNames()) {
                                Element subnetNamesItemElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "SubnetName");
                                subnetNamesItemElement.appendChild(requestDoc.createTextNode(subnetNamesItem));
                                subnetNamesSequenceElement.appendChild(subnetNamesItemElement);
                            }
                            configurationSetElement.appendChild(subnetNamesSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getStaticVirtualNetworkIPAddress() != null) {
                        Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
                        staticVirtualNetworkIPAddressElement.appendChild(requestDoc
                                .createTextNode(configurationSetsItem.getStaticVirtualNetworkIPAddress()));
                        configurationSetElement.appendChild(staticVirtualNetworkIPAddressElement);
                    }

                    if (configurationSetsItem.getPublicIPs() != null) {
                        if (configurationSetsItem.getPublicIPs() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getPublicIPs()).isInitialized()) {
                            Element publicIPsSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicIPs");
                            for (ConfigurationSet.PublicIP publicIPsItem : configurationSetsItem.getPublicIPs()) {
                                Element publicIPElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicIP");
                                publicIPsSequenceElement.appendChild(publicIPElement);

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

                                if (publicIPsItem.getIdleTimeoutInMinutes() != null) {
                                    Element idleTimeoutInMinutesElement2 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                                    idleTimeoutInMinutesElement2.appendChild(requestDoc.createTextNode(
                                            Integer.toString(publicIPsItem.getIdleTimeoutInMinutes())));
                                    publicIPElement.appendChild(idleTimeoutInMinutesElement2);
                                }

                                if (publicIPsItem.getDomainNameLabel() != null) {
                                    Element domainNameLabelElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "DomainNameLabel");
                                    domainNameLabelElement.appendChild(
                                            requestDoc.createTextNode(publicIPsItem.getDomainNameLabel()));
                                    publicIPElement.appendChild(domainNameLabelElement);
                                }
                            }
                            configurationSetElement.appendChild(publicIPsSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getNetworkInterfaces() != null) {
                        if (configurationSetsItem.getNetworkInterfaces() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getNetworkInterfaces())
                                        .isInitialized()) {
                            Element networkInterfacesSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "NetworkInterfaces");
                            for (NetworkInterface networkInterfacesItem : configurationSetsItem
                                    .getNetworkInterfaces()) {
                                Element networkInterfaceElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "NetworkInterface");
                                networkInterfacesSequenceElement.appendChild(networkInterfaceElement);

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

                                if (networkInterfacesItem.getIPConfigurations() != null) {
                                    if (networkInterfacesItem
                                            .getIPConfigurations() instanceof LazyCollection == false
                                            || ((LazyCollection) networkInterfacesItem.getIPConfigurations())
                                                    .isInitialized()) {
                                        Element iPConfigurationsSequenceElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure", "IPConfigurations");
                                        for (IPConfiguration iPConfigurationsItem : networkInterfacesItem
                                                .getIPConfigurations()) {
                                            Element iPConfigurationElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "IPConfiguration");
                                            iPConfigurationsSequenceElement.appendChild(iPConfigurationElement);

                                            if (iPConfigurationsItem.getSubnetName() != null) {
                                                Element subnetNameElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure", "SubnetName");
                                                subnetNameElement.appendChild(requestDoc
                                                        .createTextNode(iPConfigurationsItem.getSubnetName()));
                                                iPConfigurationElement.appendChild(subnetNameElement);
                                            }

                                            if (iPConfigurationsItem.getStaticVirtualNetworkIPAddress() != null) {
                                                Element staticVirtualNetworkIPAddressElement2 = requestDoc
                                                        .createElementNS(
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "StaticVirtualNetworkIPAddress");
                                                staticVirtualNetworkIPAddressElement2
                                                        .appendChild(requestDoc.createTextNode(iPConfigurationsItem
                                                                .getStaticVirtualNetworkIPAddress()));
                                                iPConfigurationElement
                                                        .appendChild(staticVirtualNetworkIPAddressElement2);
                                            }
                                        }
                                        networkInterfaceElement.appendChild(iPConfigurationsSequenceElement);
                                    }
                                }

                                if (networkInterfacesItem.getNetworkSecurityGroup() != null) {
                                    Element networkSecurityGroupElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                                    networkSecurityGroupElement.appendChild(requestDoc
                                            .createTextNode(networkInterfacesItem.getNetworkSecurityGroup()));
                                    networkInterfaceElement.appendChild(networkSecurityGroupElement);
                                }

                                if (networkInterfacesItem.getIPForwarding() != null) {
                                    Element iPForwardingElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "IPForwarding");
                                    iPForwardingElement.appendChild(
                                            requestDoc.createTextNode(networkInterfacesItem.getIPForwarding()));
                                    networkInterfaceElement.appendChild(iPForwardingElement);
                                }
                            }
                            configurationSetElement.appendChild(networkInterfacesSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getNetworkSecurityGroup() != null) {
                        Element networkSecurityGroupElement2 = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "NetworkSecurityGroup");
                        networkSecurityGroupElement2.appendChild(
                                requestDoc.createTextNode(configurationSetsItem.getNetworkSecurityGroup()));
                        configurationSetElement.appendChild(networkSecurityGroupElement2);
                    }

                    if (configurationSetsItem.getIPForwarding() != null) {
                        Element iPForwardingElement2 = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "IPForwarding");
                        iPForwardingElement2
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getIPForwarding()));
                        configurationSetElement.appendChild(iPForwardingElement2);
                    }

                    if (configurationSetsItem.getComputerName() != null) {
                        Element computerNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ComputerName");
                        computerNameElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getComputerName()));
                        configurationSetElement.appendChild(computerNameElement);
                    }

                    if (configurationSetsItem.getAdminPassword() != null) {
                        Element adminPasswordElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "AdminPassword");
                        adminPasswordElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminPassword()));
                        configurationSetElement.appendChild(adminPasswordElement);
                    }

                    if (configurationSetsItem.isResetPasswordOnFirstLogon() != null) {
                        Element resetPasswordOnFirstLogonElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "ResetPasswordOnFirstLogon");
                        resetPasswordOnFirstLogonElement.appendChild(requestDoc.createTextNode(Boolean
                                .toString(configurationSetsItem.isResetPasswordOnFirstLogon()).toLowerCase()));
                        configurationSetElement.appendChild(resetPasswordOnFirstLogonElement);
                    }

                    if (configurationSetsItem.isEnableAutomaticUpdates() != null) {
                        Element enableAutomaticUpdatesElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "EnableAutomaticUpdates");
                        enableAutomaticUpdatesElement.appendChild(requestDoc.createTextNode(
                                Boolean.toString(configurationSetsItem.isEnableAutomaticUpdates()).toLowerCase()));
                        configurationSetElement.appendChild(enableAutomaticUpdatesElement);
                    }

                    if (configurationSetsItem.getTimeZone() != null) {
                        Element timeZoneElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "TimeZone");
                        timeZoneElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getTimeZone()));
                        configurationSetElement.appendChild(timeZoneElement);
                    }

                    if (configurationSetsItem.getDomainJoin() != null) {
                        Element domainJoinElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DomainJoin");
                        configurationSetElement.appendChild(domainJoinElement);

                        if (configurationSetsItem.getDomainJoin().getCredentials() != null) {
                            Element credentialsElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Credentials");
                            domainJoinElement.appendChild(credentialsElement);

                            if (configurationSetsItem.getDomainJoin().getCredentials().getDomain() != null) {
                                Element domainElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Domain");
                                domainElement.appendChild(requestDoc.createTextNode(
                                        configurationSetsItem.getDomainJoin().getCredentials().getDomain()));
                                credentialsElement.appendChild(domainElement);
                            }

                            Element usernameElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Username");
                            usernameElement.appendChild(requestDoc.createTextNode(
                                    configurationSetsItem.getDomainJoin().getCredentials().getUserName()));
                            credentialsElement.appendChild(usernameElement);

                            Element passwordElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Password");
                            passwordElement.appendChild(requestDoc.createTextNode(
                                    configurationSetsItem.getDomainJoin().getCredentials().getPassword()));
                            credentialsElement.appendChild(passwordElement);
                        }

                        if (configurationSetsItem.getDomainJoin().getDomainToJoin() != null) {
                            Element joinDomainElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "JoinDomain");
                            joinDomainElement.appendChild(requestDoc
                                    .createTextNode(configurationSetsItem.getDomainJoin().getDomainToJoin()));
                            domainJoinElement.appendChild(joinDomainElement);
                        }

                        if (configurationSetsItem.getDomainJoin().getLdapMachineObjectOU() != null) {
                            Element machineObjectOUElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "MachineObjectOU");
                            machineObjectOUElement.appendChild(requestDoc.createTextNode(
                                    configurationSetsItem.getDomainJoin().getLdapMachineObjectOU()));
                            domainJoinElement.appendChild(machineObjectOUElement);
                        }

                        if (configurationSetsItem.getDomainJoin().getProvisioning() != null) {
                            Element provisioningElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Provisioning");
                            domainJoinElement.appendChild(provisioningElement);

                            if (configurationSetsItem.getDomainJoin().getProvisioning().getAccountData() != null) {
                                Element accountDataElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "AccountData");
                                accountDataElement.appendChild(requestDoc.createTextNode(
                                        configurationSetsItem.getDomainJoin().getProvisioning().getAccountData()));
                                provisioningElement.appendChild(accountDataElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getStoredCertificateSettings() != null) {
                        if (configurationSetsItem.getStoredCertificateSettings() instanceof LazyCollection == false
                                || ((LazyCollection) configurationSetsItem.getStoredCertificateSettings())
                                        .isInitialized()) {
                            Element storedCertificateSettingsSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "StoredCertificateSettings");
                            for (StoredCertificateSettings storedCertificateSettingsItem : configurationSetsItem
                                    .getStoredCertificateSettings()) {
                                Element certificateSettingElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "CertificateSetting");
                                storedCertificateSettingsSequenceElement.appendChild(certificateSettingElement);

                                Element storeLocationElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure", "StoreLocation");
                                storeLocationElement.appendChild(requestDoc.createTextNode("LocalMachine"));
                                certificateSettingElement.appendChild(storeLocationElement);

                                Element storeNameElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "StoreName");
                                storeNameElement.appendChild(
                                        requestDoc.createTextNode(storedCertificateSettingsItem.getStoreName()));
                                certificateSettingElement.appendChild(storeNameElement);

                                Element thumbprintElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Thumbprint");
                                thumbprintElement.appendChild(
                                        requestDoc.createTextNode(storedCertificateSettingsItem.getThumbprint()));
                                certificateSettingElement.appendChild(thumbprintElement);
                            }
                            configurationSetElement.appendChild(storedCertificateSettingsSequenceElement);
                        }
                    }

                    if (configurationSetsItem.getWindowsRemoteManagement() != null) {
                        Element winRMElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "WinRM");
                        configurationSetElement.appendChild(winRMElement);

                        if (configurationSetsItem.getWindowsRemoteManagement().getListeners() != null) {
                            if (configurationSetsItem.getWindowsRemoteManagement()
                                    .getListeners() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getWindowsRemoteManagement()
                                            .getListeners()).isInitialized()) {
                                Element listenersSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Listeners");
                                for (WindowsRemoteManagementListener listenersItem : configurationSetsItem
                                        .getWindowsRemoteManagement().getListeners()) {
                                    Element listenerElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Listener");
                                    listenersSequenceElement.appendChild(listenerElement);

                                    if (listenersItem.getCertificateThumbprint() != null) {
                                        Element certificateThumbprintElement = requestDoc.createElementNS(
                                                "http://schemas.microsoft.com/windowsazure",
                                                "CertificateThumbprint");
                                        certificateThumbprintElement.appendChild(requestDoc
                                                .createTextNode(listenersItem.getCertificateThumbprint()));
                                        listenerElement.appendChild(certificateThumbprintElement);
                                    }

                                    Element protocolElement3 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Protocol");
                                    protocolElement3.appendChild(
                                            requestDoc.createTextNode(listenersItem.getListenerType().toString()));
                                    listenerElement.appendChild(protocolElement3);
                                }
                                winRMElement.appendChild(listenersSequenceElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getAdminUserName() != null) {
                        Element adminUsernameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "AdminUsername");
                        adminUsernameElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getAdminUserName()));
                        configurationSetElement.appendChild(adminUsernameElement);
                    }

                    if (configurationSetsItem.getAdditionalUnattendContent() != null) {
                        Element additionalUnattendContentElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "AdditionalUnattendContent");
                        configurationSetElement.appendChild(additionalUnattendContentElement);

                        if (configurationSetsItem.getAdditionalUnattendContent().getUnattendPasses() != null) {
                            if (configurationSetsItem.getAdditionalUnattendContent()
                                    .getUnattendPasses() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getAdditionalUnattendContent()
                                            .getUnattendPasses()).isInitialized()) {
                                Element passesSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Passes");
                                for (UnattendPassSettings passesItem : configurationSetsItem
                                        .getAdditionalUnattendContent().getUnattendPasses()) {
                                    Element unattendPassElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "UnattendPass");
                                    passesSequenceElement.appendChild(unattendPassElement);

                                    Element passNameElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "PassName");
                                    passNameElement
                                            .appendChild(requestDoc.createTextNode(passesItem.getPassName()));
                                    unattendPassElement.appendChild(passNameElement);

                                    if (passesItem.getUnattendComponents() != null) {
                                        if (passesItem.getUnattendComponents() instanceof LazyCollection == false
                                                || ((LazyCollection) passesItem.getUnattendComponents())
                                                        .isInitialized()) {
                                            Element componentsSequenceElement = requestDoc.createElementNS(
                                                    "http://schemas.microsoft.com/windowsazure", "Components");
                                            for (UnattendComponent componentsItem : passesItem
                                                    .getUnattendComponents()) {
                                                Element unattendComponentElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "UnattendComponent");
                                                componentsSequenceElement.appendChild(unattendComponentElement);

                                                Element componentNameElement = requestDoc.createElementNS(
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "ComponentName");
                                                componentNameElement.appendChild(requestDoc
                                                        .createTextNode(componentsItem.getComponentName()));
                                                unattendComponentElement.appendChild(componentNameElement);

                                                if (componentsItem.getUnattendComponentSettings() != null) {
                                                    if (componentsItem
                                                            .getUnattendComponentSettings() instanceof LazyCollection == false
                                                            || ((LazyCollection) componentsItem
                                                                    .getUnattendComponentSettings())
                                                                            .isInitialized()) {
                                                        Element componentSettingsSequenceElement = requestDoc
                                                                .createElementNS(
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "ComponentSettings");
                                                        for (ComponentSetting componentSettingsItem : componentsItem
                                                                .getUnattendComponentSettings()) {
                                                            Element componentSettingElement = requestDoc
                                                                    .createElementNS(
                                                                            "http://schemas.microsoft.com/windowsazure",
                                                                            "ComponentSetting");
                                                            componentSettingsSequenceElement
                                                                    .appendChild(componentSettingElement);

                                                            Element settingNameElement = requestDoc.createElementNS(
                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                    "SettingName");
                                                            settingNameElement.appendChild(
                                                                    requestDoc.createTextNode(componentSettingsItem
                                                                            .getSettingName()));
                                                            componentSettingElement.appendChild(settingNameElement);

                                                            if (componentSettingsItem.getContent() != null) {
                                                                Element contentElement = requestDoc.createElementNS(
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "Content");
                                                                contentElement
                                                                        .appendChild(requestDoc.createTextNode(
                                                                                Base64.encode(componentSettingsItem
                                                                                        .getContent().getBytes())));
                                                                componentSettingElement.appendChild(contentElement);
                                                            }
                                                        }
                                                        unattendComponentElement
                                                                .appendChild(componentSettingsSequenceElement);
                                                    }
                                                }
                                            }
                                            unattendPassElement.appendChild(componentsSequenceElement);
                                        }
                                    }
                                }
                                additionalUnattendContentElement.appendChild(passesSequenceElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getHostName() != null) {
                        Element hostNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostName");
                        hostNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getHostName()));
                        configurationSetElement.appendChild(hostNameElement);
                    }

                    if (configurationSetsItem.getUserName() != null) {
                        Element userNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "UserName");
                        userNameElement.appendChild(requestDoc.createTextNode(configurationSetsItem.getUserName()));
                        configurationSetElement.appendChild(userNameElement);
                    }

                    if (configurationSetsItem.getUserPassword() != null) {
                        Element userPasswordElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "UserPassword");
                        userPasswordElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getUserPassword()));
                        configurationSetElement.appendChild(userPasswordElement);
                    }

                    if (configurationSetsItem.isDisableSshPasswordAuthentication() != null) {
                        Element disableSshPasswordAuthenticationElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "DisableSshPasswordAuthentication");
                        disableSshPasswordAuthenticationElement.appendChild(requestDoc.createTextNode(
                                Boolean.toString(configurationSetsItem.isDisableSshPasswordAuthentication())
                                        .toLowerCase()));
                        configurationSetElement.appendChild(disableSshPasswordAuthenticationElement);
                    }

                    if (configurationSetsItem.getSshSettings() != null) {
                        Element sSHElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                                "SSH");
                        configurationSetElement.appendChild(sSHElement);

                        if (configurationSetsItem.getSshSettings().getPublicKeys() != null) {
                            if (configurationSetsItem.getSshSettings()
                                    .getPublicKeys() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getSshSettings().getPublicKeys())
                                            .isInitialized()) {
                                Element publicKeysSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "PublicKeys");
                                for (SshSettingPublicKey publicKeysItem : configurationSetsItem.getSshSettings()
                                        .getPublicKeys()) {
                                    Element publicKeyElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "PublicKey");
                                    publicKeysSequenceElement.appendChild(publicKeyElement);

                                    Element fingerprintElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Fingerprint");
                                    fingerprintElement.appendChild(
                                            requestDoc.createTextNode(publicKeysItem.getFingerprint()));
                                    publicKeyElement.appendChild(fingerprintElement);

                                    Element pathElement2 = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                                    pathElement2.appendChild(requestDoc.createTextNode(publicKeysItem.getPath()));
                                    publicKeyElement.appendChild(pathElement2);
                                }
                                sSHElement.appendChild(publicKeysSequenceElement);
                            }
                        }

                        if (configurationSetsItem.getSshSettings().getKeyPairs() != null) {
                            if (configurationSetsItem.getSshSettings()
                                    .getKeyPairs() instanceof LazyCollection == false
                                    || ((LazyCollection) configurationSetsItem.getSshSettings().getKeyPairs())
                                            .isInitialized()) {
                                Element keyPairsSequenceElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "KeyPairs");
                                for (SshSettingKeyPair keyPairsItem : configurationSetsItem.getSshSettings()
                                        .getKeyPairs()) {
                                    Element keyPairElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "KeyPair");
                                    keyPairsSequenceElement.appendChild(keyPairElement);

                                    Element fingerprintElement2 = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "Fingerprint");
                                    fingerprintElement2
                                            .appendChild(requestDoc.createTextNode(keyPairsItem.getFingerprint()));
                                    keyPairElement.appendChild(fingerprintElement2);

                                    Element pathElement3 = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                                    pathElement3.appendChild(requestDoc.createTextNode(keyPairsItem.getPath()));
                                    keyPairElement.appendChild(pathElement3);
                                }
                                sSHElement.appendChild(keyPairsSequenceElement);
                            }
                        }
                    }

                    if (configurationSetsItem.getCustomData() != null) {
                        Element customDataElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "CustomData");
                        customDataElement
                                .appendChild(requestDoc.createTextNode(configurationSetsItem.getCustomData()));
                        configurationSetElement.appendChild(customDataElement);
                    }
                }
                persistentVMRoleElement.appendChild(configurationSetsSequenceElement);
            }
        }

        if (parameters.getResourceExtensionReferences() != null) {
            if (parameters.getResourceExtensionReferences() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getResourceExtensionReferences()).isInitialized()) {
                Element resourceExtensionReferencesSequenceElement = requestDoc.createElementNS(
                        "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReferences");
                for (ResourceExtensionReference resourceExtensionReferencesItem : parameters
                        .getResourceExtensionReferences()) {
                    Element resourceExtensionReferenceElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "ResourceExtensionReference");
                    resourceExtensionReferencesSequenceElement.appendChild(resourceExtensionReferenceElement);

                    if (resourceExtensionReferencesItem.getReferenceName() != null) {
                        Element referenceNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ReferenceName");
                        referenceNameElement.appendChild(
                                requestDoc.createTextNode(resourceExtensionReferencesItem.getReferenceName()));
                        resourceExtensionReferenceElement.appendChild(referenceNameElement);
                    }

                    if (resourceExtensionReferencesItem.getPublisher() != null) {
                        Element publisherElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Publisher");
                        publisherElement.appendChild(
                                requestDoc.createTextNode(resourceExtensionReferencesItem.getPublisher()));
                        resourceExtensionReferenceElement.appendChild(publisherElement);
                    }

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

                    if (resourceExtensionReferencesItem.getVersion() != null) {
                        Element versionElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
                        versionElement.appendChild(
                                requestDoc.createTextNode(resourceExtensionReferencesItem.getVersion()));
                        resourceExtensionReferenceElement.appendChild(versionElement);
                    }

                    if (resourceExtensionReferencesItem.getResourceExtensionParameterValues() != null) {
                        if (resourceExtensionReferencesItem
                                .getResourceExtensionParameterValues() instanceof LazyCollection == false
                                || ((LazyCollection) resourceExtensionReferencesItem
                                        .getResourceExtensionParameterValues()).isInitialized()) {
                            Element resourceExtensionParameterValuesSequenceElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure",
                                    "ResourceExtensionParameterValues");
                            for (ResourceExtensionParameterValue resourceExtensionParameterValuesItem : resourceExtensionReferencesItem
                                    .getResourceExtensionParameterValues()) {
                                Element resourceExtensionParameterValueElement = requestDoc.createElementNS(
                                        "http://schemas.microsoft.com/windowsazure",
                                        "ResourceExtensionParameterValue");
                                resourceExtensionParameterValuesSequenceElement
                                        .appendChild(resourceExtensionParameterValueElement);

                                if (resourceExtensionParameterValuesItem.getKey() != null) {
                                    Element keyElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Key");
                                    keyElement.appendChild(requestDoc
                                            .createTextNode(resourceExtensionParameterValuesItem.getKey()));
                                    resourceExtensionParameterValueElement.appendChild(keyElement);
                                }

                                if (resourceExtensionParameterValuesItem.getValue() != null) {
                                    Element valueElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Value");
                                    valueElement.appendChild(requestDoc.createTextNode(Base64
                                            .encode(resourceExtensionParameterValuesItem.getValue().getBytes())));
                                    resourceExtensionParameterValueElement.appendChild(valueElement);
                                }

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

                    if (resourceExtensionReferencesItem.getState() != null) {
                        Element stateElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "State");
                        stateElement
                                .appendChild(requestDoc.createTextNode(resourceExtensionReferencesItem.getState()));
                        resourceExtensionReferenceElement.appendChild(stateElement);
                    }

                    if (resourceExtensionReferencesItem.isForceUpdate() != null) {
                        Element forceUpdateElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "ForceUpdate");
                        forceUpdateElement.appendChild(requestDoc.createTextNode(
                                Boolean.toString(resourceExtensionReferencesItem.isForceUpdate()).toLowerCase()));
                        resourceExtensionReferenceElement.appendChild(forceUpdateElement);
                    }
                }
                persistentVMRoleElement.appendChild(resourceExtensionReferencesSequenceElement);
            }
        }

        if (parameters.getAvailabilitySetName() != null) {
            Element availabilitySetNameElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "AvailabilitySetName");
            availabilitySetNameElement.appendChild(requestDoc.createTextNode(parameters.getAvailabilitySetName()));
            persistentVMRoleElement.appendChild(availabilitySetNameElement);
        }

        if (parameters.getDataVirtualHardDisks() != null) {
            if (parameters.getDataVirtualHardDisks() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getDataVirtualHardDisks()).isInitialized()) {
                Element dataVirtualHardDisksSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisks");
                for (DataVirtualHardDisk dataVirtualHardDisksItem : parameters.getDataVirtualHardDisks()) {
                    Element dataVirtualHardDiskElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk");
                    dataVirtualHardDisksSequenceElement.appendChild(dataVirtualHardDiskElement);

                    if (dataVirtualHardDisksItem.getHostCaching() != null) {
                        Element hostCachingElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "HostCaching");
                        hostCachingElement
                                .appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getHostCaching()));
                        dataVirtualHardDiskElement.appendChild(hostCachingElement);
                    }

                    if (dataVirtualHardDisksItem.getLabel() != null) {
                        Element diskLabelElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskLabel");
                        diskLabelElement
                                .appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getLabel()));
                        dataVirtualHardDiskElement.appendChild(diskLabelElement);
                    }

                    if (dataVirtualHardDisksItem.getName() != null) {
                        Element diskNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "DiskName");
                        diskNameElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getName()));
                        dataVirtualHardDiskElement.appendChild(diskNameElement);
                    }

                    if (dataVirtualHardDisksItem.getLogicalUnitNumber() != null) {
                        Element lunElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                                "Lun");
                        lunElement.appendChild(requestDoc
                                .createTextNode(Integer.toString(dataVirtualHardDisksItem.getLogicalUnitNumber())));
                        dataVirtualHardDiskElement.appendChild(lunElement);
                    }

                    if (dataVirtualHardDisksItem.getLogicalDiskSizeInGB() != null) {
                        Element logicalDiskSizeInGBElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB");
                        logicalDiskSizeInGBElement.appendChild(requestDoc.createTextNode(
                                Integer.toString(dataVirtualHardDisksItem.getLogicalDiskSizeInGB())));
                        dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement);
                    }

                    if (dataVirtualHardDisksItem.getMediaLink() != null) {
                        Element mediaLinkElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink");
                        mediaLinkElement.appendChild(
                                requestDoc.createTextNode(dataVirtualHardDisksItem.getMediaLink().toString()));
                        dataVirtualHardDiskElement.appendChild(mediaLinkElement);
                    }

                    if (dataVirtualHardDisksItem.getSourceMediaLink() != null) {
                        Element sourceMediaLinkElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "SourceMediaLink");
                        sourceMediaLinkElement.appendChild(requestDoc
                                .createTextNode(dataVirtualHardDisksItem.getSourceMediaLink().toString()));
                        dataVirtualHardDiskElement.appendChild(sourceMediaLinkElement);
                    }

                    if (dataVirtualHardDisksItem.getIOType() != null) {
                        Element iOTypeElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "IOType");
                        iOTypeElement.appendChild(requestDoc.createTextNode(dataVirtualHardDisksItem.getIOType()));
                        dataVirtualHardDiskElement.appendChild(iOTypeElement);
                    }
                }
                persistentVMRoleElement.appendChild(dataVirtualHardDisksSequenceElement);
            }
        }

        Element oSVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "OSVirtualHardDisk");
        persistentVMRoleElement.appendChild(oSVirtualHardDiskElement);

        if (parameters.getOSVirtualHardDisk().getHostCaching() != null) {
            Element hostCachingElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "HostCaching");
            hostCachingElement2
                    .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getHostCaching()));
            oSVirtualHardDiskElement.appendChild(hostCachingElement2);
        }

        if (parameters.getOSVirtualHardDisk().getLabel() != null) {
            Element diskLabelElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "DiskLabel");
            diskLabelElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getLabel()));
            oSVirtualHardDiskElement.appendChild(diskLabelElement2);
        }

        if (parameters.getOSVirtualHardDisk().getName() != null) {
            Element diskNameElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "DiskName");
            diskNameElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getName()));
            oSVirtualHardDiskElement.appendChild(diskNameElement2);
        }

        if (parameters.getOSVirtualHardDisk().getMediaLink() != null) {
            Element mediaLinkElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "MediaLink");
            mediaLinkElement2.appendChild(
                    requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getMediaLink().toString()));
            oSVirtualHardDiskElement.appendChild(mediaLinkElement2);
        }

        if (parameters.getOSVirtualHardDisk().getSourceImageName() != null) {
            Element sourceImageNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SourceImageName");
            sourceImageNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getSourceImageName()));
            oSVirtualHardDiskElement.appendChild(sourceImageNameElement);
        }

        if (parameters.getOSVirtualHardDisk().getOperatingSystem() != null) {
            Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
            osElement
                    .appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getOperatingSystem()));
            oSVirtualHardDiskElement.appendChild(osElement);
        }

        if (parameters.getOSVirtualHardDisk().getRemoteSourceImageLink() != null) {
            Element remoteSourceImageLinkElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "RemoteSourceImageLink");
            remoteSourceImageLinkElement.appendChild(requestDoc
                    .createTextNode(parameters.getOSVirtualHardDisk().getRemoteSourceImageLink().toString()));
            oSVirtualHardDiskElement.appendChild(remoteSourceImageLinkElement);
        }

        if (parameters.getOSVirtualHardDisk().getIOType() != null) {
            Element iOTypeElement2 = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "IOType");
            iOTypeElement2.appendChild(requestDoc.createTextNode(parameters.getOSVirtualHardDisk().getIOType()));
            oSVirtualHardDiskElement.appendChild(iOTypeElement2);
        }

        if (parameters.getOSVirtualHardDisk().getResizedSizeInGB() != null) {
            Element resizedSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ResizedSizeInGB");
            resizedSizeInGBElement.appendChild(requestDoc
                    .createTextNode(Integer.toString(parameters.getOSVirtualHardDisk().getResizedSizeInGB())));
            oSVirtualHardDiskElement.appendChild(resizedSizeInGBElement);
        }

        if (parameters.getRoleSize() != null) {
            Element roleSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "RoleSize");
            roleSizeElement.appendChild(requestDoc.createTextNode(parameters.getRoleSize()));
            persistentVMRoleElement.appendChild(roleSizeElement);
        }

        if (parameters.isProvisionGuestAgent() != null) {
            Element provisionGuestAgentElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "ProvisionGuestAgent");
            provisionGuestAgentElement.appendChild(
                    requestDoc.createTextNode(Boolean.toString(parameters.isProvisionGuestAgent()).toLowerCase()));
            persistentVMRoleElement.appendChild(provisionGuestAgentElement);
        }

        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
            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 Begin Updating Load Balanced Endpoint Set operation changes the
    * specified load-balanced InputEndpoints on all the roles of an
    * Infrastructure as a Service deployment. Non-load-balanced endpoints must
    * be changed using UpdateRole.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Begin Updating
    * Load Balanced Endpoint Set operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginUpdatingLoadBalancedEndpointSetAsync(final String serviceName,
            final String deploymentName, final VirtualMachineUpdateLoadBalancedSetParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginUpdatingLoadBalancedEndpointSet(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Begin Updating Load Balanced Endpoint Set operation changes the
    * specified load-balanced InputEndpoints on all the roles of an
    * Infrastructure as a Service deployment. Non-load-balanced endpoints must
    * be changed using UpdateRole.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/dn469417.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Begin Updating
    * Load Balanced Endpoint Set 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse beginUpdatingLoadBalancedEndpointSet(String serviceName, String deploymentName,
            VirtualMachineUpdateLoadBalancedSetParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getLoadBalancedEndpoints() != null) {
            for (VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint loadBalancedEndpointsParameterItem : parameters
                    .getLoadBalancedEndpoints()) {
                if (loadBalancedEndpointsParameterItem.getLoadBalancedEndpointSetName() == null) {
                    throw new NullPointerException("parameters.LoadBalancedEndpoints.LoadBalancedEndpointSetName");
                }
            }
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "beginUpdatingLoadBalancedEndpointSetAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("comp=UpdateLbSet");
        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 loadBalancedEndpointListElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointList");
        requestDoc.appendChild(loadBalancedEndpointListElement);

        if (parameters.getLoadBalancedEndpoints() != null) {
            if (parameters.getLoadBalancedEndpoints() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getLoadBalancedEndpoints()).isInitialized()) {
                for (VirtualMachineUpdateLoadBalancedSetParameters.InputEndpoint loadBalancedEndpointsItem : parameters
                        .getLoadBalancedEndpoints()) {
                    Element inputEndpointElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "InputEndpoint");
                    loadBalancedEndpointListElement.appendChild(inputEndpointElement);

                    Element loadBalancedEndpointSetNameElement = requestDoc.createElementNS(
                            "http://schemas.microsoft.com/windowsazure", "LoadBalancedEndpointSetName");
                    loadBalancedEndpointSetNameElement.appendChild(
                            requestDoc.createTextNode(loadBalancedEndpointsItem.getLoadBalancedEndpointSetName()));
                    inputEndpointElement.appendChild(loadBalancedEndpointSetNameElement);

                    if (loadBalancedEndpointsItem.getLocalPort() != null) {
                        Element localPortElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "LocalPort");
                        localPortElement.appendChild(requestDoc
                                .createTextNode(Integer.toString(loadBalancedEndpointsItem.getLocalPort())));
                        inputEndpointElement.appendChild(localPortElement);
                    }

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

                    if (loadBalancedEndpointsItem.getPort() != null) {
                        Element portElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "Port");
                        portElement.appendChild(
                                requestDoc.createTextNode(Integer.toString(loadBalancedEndpointsItem.getPort())));
                        inputEndpointElement.appendChild(portElement);
                    }

                    if (loadBalancedEndpointsItem.getLoadBalancerProbe() != null) {
                        Element loadBalancerProbeElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerProbe");
                        inputEndpointElement.appendChild(loadBalancerProbeElement);

                        if (loadBalancedEndpointsItem.getLoadBalancerProbe().getPath() != null) {
                            Element pathElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Path");
                            pathElement.appendChild(requestDoc
                                    .createTextNode(loadBalancedEndpointsItem.getLoadBalancerProbe().getPath()));
                            loadBalancerProbeElement.appendChild(pathElement);
                        }

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

                        if (loadBalancedEndpointsItem.getLoadBalancerProbe().getProtocol() != null) {
                            Element protocolElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Protocol");
                            protocolElement.appendChild(requestDoc.createTextNode(
                                    ComputeManagementClientImpl.loadBalancerProbeTransportProtocolToString(
                                            loadBalancedEndpointsItem.getLoadBalancerProbe().getProtocol())));
                            loadBalancerProbeElement.appendChild(protocolElement);
                        }

                        if (loadBalancedEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds() != null) {
                            Element intervalInSecondsElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds");
                            intervalInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(
                                    loadBalancedEndpointsItem.getLoadBalancerProbe().getIntervalInSeconds())));
                            loadBalancerProbeElement.appendChild(intervalInSecondsElement);
                        }

                        if (loadBalancedEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds() != null) {
                            Element timeoutInSecondsElement = requestDoc.createElementNS(
                                    "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds");
                            timeoutInSecondsElement.appendChild(requestDoc.createTextNode(Integer.toString(
                                    loadBalancedEndpointsItem.getLoadBalancerProbe().getTimeoutInSeconds())));
                            loadBalancerProbeElement.appendChild(timeoutInSecondsElement);
                        }
                    }

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

                    if (loadBalancedEndpointsItem.getVirtualIPAddress() != null) {
                        Element vipElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                                "Vip");
                        vipElement.appendChild(requestDoc
                                .createTextNode(loadBalancedEndpointsItem.getVirtualIPAddress().getHostAddress()));
                        inputEndpointElement.appendChild(vipElement);
                    }

                    if (loadBalancedEndpointsItem.isEnableDirectServerReturn() != null) {
                        Element enableDirectServerReturnElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "EnableDirectServerReturn");
                        enableDirectServerReturnElement.appendChild(requestDoc.createTextNode(Boolean
                                .toString(loadBalancedEndpointsItem.isEnableDirectServerReturn()).toLowerCase()));
                        inputEndpointElement.appendChild(enableDirectServerReturnElement);
                    }

                    Element endpointAclElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "EndpointAcl");
                    inputEndpointElement.appendChild(endpointAclElement);

                    if (loadBalancedEndpointsItem.getRules() != null) {
                        if (loadBalancedEndpointsItem.getRules() instanceof LazyCollection == false
                                || ((LazyCollection) loadBalancedEndpointsItem.getRules()).isInitialized()) {
                            Element rulesSequenceElement = requestDoc
                                    .createElementNS("http://schemas.microsoft.com/windowsazure", "Rules");
                            for (AccessControlListRule rulesItem : loadBalancedEndpointsItem.getRules()) {
                                Element ruleElement = requestDoc
                                        .createElementNS("http://schemas.microsoft.com/windowsazure", "Rule");
                                rulesSequenceElement.appendChild(ruleElement);

                                if (rulesItem.getOrder() != null) {
                                    Element orderElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Order");
                                    orderElement.appendChild(
                                            requestDoc.createTextNode(Integer.toString(rulesItem.getOrder())));
                                    ruleElement.appendChild(orderElement);
                                }

                                if (rulesItem.getAction() != null) {
                                    Element actionElement = requestDoc
                                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Action");
                                    actionElement.appendChild(requestDoc.createTextNode(rulesItem.getAction()));
                                    ruleElement.appendChild(actionElement);
                                }

                                if (rulesItem.getRemoteSubnet() != null) {
                                    Element remoteSubnetElement = requestDoc.createElementNS(
                                            "http://schemas.microsoft.com/windowsazure", "RemoteSubnet");
                                    remoteSubnetElement
                                            .appendChild(requestDoc.createTextNode(rulesItem.getRemoteSubnet()));
                                    ruleElement.appendChild(remoteSubnetElement);
                                }

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

                    if (loadBalancedEndpointsItem.getLoadBalancerName() != null) {
                        Element loadBalancerNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "LoadBalancerName");
                        loadBalancerNameElement.appendChild(
                                requestDoc.createTextNode(loadBalancedEndpointsItem.getLoadBalancerName()));
                        inputEndpointElement.appendChild(loadBalancerNameElement);
                    }

                    if (loadBalancedEndpointsItem.getIdleTimeoutInMinutes() != null) {
                        Element idleTimeoutInMinutesElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "IdleTimeoutInMinutes");
                        idleTimeoutInMinutesElement.appendChild(requestDoc.createTextNode(
                                Integer.toString(loadBalancedEndpointsItem.getIdleTimeoutInMinutes())));
                        inputEndpointElement.appendChild(idleTimeoutInMinutesElement);
                    }

                    if (loadBalancedEndpointsItem.getLoadBalancerDistribution() != null) {
                        Element loadBalancerDistributionElement = requestDoc.createElementNS(
                                "http://schemas.microsoft.com/windowsazure", "LoadBalancerDistribution");
                        loadBalancerDistributionElement.appendChild(
                                requestDoc.createTextNode(loadBalancedEndpointsItem.getLoadBalancerDistribution()));
                        inputEndpointElement.appendChild(loadBalancerDistributionElement);
                    }

                    if (loadBalancedEndpointsItem.getVirtualIPName() != null) {
                        Element virtualIPNameElement = requestDoc
                                .createElementNS("http://schemas.microsoft.com/windowsazure", "VirtualIPName");
                        virtualIPNameElement.appendChild(
                                requestDoc.createTextNode(loadBalancedEndpointsItem.getVirtualIPName()));
                        inputEndpointElement.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
            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 Capture Role operation creates a copy of the operating system virtual
    * hard disk (VHD) that is deployed in the virtual machine, saves the VHD
    * copy in the same storage location as the operating system VHD, and
    * registers the copy as an image in your image gallery. From the captured
    * image, you can create additional customized virtual machines. For more
    * information about images and disks, see Manage Disks and Images at
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For
    * more information about capturing images, see How to Capture an Image of
    * a Virtual Machine Running Windows Server 2008 R2 at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
    * or How to Capture an Image of a Virtual Machine Running Linux at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Capture Virtual
    * Machine 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> captureOSImageAsync(final String serviceName,
            final String deploymentName, final String virtualMachineName,
            final VirtualMachineCaptureOSImageParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return captureOSImage(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * The Capture Role operation creates a copy of the operating system virtual
    * hard disk (VHD) that is deployed in the virtual machine, saves the VHD
    * copy in the same storage location as the operating system VHD, and
    * registers the copy as an image in your image gallery. From the captured
    * image, you can create additional customized virtual machines. For more
    * information about images and disks, see Manage Disks and Images at
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj672979.aspx. For
    * more information about capturing images, see How to Capture an Image of
    * a Virtual Machine Running Windows Server 2008 R2 at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-capture-image-windows-server/
    * or How to Capture an Image of a Virtual Machine Running Linux at
    * http://www.windowsazure.com/en-us/documentation/articles/virtual-machines-linux-capture-image/.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157201.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Capture Virtual
    * Machine 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse captureOSImage(String serviceName, String deploymentName,
            String virtualMachineName, VirtualMachineCaptureOSImageParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "captureOSImageAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginCapturingOSImageAsync(serviceName, deploymentName, virtualMachineName, parameters).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();
            }
        }
    }

    /**
    * Capture role as VM template.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Capture Virtual
    * Machine 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> captureVMImageAsync(final String serviceName,
            final String deploymentName, final String virtualMachineName,
            final VirtualMachineCaptureVMImageParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return captureVMImage(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * Capture role as VM template.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @param parameters Required. Parameters supplied to the Capture Virtual
    * Machine 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse captureVMImage(String serviceName, String deploymentName,
            String virtualMachineName, VirtualMachineCaptureVMImageParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "captureVMImageAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginCapturingVMImageAsync(serviceName, deploymentName, virtualMachineName, parameters).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 Create Role operation adds a virtual machine to an existing
    * deployment. You can refer to the OSDisk in the Add Role operation in the
    * following ways: Platform/User Image - Set the SourceImageName to a
    * platform or user image. You can optionally specify the DiskName and
    * MediaLink values as part the operation to control the name and location
    * of target disk. When DiskName and MediaLink are specified in this mode,
    * they must not already exist in the system, otherwise a conflict fault is
    * returned; UserDisk - Set DiskName to a user supplied image in image
    * repository. SourceImageName must be set to NULL. All other properties
    * are ignored; or Blob in a Storage Account - Set MediaLink to a blob
    * containing the image. SourceImageName and DiskName are set to NULL.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Create Virtual
    * Machine 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> createAsync(final String serviceName, final String deploymentName,
            final VirtualMachineCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return create(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Create Role operation adds a virtual machine to an existing
    * deployment. You can refer to the OSDisk in the Add Role operation in the
    * following ways: Platform/User Image - Set the SourceImageName to a
    * platform or user image. You can optionally specify the DiskName and
    * MediaLink values as part the operation to control the name and location
    * of target disk. When DiskName and MediaLink are specified in this mode,
    * they must not already exist in the system, otherwise a conflict fault is
    * returned; UserDisk - Set DiskName to a user supplied image in image
    * repository. SourceImageName must be set to NULL. All other properties
    * are ignored; or Blob in a Storage Account - Set MediaLink to a blob
    * containing the image. SourceImageName and DiskName are set to NULL.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157186.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Create Virtual
    * Machine 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 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 ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the 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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse create(String serviceName, String deploymentName,
            VirtualMachineCreateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException,
            ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginCreatingAsync(serviceName, deploymentName, parameters).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 Create Virtual Machine Deployment operation provisions a virtual
    * machine based on the supplied configuration. When you create a
    * deployment of a virtual machine, you should make sure that the cloud
    * service and the disk or image that you use are located in the same
    * region. For example, if the cloud service was created in the West US
    * region, the disk or image that you use should also be located in a
    * storage account in the West US region.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param parameters Required. Parameters supplied to the Create Virtual
    * Machine Deployment 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> createDeploymentAsync(final String serviceName,
            final VirtualMachineCreateDeploymentParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return createDeployment(serviceName, parameters);
            }
        });
    }

    /**
    * The Create Virtual Machine Deployment operation provisions a virtual
    * machine based on the supplied configuration. When you create a
    * deployment of a virtual machine, you should make sure that the cloud
    * service and the disk or image that you use are located in the same
    * region. For example, if the cloud service was created in the West US
    * region, the disk or image that you use should also be located in a
    * storage account in the West US region.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157194.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param parameters Required. Parameters supplied to the Create Virtual
    * Machine Deployment 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse createDeployment(String serviceName,
            VirtualMachineCreateDeploymentParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "createDeploymentAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginCreatingDeploymentAsync(serviceName, parameters).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 Delete Role operation deletes the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * delete.
    * @param deleteFromStorage Required. Specifies that the source blob(s) for
    * the virtual machine should also be deleted from storage.
    * @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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> deleteAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName, final boolean deleteFromStorage) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return delete(serviceName, deploymentName, virtualMachineName, deleteFromStorage);
            }
        });
    }

    /**
    * The Delete Role operation deletes the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157184.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * delete.
    * @param deleteFromStorage Required. Specifies that the source blob(s) for
    * the virtual machine should also be deleted from storage.
    * @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 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse delete(String serviceName, String deploymentName, String virtualMachineName,
            boolean deleteFromStorage)
            throws IOException, ServiceException, InterruptedException, ExecutionException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("deleteFromStorage", deleteFromStorage);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginDeletingAsync(serviceName, deploymentName, virtualMachineName, deleteFromStorage).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 Get Role operation retrieves information about the specified virtual
    * machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine.
    * @return The Get Virtual Machine operation response.
    */
    @Override
    public Future<VirtualMachineGetResponse> getAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName) {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineGetResponse>() {
            @Override
            public VirtualMachineGetResponse call() throws Exception {
                return get(serviceName, deploymentName, virtualMachineName);
            }
        });
    }

    /**
    * The Get Role operation retrieves information about the specified virtual
    * machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157193.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The Get Virtual Machine operation response.
    */
    @Override
    public VirtualMachineGetResponse get(String serviceName, String deploymentName, String virtualMachineName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roles/";
        url = url + URLEncoder.encode(virtualMachineName, "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
            VirtualMachineGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element persistentVMRoleElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "PersistentVMRole");
                if (persistentVMRoleElement != null) {
                    Element roleNameElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement,
                            "http://schemas.microsoft.com/windowsazure", "RoleName");
                    if (roleNameElement != null) {
                        String roleNameInstance;
                        roleNameInstance = roleNameElement.getTextContent();
                        result.setRoleName(roleNameInstance);
                    }

                    Element osVersionElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement,
                            "http://schemas.microsoft.com/windowsazure", "OsVersion");
                    if (osVersionElement != null) {
                        String osVersionInstance;
                        osVersionInstance = osVersionElement.getTextContent();
                        result.setOsVersion(osVersionInstance);
                    }

                    Element roleTypeElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement,
                            "http://schemas.microsoft.com/windowsazure", "RoleType");
                    if (roleTypeElement != null && roleTypeElement.getTextContent() != null
                            && !roleTypeElement.getTextContent().isEmpty()) {
                        VirtualMachineRoleType roleTypeInstance;
                        roleTypeInstance = VirtualMachineRoleType.valueOf(roleTypeElement.getTextContent());
                        result.setRoleType(roleTypeInstance);
                    }

                    Element availabilitySetNameElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement,
                            "http://schemas.microsoft.com/windowsazure", "AvailabilitySetName");
                    if (availabilitySetNameElement != null) {
                        String availabilitySetNameInstance;
                        availabilitySetNameInstance = availabilitySetNameElement.getTextContent();
                        result.setAvailabilitySetName(availabilitySetNameInstance);
                    }

                    Element roleSizeElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement,
                            "http://schemas.microsoft.com/windowsazure", "RoleSize");
                    if (roleSizeElement != null) {
                        String roleSizeInstance;
                        roleSizeInstance = roleSizeElement.getTextContent();
                        result.setRoleSize(roleSizeInstance);
                    }

                    Element defaultWinRmCertificateThumbprintElement = XmlUtility.getElementByTagNameNS(
                            persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure",
                            "DefaultWinRmCertificateThumbprint");
                    if (defaultWinRmCertificateThumbprintElement != null) {
                        String defaultWinRmCertificateThumbprintInstance;
                        defaultWinRmCertificateThumbprintInstance = defaultWinRmCertificateThumbprintElement
                                .getTextContent();
                        result.setDefaultWinRmCertificateThumbprint(defaultWinRmCertificateThumbprintInstance);
                    }

                    Element configurationSetsSequenceElement = XmlUtility.getElementByTagNameNS(
                            persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure",
                            "ConfigurationSets");
                    if (configurationSetsSequenceElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(configurationSetsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ConfigurationSet")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element configurationSetsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(configurationSetsSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "ConfigurationSet")
                                    .get(i1));
                            ConfigurationSet configurationSetInstance = new ConfigurationSet();
                            result.getConfigurationSets().add(configurationSetInstance);

                            Element configurationSetTypeElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "ConfigurationSetType");
                            if (configurationSetTypeElement != null) {
                                String configurationSetTypeInstance;
                                configurationSetTypeInstance = configurationSetTypeElement.getTextContent();
                                configurationSetInstance.setConfigurationSetType(configurationSetTypeInstance);
                            }

                            Element inputEndpointsSequenceElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "InputEndpoints");
                            if (inputEndpointsSequenceElement != null) {
                                for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(inputEndpointsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "InputEndpoint")
                                        .size(); i2 = i2 + 1) {
                                    org.w3c.dom.Element inputEndpointsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(inputEndpointsSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "InputEndpoint")
                                            .get(i2));
                                    InputEndpoint inputEndpointInstance = new InputEndpoint();
                                    configurationSetInstance.getInputEndpoints().add(inputEndpointInstance);

                                    Element loadBalancedEndpointSetNameElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancedEndpointSetName");
                                    if (loadBalancedEndpointSetNameElement != null) {
                                        String loadBalancedEndpointSetNameInstance;
                                        loadBalancedEndpointSetNameInstance = loadBalancedEndpointSetNameElement
                                                .getTextContent();
                                        inputEndpointInstance.setLoadBalancedEndpointSetName(
                                                loadBalancedEndpointSetNameInstance);
                                    }

                                    Element localPortElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "LocalPort");
                                    if (localPortElement != null && localPortElement.getTextContent() != null
                                            && !localPortElement.getTextContent().isEmpty()) {
                                        int localPortInstance;
                                        localPortInstance = DatatypeConverter
                                                .parseInt(localPortElement.getTextContent());
                                        inputEndpointInstance.setLocalPort(localPortInstance);
                                    }

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

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

                                    Element loadBalancerProbeElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancerProbe");
                                    if (loadBalancerProbeElement != null) {
                                        LoadBalancerProbe loadBalancerProbeInstance = new LoadBalancerProbe();
                                        inputEndpointInstance.setLoadBalancerProbe(loadBalancerProbeInstance);

                                        Element pathElement = XmlUtility.getElementByTagNameNS(
                                                loadBalancerProbeElement,
                                                "http://schemas.microsoft.com/windowsazure", "Path");
                                        if (pathElement != null) {
                                            String pathInstance;
                                            pathInstance = pathElement.getTextContent();
                                            loadBalancerProbeInstance.setPath(pathInstance);
                                        }

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

                                        Element protocolElement = XmlUtility.getElementByTagNameNS(
                                                loadBalancerProbeElement,
                                                "http://schemas.microsoft.com/windowsazure", "Protocol");
                                        if (protocolElement != null && protocolElement.getTextContent() != null
                                                && !protocolElement.getTextContent().isEmpty()) {
                                            LoadBalancerProbeTransportProtocol protocolInstance;
                                            protocolInstance = ComputeManagementClientImpl
                                                    .parseLoadBalancerProbeTransportProtocol(
                                                            protocolElement.getTextContent());
                                            loadBalancerProbeInstance.setProtocol(protocolInstance);
                                        }

                                        Element intervalInSecondsElement = XmlUtility.getElementByTagNameNS(
                                                loadBalancerProbeElement,
                                                "http://schemas.microsoft.com/windowsazure", "IntervalInSeconds");
                                        if (intervalInSecondsElement != null
                                                && intervalInSecondsElement.getTextContent() != null
                                                && !intervalInSecondsElement.getTextContent().isEmpty()) {
                                            int intervalInSecondsInstance;
                                            intervalInSecondsInstance = DatatypeConverter
                                                    .parseInt(intervalInSecondsElement.getTextContent());
                                            loadBalancerProbeInstance
                                                    .setIntervalInSeconds(intervalInSecondsInstance);
                                        }

                                        Element timeoutInSecondsElement = XmlUtility.getElementByTagNameNS(
                                                loadBalancerProbeElement,
                                                "http://schemas.microsoft.com/windowsazure", "TimeoutInSeconds");
                                        if (timeoutInSecondsElement != null
                                                && timeoutInSecondsElement.getTextContent() != null
                                                && !timeoutInSecondsElement.getTextContent().isEmpty()) {
                                            int timeoutInSecondsInstance;
                                            timeoutInSecondsInstance = DatatypeConverter
                                                    .parseInt(timeoutInSecondsElement.getTextContent());
                                            loadBalancerProbeInstance.setTimeoutInSeconds(timeoutInSecondsInstance);
                                        }
                                    }

                                    Element protocolElement2 = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "Protocol");
                                    if (protocolElement2 != null) {
                                        String protocolInstance2;
                                        protocolInstance2 = protocolElement2.getTextContent();
                                        inputEndpointInstance.setProtocol(protocolInstance2);
                                    }

                                    Element vipElement = XmlUtility.getElementByTagNameNS(inputEndpointsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Vip");
                                    if (vipElement != null) {
                                        InetAddress vipInstance;
                                        vipInstance = InetAddress.getByName(vipElement.getTextContent());
                                        inputEndpointInstance.setVirtualIPAddress(vipInstance);
                                    }

                                    Element enableDirectServerReturnElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "EnableDirectServerReturn");
                                    if (enableDirectServerReturnElement != null
                                            && enableDirectServerReturnElement.getTextContent() != null
                                            && !enableDirectServerReturnElement.getTextContent().isEmpty()) {
                                        boolean enableDirectServerReturnInstance;
                                        enableDirectServerReturnInstance = DatatypeConverter.parseBoolean(
                                                enableDirectServerReturnElement.getTextContent().toLowerCase());
                                        inputEndpointInstance
                                                .setEnableDirectServerReturn(enableDirectServerReturnInstance);
                                    }

                                    Element loadBalancerNameElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancerName");
                                    if (loadBalancerNameElement != null) {
                                        String loadBalancerNameInstance;
                                        loadBalancerNameInstance = loadBalancerNameElement.getTextContent();
                                        inputEndpointInstance.setLoadBalancerName(loadBalancerNameInstance);
                                    }

                                    Element endpointAclElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "EndpointAcl");
                                    if (endpointAclElement != null) {
                                        EndpointAcl endpointAclInstance = new EndpointAcl();
                                        inputEndpointInstance.setEndpointAcl(endpointAclInstance);

                                        Element rulesSequenceElement = XmlUtility.getElementByTagNameNS(
                                                endpointAclElement, "http://schemas.microsoft.com/windowsazure",
                                                "Rules");
                                        if (rulesSequenceElement != null) {
                                            for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                                    .getElementsByTagNameNS(rulesSequenceElement,
                                                            "http://schemas.microsoft.com/windowsazure", "Rule")
                                                    .size(); i3 = i3 + 1) {
                                                org.w3c.dom.Element rulesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                        .getElementsByTagNameNS(rulesSequenceElement,
                                                                "http://schemas.microsoft.com/windowsazure", "Rule")
                                                        .get(i3));
                                                AccessControlListRule ruleInstance = new AccessControlListRule();
                                                endpointAclInstance.getRules().add(ruleInstance);

                                                Element orderElement = XmlUtility.getElementByTagNameNS(
                                                        rulesElement, "http://schemas.microsoft.com/windowsazure",
                                                        "Order");
                                                if (orderElement != null && orderElement.getTextContent() != null
                                                        && !orderElement.getTextContent().isEmpty()) {
                                                    int orderInstance;
                                                    orderInstance = DatatypeConverter
                                                            .parseInt(orderElement.getTextContent());
                                                    ruleInstance.setOrder(orderInstance);
                                                }

                                                Element actionElement = XmlUtility.getElementByTagNameNS(
                                                        rulesElement, "http://schemas.microsoft.com/windowsazure",
                                                        "Action");
                                                if (actionElement != null) {
                                                    String actionInstance;
                                                    actionInstance = actionElement.getTextContent();
                                                    ruleInstance.setAction(actionInstance);
                                                }

                                                Element remoteSubnetElement = XmlUtility.getElementByTagNameNS(
                                                        rulesElement, "http://schemas.microsoft.com/windowsazure",
                                                        "RemoteSubnet");
                                                if (remoteSubnetElement != null) {
                                                    String remoteSubnetInstance;
                                                    remoteSubnetInstance = remoteSubnetElement.getTextContent();
                                                    ruleInstance.setRemoteSubnet(remoteSubnetInstance);
                                                }

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

                                    Element idleTimeoutInMinutesElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "IdleTimeoutInMinutes");
                                    if (idleTimeoutInMinutesElement != null
                                            && idleTimeoutInMinutesElement.getTextContent() != null
                                            && !idleTimeoutInMinutesElement.getTextContent().isEmpty()) {
                                        int idleTimeoutInMinutesInstance;
                                        idleTimeoutInMinutesInstance = DatatypeConverter
                                                .parseInt(idleTimeoutInMinutesElement.getTextContent());
                                        inputEndpointInstance.setIdleTimeoutInMinutes(idleTimeoutInMinutesInstance);
                                    }

                                    Element loadBalancerDistributionElement = XmlUtility.getElementByTagNameNS(
                                            inputEndpointsElement, "http://schemas.microsoft.com/windowsazure",
                                            "LoadBalancerDistribution");
                                    if (loadBalancerDistributionElement != null) {
                                        String loadBalancerDistributionInstance;
                                        loadBalancerDistributionInstance = loadBalancerDistributionElement
                                                .getTextContent();
                                        inputEndpointInstance
                                                .setLoadBalancerDistribution(loadBalancerDistributionInstance);
                                    }

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

                            Element subnetNamesSequenceElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "SubnetNames");
                            if (subnetNamesSequenceElement != null) {
                                for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(subnetNamesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "SubnetName")
                                        .size(); i4 = i4 + 1) {
                                    org.w3c.dom.Element subnetNamesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(subnetNamesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "SubnetName")
                                            .get(i4));
                                    configurationSetInstance.getSubnetNames()
                                            .add(subnetNamesElement.getTextContent());
                                }
                            }

                            Element staticVirtualNetworkIPAddressElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "StaticVirtualNetworkIPAddress");
                            if (staticVirtualNetworkIPAddressElement != null) {
                                String staticVirtualNetworkIPAddressInstance;
                                staticVirtualNetworkIPAddressInstance = staticVirtualNetworkIPAddressElement
                                        .getTextContent();
                                configurationSetInstance
                                        .setStaticVirtualNetworkIPAddress(staticVirtualNetworkIPAddressInstance);
                            }

                            Element publicIPsSequenceElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "PublicIPs");
                            if (publicIPsSequenceElement != null) {
                                for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(publicIPsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "PublicIP")
                                        .size(); i5 = i5 + 1) {
                                    org.w3c.dom.Element publicIPsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(publicIPsSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "PublicIP")
                                            .get(i5));
                                    ConfigurationSet.PublicIP publicIPInstance = new ConfigurationSet.PublicIP();
                                    configurationSetInstance.getPublicIPs().add(publicIPInstance);

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

                                    Element idleTimeoutInMinutesElement2 = XmlUtility.getElementByTagNameNS(
                                            publicIPsElement, "http://schemas.microsoft.com/windowsazure",
                                            "IdleTimeoutInMinutes");
                                    if (idleTimeoutInMinutesElement2 != null
                                            && idleTimeoutInMinutesElement2.getTextContent() != null
                                            && !idleTimeoutInMinutesElement2.getTextContent().isEmpty()) {
                                        int idleTimeoutInMinutesInstance2;
                                        idleTimeoutInMinutesInstance2 = DatatypeConverter
                                                .parseInt(idleTimeoutInMinutesElement2.getTextContent());
                                        publicIPInstance.setIdleTimeoutInMinutes(idleTimeoutInMinutesInstance2);
                                    }

                                    Element domainNameLabelElement = XmlUtility.getElementByTagNameNS(
                                            publicIPsElement, "http://schemas.microsoft.com/windowsazure",
                                            "DomainNameLabel");
                                    if (domainNameLabelElement != null) {
                                        String domainNameLabelInstance;
                                        domainNameLabelInstance = domainNameLabelElement.getTextContent();
                                        publicIPInstance.setDomainNameLabel(domainNameLabelInstance);
                                    }
                                }
                            }

                            Element networkInterfacesSequenceElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "NetworkInterfaces");
                            if (networkInterfacesSequenceElement != null) {
                                for (int i6 = 0; i6 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(networkInterfacesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "NetworkInterface")
                                        .size(); i6 = i6 + 1) {
                                    org.w3c.dom.Element networkInterfacesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(networkInterfacesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "NetworkInterface")
                                            .get(i6));
                                    NetworkInterface networkInterfaceInstance = new NetworkInterface();
                                    configurationSetInstance.getNetworkInterfaces().add(networkInterfaceInstance);

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

                                    Element iPConfigurationsSequenceElement = XmlUtility.getElementByTagNameNS(
                                            networkInterfacesElement, "http://schemas.microsoft.com/windowsazure",
                                            "IPConfigurations");
                                    if (iPConfigurationsSequenceElement != null) {
                                        for (int i7 = 0; i7 < com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(iPConfigurationsSequenceElement,
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "IPConfiguration")
                                                .size(); i7 = i7 + 1) {
                                            org.w3c.dom.Element iPConfigurationsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                    .getElementsByTagNameNS(iPConfigurationsSequenceElement,
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "IPConfiguration")
                                                    .get(i7));
                                            IPConfiguration iPConfigurationInstance = new IPConfiguration();
                                            networkInterfaceInstance.getIPConfigurations()
                                                    .add(iPConfigurationInstance);

                                            Element subnetNameElement = XmlUtility.getElementByTagNameNS(
                                                    iPConfigurationsElement,
                                                    "http://schemas.microsoft.com/windowsazure", "SubnetName");
                                            if (subnetNameElement != null) {
                                                String subnetNameInstance;
                                                subnetNameInstance = subnetNameElement.getTextContent();
                                                iPConfigurationInstance.setSubnetName(subnetNameInstance);
                                            }

                                            Element staticVirtualNetworkIPAddressElement2 = XmlUtility
                                                    .getElementByTagNameNS(iPConfigurationsElement,
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "StaticVirtualNetworkIPAddress");
                                            if (staticVirtualNetworkIPAddressElement2 != null) {
                                                String staticVirtualNetworkIPAddressInstance2;
                                                staticVirtualNetworkIPAddressInstance2 = staticVirtualNetworkIPAddressElement2
                                                        .getTextContent();
                                                iPConfigurationInstance.setStaticVirtualNetworkIPAddress(
                                                        staticVirtualNetworkIPAddressInstance2);
                                            }
                                        }
                                    }

                                    Element networkSecurityGroupElement = XmlUtility.getElementByTagNameNS(
                                            networkInterfacesElement, "http://schemas.microsoft.com/windowsazure",
                                            "NetworkSecurityGroup");
                                    if (networkSecurityGroupElement != null) {
                                        String networkSecurityGroupInstance;
                                        networkSecurityGroupInstance = networkSecurityGroupElement.getTextContent();
                                        networkInterfaceInstance
                                                .setNetworkSecurityGroup(networkSecurityGroupInstance);
                                    }

                                    Element iPForwardingElement = XmlUtility.getElementByTagNameNS(
                                            networkInterfacesElement, "http://schemas.microsoft.com/windowsazure",
                                            "IPForwarding");
                                    if (iPForwardingElement != null) {
                                        String iPForwardingInstance;
                                        iPForwardingInstance = iPForwardingElement.getTextContent();
                                        networkInterfaceInstance.setIPForwarding(iPForwardingInstance);
                                    }
                                }
                            }

                            Element networkSecurityGroupElement2 = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "NetworkSecurityGroup");
                            if (networkSecurityGroupElement2 != null) {
                                String networkSecurityGroupInstance2;
                                networkSecurityGroupInstance2 = networkSecurityGroupElement2.getTextContent();
                                configurationSetInstance.setNetworkSecurityGroup(networkSecurityGroupInstance2);
                            }

                            Element iPForwardingElement2 = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "IPForwarding");
                            if (iPForwardingElement2 != null) {
                                String iPForwardingInstance2;
                                iPForwardingInstance2 = iPForwardingElement2.getTextContent();
                                configurationSetInstance.setIPForwarding(iPForwardingInstance2);
                            }

                            Element computerNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "ComputerName");
                            if (computerNameElement != null) {
                                String computerNameInstance;
                                computerNameInstance = computerNameElement.getTextContent();
                                configurationSetInstance.setComputerName(computerNameInstance);
                            }

                            Element adminPasswordElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "AdminPassword");
                            if (adminPasswordElement != null) {
                                String adminPasswordInstance;
                                adminPasswordInstance = adminPasswordElement.getTextContent();
                                configurationSetInstance.setAdminPassword(adminPasswordInstance);
                            }

                            Element resetPasswordOnFirstLogonElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "ResetPasswordOnFirstLogon");
                            if (resetPasswordOnFirstLogonElement != null
                                    && resetPasswordOnFirstLogonElement.getTextContent() != null
                                    && !resetPasswordOnFirstLogonElement.getTextContent().isEmpty()) {
                                boolean resetPasswordOnFirstLogonInstance;
                                resetPasswordOnFirstLogonInstance = DatatypeConverter.parseBoolean(
                                        resetPasswordOnFirstLogonElement.getTextContent().toLowerCase());
                                configurationSetInstance
                                        .setResetPasswordOnFirstLogon(resetPasswordOnFirstLogonInstance);
                            }

                            Element enableAutomaticUpdatesElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "EnableAutomaticUpdates");
                            if (enableAutomaticUpdatesElement != null
                                    && enableAutomaticUpdatesElement.getTextContent() != null
                                    && !enableAutomaticUpdatesElement.getTextContent().isEmpty()) {
                                boolean enableAutomaticUpdatesInstance;
                                enableAutomaticUpdatesInstance = DatatypeConverter
                                        .parseBoolean(enableAutomaticUpdatesElement.getTextContent().toLowerCase());
                                configurationSetInstance.setEnableAutomaticUpdates(enableAutomaticUpdatesInstance);
                            }

                            Element timeZoneElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "TimeZone");
                            if (timeZoneElement != null) {
                                String timeZoneInstance;
                                timeZoneInstance = timeZoneElement.getTextContent();
                                configurationSetInstance.setTimeZone(timeZoneInstance);
                            }

                            Element domainJoinElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "DomainJoin");
                            if (domainJoinElement != null) {
                                DomainJoinSettings domainJoinInstance = new DomainJoinSettings();
                                configurationSetInstance.setDomainJoin(domainJoinInstance);

                                Element credentialsElement = XmlUtility.getElementByTagNameNS(domainJoinElement,
                                        "http://schemas.microsoft.com/windowsazure", "Credentials");
                                if (credentialsElement != null) {
                                    DomainJoinCredentials credentialsInstance = new DomainJoinCredentials();
                                    domainJoinInstance.setCredentials(credentialsInstance);

                                    Element domainElement = XmlUtility.getElementByTagNameNS(credentialsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Domain");
                                    if (domainElement != null) {
                                        String domainInstance;
                                        domainInstance = domainElement.getTextContent();
                                        credentialsInstance.setDomain(domainInstance);
                                    }

                                    Element usernameElement = XmlUtility.getElementByTagNameNS(credentialsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Username");
                                    if (usernameElement != null) {
                                        String usernameInstance;
                                        usernameInstance = usernameElement.getTextContent();
                                        credentialsInstance.setUserName(usernameInstance);
                                    }

                                    Element passwordElement = XmlUtility.getElementByTagNameNS(credentialsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Password");
                                    if (passwordElement != null) {
                                        String passwordInstance;
                                        passwordInstance = passwordElement.getTextContent();
                                        credentialsInstance.setPassword(passwordInstance);
                                    }
                                }

                                Element joinDomainElement = XmlUtility.getElementByTagNameNS(domainJoinElement,
                                        "http://schemas.microsoft.com/windowsazure", "JoinDomain");
                                if (joinDomainElement != null) {
                                    String joinDomainInstance;
                                    joinDomainInstance = joinDomainElement.getTextContent();
                                    domainJoinInstance.setDomainToJoin(joinDomainInstance);
                                }

                                Element machineObjectOUElement = XmlUtility.getElementByTagNameNS(domainJoinElement,
                                        "http://schemas.microsoft.com/windowsazure", "MachineObjectOU");
                                if (machineObjectOUElement != null) {
                                    String machineObjectOUInstance;
                                    machineObjectOUInstance = machineObjectOUElement.getTextContent();
                                    domainJoinInstance.setLdapMachineObjectOU(machineObjectOUInstance);
                                }

                                Element provisioningElement = XmlUtility.getElementByTagNameNS(domainJoinElement,
                                        "http://schemas.microsoft.com/windowsazure", "Provisioning");
                                if (provisioningElement != null) {
                                    DomainJoinProvisioning provisioningInstance = new DomainJoinProvisioning();
                                    domainJoinInstance.setProvisioning(provisioningInstance);

                                    Element accountDataElement = XmlUtility.getElementByTagNameNS(
                                            provisioningElement, "http://schemas.microsoft.com/windowsazure",
                                            "AccountData");
                                    if (accountDataElement != null) {
                                        String accountDataInstance;
                                        accountDataInstance = accountDataElement.getTextContent();
                                        provisioningInstance.setAccountData(accountDataInstance);
                                    }
                                }
                            }

                            Element storedCertificateSettingsSequenceElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "StoredCertificateSettings");
                            if (storedCertificateSettingsSequenceElement != null) {
                                for (int i8 = 0; i8 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(storedCertificateSettingsSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "CertificateSetting")
                                        .size(); i8 = i8 + 1) {
                                    org.w3c.dom.Element storedCertificateSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(storedCertificateSettingsSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure",
                                                    "CertificateSetting")
                                            .get(i8));
                                    StoredCertificateSettings certificateSettingInstance = new StoredCertificateSettings();
                                    configurationSetInstance.getStoredCertificateSettings()
                                            .add(certificateSettingInstance);

                                    Element storeLocationElement = XmlUtility.getElementByTagNameNS(
                                            storedCertificateSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "StoreLocation");
                                    if (storeLocationElement != null) {
                                    }

                                    Element storeNameElement = XmlUtility.getElementByTagNameNS(
                                            storedCertificateSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "StoreName");
                                    if (storeNameElement != null) {
                                        String storeNameInstance;
                                        storeNameInstance = storeNameElement.getTextContent();
                                        certificateSettingInstance.setStoreName(storeNameInstance);
                                    }

                                    Element thumbprintElement = XmlUtility.getElementByTagNameNS(
                                            storedCertificateSettingsElement,
                                            "http://schemas.microsoft.com/windowsazure", "Thumbprint");
                                    if (thumbprintElement != null) {
                                        String thumbprintInstance;
                                        thumbprintInstance = thumbprintElement.getTextContent();
                                        certificateSettingInstance.setThumbprint(thumbprintInstance);
                                    }
                                }
                            }

                            Element winRMElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "WinRM");
                            if (winRMElement != null) {
                                WindowsRemoteManagementSettings winRMInstance = new WindowsRemoteManagementSettings();
                                configurationSetInstance.setWindowsRemoteManagement(winRMInstance);

                                Element listenersSequenceElement = XmlUtility.getElementByTagNameNS(winRMElement,
                                        "http://schemas.microsoft.com/windowsazure", "Listeners");
                                if (listenersSequenceElement != null) {
                                    for (int i9 = 0; i9 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(listenersSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "Listener")
                                            .size(); i9 = i9 + 1) {
                                        org.w3c.dom.Element listenersElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(listenersSequenceElement,
                                                        "http://schemas.microsoft.com/windowsazure", "Listener")
                                                .get(i9));
                                        WindowsRemoteManagementListener listenerInstance = new WindowsRemoteManagementListener();
                                        winRMInstance.getListeners().add(listenerInstance);

                                        Element protocolElement3 = XmlUtility.getElementByTagNameNS(
                                                listenersElement, "http://schemas.microsoft.com/windowsazure",
                                                "Protocol");
                                        if (protocolElement3 != null && protocolElement3.getTextContent() != null
                                                && !protocolElement3.getTextContent().isEmpty()) {
                                            VirtualMachineWindowsRemoteManagementListenerType protocolInstance3;
                                            protocolInstance3 = VirtualMachineWindowsRemoteManagementListenerType
                                                    .valueOf(protocolElement3.getTextContent());
                                            listenerInstance.setListenerType(protocolInstance3);
                                        }

                                        Element certificateThumbprintElement = XmlUtility.getElementByTagNameNS(
                                                listenersElement, "http://schemas.microsoft.com/windowsazure",
                                                "CertificateThumbprint");
                                        if (certificateThumbprintElement != null) {
                                            String certificateThumbprintInstance;
                                            certificateThumbprintInstance = certificateThumbprintElement
                                                    .getTextContent();
                                            listenerInstance
                                                    .setCertificateThumbprint(certificateThumbprintInstance);
                                        }
                                    }
                                }
                            }

                            Element adminUsernameElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "AdminUsername");
                            if (adminUsernameElement != null) {
                                String adminUsernameInstance;
                                adminUsernameInstance = adminUsernameElement.getTextContent();
                                configurationSetInstance.setAdminUserName(adminUsernameInstance);
                            }

                            Element additionalUnattendContentElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "AdditionalUnattendContent");
                            if (additionalUnattendContentElement != null) {
                                AdditionalUnattendContentSettings additionalUnattendContentInstance = new AdditionalUnattendContentSettings();
                                configurationSetInstance
                                        .setAdditionalUnattendContent(additionalUnattendContentInstance);

                                Element passesSequenceElement = XmlUtility.getElementByTagNameNS(
                                        additionalUnattendContentElement,
                                        "http://schemas.microsoft.com/windowsazure", "Passes");
                                if (passesSequenceElement != null) {
                                    for (int i10 = 0; i10 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(passesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "UnattendPass")
                                            .size(); i10 = i10 + 1) {
                                        org.w3c.dom.Element passesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(passesSequenceElement,
                                                        "http://schemas.microsoft.com/windowsazure", "UnattendPass")
                                                .get(i10));
                                        UnattendPassSettings unattendPassInstance = new UnattendPassSettings();
                                        additionalUnattendContentInstance.getUnattendPasses()
                                                .add(unattendPassInstance);

                                        Element passNameElement = XmlUtility.getElementByTagNameNS(passesElement,
                                                "http://schemas.microsoft.com/windowsazure", "PassName");
                                        if (passNameElement != null) {
                                            String passNameInstance;
                                            passNameInstance = passNameElement.getTextContent();
                                            unattendPassInstance.setPassName(passNameInstance);
                                        }

                                        Element componentsSequenceElement = XmlUtility.getElementByTagNameNS(
                                                passesElement, "http://schemas.microsoft.com/windowsazure",
                                                "Components");
                                        if (componentsSequenceElement != null) {
                                            for (int i11 = 0; i11 < com.microsoft.windowsazure.core.utils.XmlUtility
                                                    .getElementsByTagNameNS(componentsSequenceElement,
                                                            "http://schemas.microsoft.com/windowsazure",
                                                            "UnattendComponent")
                                                    .size(); i11 = i11 + 1) {
                                                org.w3c.dom.Element componentsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                        .getElementsByTagNameNS(componentsSequenceElement,
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "UnattendComponent")
                                                        .get(i11));
                                                UnattendComponent unattendComponentInstance = new UnattendComponent();
                                                unattendPassInstance.getUnattendComponents()
                                                        .add(unattendComponentInstance);

                                                Element componentNameElement = XmlUtility.getElementByTagNameNS(
                                                        componentsElement,
                                                        "http://schemas.microsoft.com/windowsazure",
                                                        "ComponentName");
                                                if (componentNameElement != null) {
                                                    String componentNameInstance;
                                                    componentNameInstance = componentNameElement.getTextContent();
                                                    unattendComponentInstance
                                                            .setComponentName(componentNameInstance);
                                                }

                                                Element componentSettingsSequenceElement = XmlUtility
                                                        .getElementByTagNameNS(componentsElement,
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "ComponentSettings");
                                                if (componentSettingsSequenceElement != null) {
                                                    for (int i12 = 0; i12 < com.microsoft.windowsazure.core.utils.XmlUtility
                                                            .getElementsByTagNameNS(
                                                                    componentSettingsSequenceElement,
                                                                    "http://schemas.microsoft.com/windowsazure",
                                                                    "ComponentSetting")
                                                            .size(); i12 = i12 + 1) {
                                                        org.w3c.dom.Element componentSettingsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                                .getElementsByTagNameNS(
                                                                        componentSettingsSequenceElement,
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "ComponentSetting")
                                                                .get(i12));
                                                        ComponentSetting componentSettingInstance = new ComponentSetting();
                                                        unattendComponentInstance.getUnattendComponentSettings()
                                                                .add(componentSettingInstance);

                                                        Element settingNameElement = XmlUtility
                                                                .getElementByTagNameNS(componentSettingsElement,
                                                                        "http://schemas.microsoft.com/windowsazure",
                                                                        "SettingName");
                                                        if (settingNameElement != null) {
                                                            String settingNameInstance;
                                                            settingNameInstance = settingNameElement
                                                                    .getTextContent();
                                                            componentSettingInstance
                                                                    .setSettingName(settingNameInstance);
                                                        }

                                                        Element contentElement = XmlUtility.getElementByTagNameNS(
                                                                componentSettingsElement,
                                                                "http://schemas.microsoft.com/windowsazure",
                                                                "Content");
                                                        if (contentElement != null) {
                                                            String contentInstance;
                                                            contentInstance = contentElement
                                                                    .getTextContent() != null
                                                                            ? new String(
                                                                                    Base64.decode(contentElement
                                                                                            .getTextContent()))
                                                                            : null;
                                                            componentSettingInstance.setContent(contentInstance);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            Element hostNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "HostName");
                            if (hostNameElement != null) {
                                String hostNameInstance;
                                hostNameInstance = hostNameElement.getTextContent();
                                configurationSetInstance.setHostName(hostNameInstance);
                            }

                            Element userNameElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "UserName");
                            if (userNameElement != null) {
                                String userNameInstance;
                                userNameInstance = userNameElement.getTextContent();
                                configurationSetInstance.setUserName(userNameInstance);
                            }

                            Element userPasswordElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "UserPassword");
                            if (userPasswordElement != null) {
                                String userPasswordInstance;
                                userPasswordInstance = userPasswordElement.getTextContent();
                                configurationSetInstance.setUserPassword(userPasswordInstance);
                            }

                            Element disableSshPasswordAuthenticationElement = XmlUtility.getElementByTagNameNS(
                                    configurationSetsElement, "http://schemas.microsoft.com/windowsazure",
                                    "DisableSshPasswordAuthentication");
                            if (disableSshPasswordAuthenticationElement != null
                                    && disableSshPasswordAuthenticationElement.getTextContent() != null
                                    && !disableSshPasswordAuthenticationElement.getTextContent().isEmpty()) {
                                boolean disableSshPasswordAuthenticationInstance;
                                disableSshPasswordAuthenticationInstance = DatatypeConverter.parseBoolean(
                                        disableSshPasswordAuthenticationElement.getTextContent().toLowerCase());
                                configurationSetInstance.setDisableSshPasswordAuthentication(
                                        disableSshPasswordAuthenticationInstance);
                            }

                            Element sSHElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "SSH");
                            if (sSHElement != null) {
                                SshSettings sSHInstance = new SshSettings();
                                configurationSetInstance.setSshSettings(sSHInstance);

                                Element publicKeysSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement,
                                        "http://schemas.microsoft.com/windowsazure", "PublicKeys");
                                if (publicKeysSequenceElement != null) {
                                    for (int i13 = 0; i13 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(publicKeysSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "PublicKey")
                                            .size(); i13 = i13 + 1) {
                                        org.w3c.dom.Element publicKeysElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(publicKeysSequenceElement,
                                                        "http://schemas.microsoft.com/windowsazure", "PublicKey")
                                                .get(i13));
                                        SshSettingPublicKey publicKeyInstance = new SshSettingPublicKey();
                                        sSHInstance.getPublicKeys().add(publicKeyInstance);

                                        Element fingerprintElement = XmlUtility.getElementByTagNameNS(
                                                publicKeysElement, "http://schemas.microsoft.com/windowsazure",
                                                "Fingerprint");
                                        if (fingerprintElement != null) {
                                            String fingerprintInstance;
                                            fingerprintInstance = fingerprintElement.getTextContent();
                                            publicKeyInstance.setFingerprint(fingerprintInstance);
                                        }

                                        Element pathElement2 = XmlUtility.getElementByTagNameNS(publicKeysElement,
                                                "http://schemas.microsoft.com/windowsazure", "Path");
                                        if (pathElement2 != null) {
                                            String pathInstance2;
                                            pathInstance2 = pathElement2.getTextContent();
                                            publicKeyInstance.setPath(pathInstance2);
                                        }
                                    }
                                }

                                Element keyPairsSequenceElement = XmlUtility.getElementByTagNameNS(sSHElement,
                                        "http://schemas.microsoft.com/windowsazure", "KeyPairs");
                                if (keyPairsSequenceElement != null) {
                                    for (int i14 = 0; i14 < com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(keyPairsSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "KeyPair")
                                            .size(); i14 = i14 + 1) {
                                        org.w3c.dom.Element keyPairsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                                .getElementsByTagNameNS(keyPairsSequenceElement,
                                                        "http://schemas.microsoft.com/windowsazure", "KeyPair")
                                                .get(i14));
                                        SshSettingKeyPair keyPairInstance = new SshSettingKeyPair();
                                        sSHInstance.getKeyPairs().add(keyPairInstance);

                                        Element fingerprintElement2 = XmlUtility.getElementByTagNameNS(
                                                keyPairsElement, "http://schemas.microsoft.com/windowsazure",
                                                "Fingerprint");
                                        if (fingerprintElement2 != null) {
                                            String fingerprintInstance2;
                                            fingerprintInstance2 = fingerprintElement2.getTextContent();
                                            keyPairInstance.setFingerprint(fingerprintInstance2);
                                        }

                                        Element pathElement3 = XmlUtility.getElementByTagNameNS(keyPairsElement,
                                                "http://schemas.microsoft.com/windowsazure", "Path");
                                        if (pathElement3 != null) {
                                            String pathInstance3;
                                            pathInstance3 = pathElement3.getTextContent();
                                            keyPairInstance.setPath(pathInstance3);
                                        }
                                    }
                                }
                            }

                            Element customDataElement = XmlUtility.getElementByTagNameNS(configurationSetsElement,
                                    "http://schemas.microsoft.com/windowsazure", "CustomData");
                            if (customDataElement != null) {
                                String customDataInstance;
                                customDataInstance = customDataElement.getTextContent();
                                configurationSetInstance.setCustomData(customDataInstance);
                            }
                        }
                    }

                    Element dataVirtualHardDisksSequenceElement = XmlUtility.getElementByTagNameNS(
                            persistentVMRoleElement, "http://schemas.microsoft.com/windowsazure",
                            "DataVirtualHardDisks");
                    if (dataVirtualHardDisksSequenceElement != null) {
                        for (int i15 = 0; i15 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(dataVirtualHardDisksSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk")
                                .size(); i15 = i15 + 1) {
                            org.w3c.dom.Element dataVirtualHardDisksElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(dataVirtualHardDisksSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "DataVirtualHardDisk")
                                    .get(i15));
                            DataVirtualHardDisk dataVirtualHardDiskInstance = new DataVirtualHardDisk();
                            result.getDataVirtualHardDisks().add(dataVirtualHardDiskInstance);

                            Element hostCachingElement = XmlUtility.getElementByTagNameNS(
                                    dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure",
                                    "HostCaching");
                            if (hostCachingElement != null) {
                                String hostCachingInstance;
                                hostCachingInstance = hostCachingElement.getTextContent();
                                dataVirtualHardDiskInstance.setHostCaching(hostCachingInstance);
                            }

                            Element diskLabelElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement,
                                    "http://schemas.microsoft.com/windowsazure", "DiskLabel");
                            if (diskLabelElement != null) {
                                String diskLabelInstance;
                                diskLabelInstance = diskLabelElement.getTextContent();
                                dataVirtualHardDiskInstance.setLabel(diskLabelInstance);
                            }

                            Element diskNameElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement,
                                    "http://schemas.microsoft.com/windowsazure", "DiskName");
                            if (diskNameElement != null) {
                                String diskNameInstance;
                                diskNameInstance = diskNameElement.getTextContent();
                                dataVirtualHardDiskInstance.setName(diskNameInstance);
                            }

                            Element lunElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement,
                                    "http://schemas.microsoft.com/windowsazure", "Lun");
                            if (lunElement != null && lunElement.getTextContent() != null
                                    && !lunElement.getTextContent().isEmpty()) {
                                int lunInstance;
                                lunInstance = DatatypeConverter.parseInt(lunElement.getTextContent());
                                dataVirtualHardDiskInstance.setLogicalUnitNumber(lunInstance);
                            }

                            Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(
                                    dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure",
                                    "LogicalDiskSizeInGB");
                            if (logicalDiskSizeInGBElement != null
                                    && logicalDiskSizeInGBElement.getTextContent() != null
                                    && !logicalDiskSizeInGBElement.getTextContent().isEmpty()) {
                                int logicalDiskSizeInGBInstance;
                                logicalDiskSizeInGBInstance = DatatypeConverter
                                        .parseInt(logicalDiskSizeInGBElement.getTextContent());
                                dataVirtualHardDiskInstance.setLogicalDiskSizeInGB(logicalDiskSizeInGBInstance);
                            }

                            Element mediaLinkElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement,
                                    "http://schemas.microsoft.com/windowsazure", "MediaLink");
                            if (mediaLinkElement != null) {
                                URI mediaLinkInstance;
                                mediaLinkInstance = new URI(mediaLinkElement.getTextContent());
                                dataVirtualHardDiskInstance.setMediaLink(mediaLinkInstance);
                            }

                            Element sourceMediaLinkElement = XmlUtility.getElementByTagNameNS(
                                    dataVirtualHardDisksElement, "http://schemas.microsoft.com/windowsazure",
                                    "SourceMediaLink");
                            if (sourceMediaLinkElement != null) {
                                URI sourceMediaLinkInstance;
                                sourceMediaLinkInstance = new URI(sourceMediaLinkElement.getTextContent());
                                dataVirtualHardDiskInstance.setSourceMediaLink(sourceMediaLinkInstance);
                            }

                            Element iOTypeElement = XmlUtility.getElementByTagNameNS(dataVirtualHardDisksElement,
                                    "http://schemas.microsoft.com/windowsazure", "IOType");
                            if (iOTypeElement != null) {
                                String iOTypeInstance;
                                iOTypeInstance = iOTypeElement.getTextContent();
                                dataVirtualHardDiskInstance.setIOType(iOTypeInstance);
                            }
                        }
                    }

                    Element oSVirtualHardDiskElement = XmlUtility.getElementByTagNameNS(persistentVMRoleElement,
                            "http://schemas.microsoft.com/windowsazure", "OSVirtualHardDisk");
                    if (oSVirtualHardDiskElement != null) {
                        OSVirtualHardDisk oSVirtualHardDiskInstance = new OSVirtualHardDisk();
                        result.setOSVirtualHardDisk(oSVirtualHardDiskInstance);

                        Element hostCachingElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "HostCaching");
                        if (hostCachingElement2 != null) {
                            String hostCachingInstance2;
                            hostCachingInstance2 = hostCachingElement2.getTextContent();
                            oSVirtualHardDiskInstance.setHostCaching(hostCachingInstance2);
                        }

                        Element diskLabelElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "DiskLabel");
                        if (diskLabelElement2 != null) {
                            String diskLabelInstance2;
                            diskLabelInstance2 = diskLabelElement2.getTextContent();
                            oSVirtualHardDiskInstance.setLabel(diskLabelInstance2);
                        }

                        Element diskNameElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "DiskName");
                        if (diskNameElement2 != null) {
                            String diskNameInstance2;
                            diskNameInstance2 = diskNameElement2.getTextContent();
                            oSVirtualHardDiskInstance.setName(diskNameInstance2);
                        }

                        Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "MediaLink");
                        if (mediaLinkElement2 != null) {
                            URI mediaLinkInstance2;
                            mediaLinkInstance2 = new URI(mediaLinkElement2.getTextContent());
                            oSVirtualHardDiskInstance.setMediaLink(mediaLinkInstance2);
                        }

                        Element sourceImageNameElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "SourceImageName");
                        if (sourceImageNameElement != null) {
                            String sourceImageNameInstance;
                            sourceImageNameInstance = sourceImageNameElement.getTextContent();
                            oSVirtualHardDiskInstance.setSourceImageName(sourceImageNameInstance);
                        }

                        Element osElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "OS");
                        if (osElement != null) {
                            String osInstance;
                            osInstance = osElement.getTextContent();
                            oSVirtualHardDiskInstance.setOperatingSystem(osInstance);
                        }

                        Element remoteSourceImageLinkElement = XmlUtility.getElementByTagNameNS(
                                oSVirtualHardDiskElement, "http://schemas.microsoft.com/windowsazure",
                                "RemoteSourceImageLink");
                        if (remoteSourceImageLinkElement != null) {
                            URI remoteSourceImageLinkInstance;
                            remoteSourceImageLinkInstance = new URI(remoteSourceImageLinkElement.getTextContent());
                            oSVirtualHardDiskInstance.setRemoteSourceImageLink(remoteSourceImageLinkInstance);
                        }

                        Element iOTypeElement2 = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "IOType");
                        if (iOTypeElement2 != null) {
                            String iOTypeInstance2;
                            iOTypeInstance2 = iOTypeElement2.getTextContent();
                            oSVirtualHardDiskInstance.setIOType(iOTypeInstance2);
                        }

                        Element resizedSizeInGBElement = XmlUtility.getElementByTagNameNS(oSVirtualHardDiskElement,
                                "http://schemas.microsoft.com/windowsazure", "ResizedSizeInGB");
                        if (resizedSizeInGBElement != null && resizedSizeInGBElement.getTextContent() != null
                                && !resizedSizeInGBElement.getTextContent().isEmpty()) {
                            int resizedSizeInGBInstance;
                            resizedSizeInGBInstance = DatatypeConverter
                                    .parseInt(resizedSizeInGBElement.getTextContent());
                            oSVirtualHardDiskInstance.setResizedSizeInGB(resizedSizeInGBInstance);
                        }
                    }
                }

            }
            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 Download RDP file operation retrieves the Remote Desktop Protocol
    * configuration file from the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine.
    * @return The Download RDP file operation response.
    */
    @Override
    public Future<VirtualMachineGetRemoteDesktopFileResponse> getRemoteDesktopFileAsync(final String serviceName,
            final String deploymentName, final String virtualMachineName) {
        return this.getClient().getExecutorService()
                .submit(new Callable<VirtualMachineGetRemoteDesktopFileResponse>() {
                    @Override
                    public VirtualMachineGetRemoteDesktopFileResponse call() throws Exception {
                        return getRemoteDesktopFile(serviceName, deploymentName, virtualMachineName);
                    }
                });
    }

    /**
    * The Download RDP file operation retrieves the Remote Desktop Protocol
    * configuration file from the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157183.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine.
    * @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 Download RDP file operation response.
    */
    @Override
    public VirtualMachineGetRemoteDesktopFileResponse getRemoteDesktopFile(String serviceName,
            String deploymentName, String virtualMachineName) throws IOException, ServiceException {
        // Validate
        if (serviceName == null) {
            throw new NullPointerException("serviceName");
        }
        if (deploymentName == null) {
            throw new NullPointerException("deploymentName");
        }
        if (virtualMachineName == null) {
            throw new NullPointerException("virtualMachineName");
        }

        // 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            CloudTracing.enter(invocationId, this, "getRemoteDesktopFileAsync", 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/hostedservices/";
        url = url + URLEncoder.encode(serviceName, "UTF-8");
        url = url + "/deployments/";
        url = url + URLEncoder.encode(deploymentName, "UTF-8");
        url = url + "/roleinstances/";
        url = url + URLEncoder.encode(virtualMachineName, "UTF-8");
        url = url + "/ModelFile";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("FileType=RDP");
        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
            VirtualMachineGetRemoteDesktopFileResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineGetRemoteDesktopFileResponse();
                result.setRemoteDesktopFile(StreamUtils.toString(responseContent).getBytes("UTF-8"));

            }
            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 Restart role operation restarts the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> restartAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return restart(serviceName, deploymentName, virtualMachineName);
            }
        });
    }

    /**
    * The Restart role operation restarts the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157197.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * restart.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse restart(String serviceName, String deploymentName, String virtualMachineName)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            CloudTracing.enter(invocationId, this, "restartAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginRestartingAsync(serviceName, deploymentName, virtualMachineName).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 Shutdown Role operation shuts down the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * shutdown.
    * @param parameters Required. The parameters for the shutdown virtual
    * machine 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> shutdownAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName, final VirtualMachineShutdownParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return shutdown(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * The Shutdown Role operation shuts down the specified virtual machine.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157195.aspx
    * for more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * shutdown.
    * @param parameters Required. The parameters for the shutdown virtual
    * machine 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse shutdown(String serviceName, String deploymentName, String virtualMachineName,
            VirtualMachineShutdownParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "shutdownAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginShutdownAsync(serviceName, deploymentName, virtualMachineName, parameters).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 Shutdown Roles operation stops the specified set of virtual machines.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Shutdown Roles
    * 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> shutdownRolesAsync(final String serviceName, final String deploymentName,
            final VirtualMachineShutdownRolesParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return shutdownRoles(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Shutdown Roles operation stops the specified set of virtual machines.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Shutdown Roles
    * 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse shutdownRoles(String serviceName, String deploymentName,
            VirtualMachineShutdownRolesParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "shutdownRolesAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginShuttingDownRolesAsync(serviceName, deploymentName, parameters).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 Start Role operation starts the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * start.
    * @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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> startAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return start(serviceName, deploymentName, virtualMachineName);
            }
        });
    }

    /**
    * The Start Role operation starts the specified virtual machine.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157189.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of the virtual machine to
    * start.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse start(String serviceName, String deploymentName, String virtualMachineName)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            CloudTracing.enter(invocationId, this, "startAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginStartingAsync(serviceName, deploymentName, virtualMachineName).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 Start Roles operation starts the specified set of virtual machines.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Start Roles
    * 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> startRolesAsync(final String serviceName, final String deploymentName,
            final VirtualMachineStartRolesParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return startRoles(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Start Roles operation starts the specified set of virtual machines.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters to pass to the Start Roles
    * 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse startRoles(String serviceName, String deploymentName,
            VirtualMachineStartRolesParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "startRolesAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginStartingRolesAsync(serviceName, deploymentName, parameters).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 Update Role operation adds a virtual machine to an existing
    * deployment.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of your virtual machine.
    * @param parameters Required. Parameters supplied to the Update Virtual
    * Machine 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> updateAsync(final String serviceName, final String deploymentName,
            final String virtualMachineName, final VirtualMachineUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return update(serviceName, deploymentName, virtualMachineName, parameters);
            }
        });
    }

    /**
    * The Update Role operation adds a virtual machine to an existing
    * deployment.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157187.aspx for
    * more information)
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param virtualMachineName Required. The name of your virtual machine.
    * @param parameters Required. Parameters supplied to the Update Virtual
    * Machine 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 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 ServiceException Thrown if an unexpected response is found.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the 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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse update(String serviceName, String deploymentName, String virtualMachineName,
            VirtualMachineUpdateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException,
            ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("virtualMachineName", virtualMachineName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginUpdatingAsync(serviceName, deploymentName, virtualMachineName, parameters).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 Update Load Balanced Endpoint Set operation changes the specified
    * load-balanced InputEndpoints on all the roles of an Infrastructure as a
    * Service deployment. Non-load-balanced endpoints must be changed using
    * UpdateRole.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Update Load
    * Balanced Endpoint Set 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 error information regarding the failure.
    */
    @Override
    public Future<OperationStatusResponse> updateLoadBalancedEndpointSetAsync(final String serviceName,
            final String deploymentName, final VirtualMachineUpdateLoadBalancedSetParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return updateLoadBalancedEndpointSet(serviceName, deploymentName, parameters);
            }
        });
    }

    /**
    * The Update Load Balanced Endpoint Set operation changes the specified
    * load-balanced InputEndpoints on all the roles of an Infrastructure as a
    * Service deployment. Non-load-balanced endpoints must be changed using
    * UpdateRole.
    *
    * @param serviceName Required. The name of your service.
    * @param deploymentName Required. The name of your deployment.
    * @param parameters Required. Parameters supplied to the Update Load
    * Balanced Endpoint Set 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.
    * @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 error information regarding the failure.
    */
    @Override
    public OperationStatusResponse updateLoadBalancedEndpointSet(String serviceName, String deploymentName,
            VirtualMachineUpdateLoadBalancedSetParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException {
        ComputeManagementClient 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("serviceName", serviceName);
            tracingParameters.put("deploymentName", deploymentName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "updateLoadBalancedEndpointSetAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachinesOperations()
                    .beginUpdatingLoadBalancedEndpointSetAsync(serviceName, deploymentName, parameters).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();
            }
        }
    }
}