com.microsoft.windowsazure.management.AffinityGroupOperationsImpl.java Source code

Java tutorial

Introduction

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

import com.microsoft.windowsazure.core.OperationResponse;
import com.microsoft.windowsazure.core.ServiceOperations;
import com.microsoft.windowsazure.core.pipeline.apache.CustomHttpDelete;
import com.microsoft.windowsazure.core.utils.BOMInputStream;
import com.microsoft.windowsazure.core.utils.Base64;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.models.AffinityGroupCreateParameters;
import com.microsoft.windowsazure.management.models.AffinityGroupGetResponse;
import com.microsoft.windowsazure.management.models.AffinityGroupListResponse;
import com.microsoft.windowsazure.management.models.AffinityGroupUpdateParameters;
import com.microsoft.windowsazure.management.models.ComputeCapabilities;
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.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;

/**
* Operations for managing affinity groups in your subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/ee460798.aspx for more
* information)
*/
public class AffinityGroupOperationsImpl
        implements ServiceOperations<ManagementClientImpl>, AffinityGroupOperations {
    /**
    * Initializes a new instance of the AffinityGroupOperationsImpl class.
    *
    * @param client Reference to the service client.
    */
    AffinityGroupOperationsImpl(ManagementClientImpl client) {
        this.client = client;
    }

    private ManagementClientImpl client;

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

    /**
    * The Create Affinity Group operation creates a new affinity group for the
    * specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Create Affinity
    * Group operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> createAsync(final AffinityGroupCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return create(parameters);
            }
        });
    }

    /**
    * The Create Affinity Group operation creates a new affinity group for the
    * specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for
    * more information)
    *
    * @param parameters Required. Parameters supplied to the Create Affinity
    * Group 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 create(AffinityGroupCreateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
            throw new IllegalArgumentException("parameters.Description");
        }
        if (parameters.getLabel() == null) {
            throw new NullPointerException("parameters.Label");
        }
        if (parameters.getLabel().length() > 100) {
            throw new IllegalArgumentException("parameters.Label");
        }
        if (parameters.getLocation() == null) {
            throw new NullPointerException("parameters.Location");
        }
        if (parameters.getName() == null) {
            throw new NullPointerException("parameters.Name");
        }

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

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

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

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

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

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

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

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

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

        Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Location");
        locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
        createAffinityGroupElement.appendChild(locationElement);

        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_CREATED) {
                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 Delete Affinity Group operation deletes an affinity group in the
    * specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx for
    * more information)
    *
    * @param affinityGroupName Required. The name of the affinity group.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> deleteAsync(final String affinityGroupName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return delete(affinityGroupName);
            }
        });
    }

    /**
    * The Delete Affinity Group operation deletes an affinity group in the
    * specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/gg715314.aspx for
    * more information)
    *
    * @param affinityGroupName Required. The name of the affinity group.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse delete(String affinityGroupName) throws IOException, ServiceException {
        // Validate
        if (affinityGroupName == null) {
            throw new NullPointerException("affinityGroupName");
        }

        // 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("affinityGroupName", affinityGroupName);
            CloudTracing.enter(invocationId, this, "deleteAsync", tracingParameters);
        }

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

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

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

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

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

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

    /**
    * The Get Affinity Group Properties operation returns the system properties
    * associated with the specified affinity group.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for
    * more information)
    *
    * @param affinityGroupName Required. The name of the desired affinity group
    * as returned by the name element of the List Affinity Groups operation.
    * @return The Get Affinity Group operation response.
    */
    @Override
    public Future<AffinityGroupGetResponse> getAsync(final String affinityGroupName) {
        return this.getClient().getExecutorService().submit(new Callable<AffinityGroupGetResponse>() {
            @Override
            public AffinityGroupGetResponse call() throws Exception {
                return get(affinityGroupName);
            }
        });
    }

    /**
    * The Get Affinity Group Properties operation returns the system properties
    * associated with the specified affinity group.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460789.aspx for
    * more information)
    *
    * @param affinityGroupName Required. The name of the desired affinity group
    * as returned by the name element of the List Affinity Groups operation.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The Get Affinity Group operation response.
    */
    @Override
    public AffinityGroupGetResponse get(String affinityGroupName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (affinityGroupName == null) {
            throw new NullPointerException("affinityGroupName");
        }

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

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

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2014-10-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
            AffinityGroupGetResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new AffinityGroupGetResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

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

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

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

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

                    Element hostedServicesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement,
                            "http://schemas.microsoft.com/windowsazure", "HostedServices");
                    if (hostedServicesSequenceElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(hostedServicesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "HostedService")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element hostedServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(hostedServicesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "HostedService")
                                    .get(i1));
                            AffinityGroupGetResponse.HostedServiceReference hostedServiceInstance = new AffinityGroupGetResponse.HostedServiceReference();
                            result.getHostedServices().add(hostedServiceInstance);

                            Element urlElement = XmlUtility.getElementByTagNameNS(hostedServicesElement,
                                    "http://schemas.microsoft.com/windowsazure", "Url");
                            if (urlElement != null) {
                                URI urlInstance;
                                urlInstance = new URI(urlElement.getTextContent());
                                hostedServiceInstance.setUri(urlInstance);
                            }

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

                    Element storageServicesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement,
                            "http://schemas.microsoft.com/windowsazure", "StorageServices");
                    if (storageServicesSequenceElement != null) {
                        for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(storageServicesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "StorageService")
                                .size(); i2 = i2 + 1) {
                            org.w3c.dom.Element storageServicesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(storageServicesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "StorageService")
                                    .get(i2));
                            AffinityGroupGetResponse.StorageServiceReference storageServiceInstance = new AffinityGroupGetResponse.StorageServiceReference();
                            result.getStorageServices().add(storageServiceInstance);

                            Element urlElement2 = XmlUtility.getElementByTagNameNS(storageServicesElement,
                                    "http://schemas.microsoft.com/windowsazure", "Url");
                            if (urlElement2 != null) {
                                URI urlInstance2;
                                urlInstance2 = new URI(urlElement2.getTextContent());
                                storageServiceInstance.setUri(urlInstance2);
                            }

                            Element serviceNameElement2 = XmlUtility.getElementByTagNameNS(storageServicesElement,
                                    "http://schemas.microsoft.com/windowsazure", "ServiceName");
                            if (serviceNameElement2 != null) {
                                String serviceNameInstance2;
                                serviceNameInstance2 = serviceNameElement2.getTextContent();
                                storageServiceInstance.setServiceName(serviceNameInstance2);
                            }
                        }
                    }

                    Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(affinityGroupElement,
                            "http://schemas.microsoft.com/windowsazure", "Capabilities");
                    if (capabilitiesSequenceElement != null) {
                        for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(capabilitiesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "Capability")
                                .size(); i3 = i3 + 1) {
                            org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(capabilitiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Capability")
                                    .get(i3));
                            result.getCapabilities().add(capabilitiesElement.getTextContent());
                        }
                    }

                    Element createdTimeElement = XmlUtility.getElementByTagNameNS(affinityGroupElement,
                            "http://schemas.microsoft.com/windowsazure", "CreatedTime");
                    if (createdTimeElement != null && createdTimeElement.getTextContent() != null
                            && !createdTimeElement.getTextContent().isEmpty()) {
                        Calendar createdTimeInstance;
                        createdTimeInstance = DatatypeConverter.parseDateTime(createdTimeElement.getTextContent());
                        result.setCreatedTime(createdTimeInstance);
                    }

                    Element computeCapabilitiesElement = XmlUtility.getElementByTagNameNS(affinityGroupElement,
                            "http://schemas.microsoft.com/windowsazure", "ComputeCapabilities");
                    if (computeCapabilitiesElement != null) {
                        ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities();
                        result.setComputeCapabilities(computeCapabilitiesInstance);

                        Element virtualMachinesRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                "VirtualMachinesRoleSizes");
                        if (virtualMachinesRoleSizesSequenceElement != null) {
                            for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                    .size(); i4 = i4 + 1) {
                                org.w3c.dom.Element virtualMachinesRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .get(i4));
                                computeCapabilitiesInstance.getVirtualMachinesRoleSizes()
                                        .add(virtualMachinesRoleSizesElement.getTextContent());
                            }
                        }

                        Element webWorkerRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                "WebWorkerRoleSizes");
                        if (webWorkerRoleSizesSequenceElement != null) {
                            for (int i5 = 0; i5 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                    .size(); i5 = i5 + 1) {
                                org.w3c.dom.Element webWorkerRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .get(i5));
                                computeCapabilitiesInstance.getWebWorkerRoleSizes()
                                        .add(webWorkerRoleSizesElement.getTextContent());
                            }
                        }
                    }
                }

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

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

    /**
    * The List Affinity Groups operation lists the affinity groups associated
    * with the specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for
    * more information)
    *
    * @return The List Affinity Groups operation response.
    */
    @Override
    public Future<AffinityGroupListResponse> listAsync() {
        return this.getClient().getExecutorService().submit(new Callable<AffinityGroupListResponse>() {
            @Override
            public AffinityGroupListResponse call() throws Exception {
                return list();
            }
        });
    }

    /**
    * The List Affinity Groups operation lists the affinity groups associated
    * with the specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/ee460797.aspx for
    * more information)
    *
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @return The List Affinity Groups operation response.
    */
    @Override
    public AffinityGroupListResponse list()
            throws IOException, ServiceException, ParserConfigurationException, SAXException {
        // Validate

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

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

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

        // Set Headers
        httpRequest.setHeader("x-ms-version", "2014-10-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
            AffinityGroupListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new AffinityGroupListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element affinityGroupsSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "AffinityGroups");
                if (affinityGroupsSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(affinityGroupsSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "AffinityGroup")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element affinityGroupsElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(affinityGroupsSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "AffinityGroup")
                                .get(i1));
                        AffinityGroupListResponse.AffinityGroup affinityGroupInstance = new AffinityGroupListResponse.AffinityGroup();
                        result.getAffinityGroups().add(affinityGroupInstance);

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

                        Element labelElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                                "http://schemas.microsoft.com/windowsazure", "Label");
                        if (labelElement != null) {
                            String labelInstance;
                            labelInstance = labelElement.getTextContent() != null
                                    ? new String(Base64.decode(labelElement.getTextContent()))
                                    : null;
                            affinityGroupInstance.setLabel(labelInstance);
                        }

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

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

                        Element capabilitiesSequenceElement = XmlUtility.getElementByTagNameNS(
                                affinityGroupsElement, "http://schemas.microsoft.com/windowsazure", "Capabilities");
                        if (capabilitiesSequenceElement != null) {
                            for (int i2 = 0; i2 < com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(capabilitiesSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure", "Capability")
                                    .size(); i2 = i2 + 1) {
                                org.w3c.dom.Element capabilitiesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(capabilitiesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "Capability")
                                        .get(i2));
                                affinityGroupInstance.getCapabilities().add(capabilitiesElement.getTextContent());
                            }
                        }

                        Element createdTimeElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                                "http://schemas.microsoft.com/windowsazure", "CreatedTime");
                        if (createdTimeElement != null && createdTimeElement.getTextContent() != null
                                && !createdTimeElement.getTextContent().isEmpty()) {
                            Calendar createdTimeInstance;
                            createdTimeInstance = DatatypeConverter
                                    .parseDateTime(createdTimeElement.getTextContent());
                            affinityGroupInstance.setCreatedTime(createdTimeInstance);
                        }

                        Element computeCapabilitiesElement = XmlUtility.getElementByTagNameNS(affinityGroupsElement,
                                "http://schemas.microsoft.com/windowsazure", "ComputeCapabilities");
                        if (computeCapabilitiesElement != null) {
                            ComputeCapabilities computeCapabilitiesInstance = new ComputeCapabilities();
                            affinityGroupInstance.setComputeCapabilities(computeCapabilitiesInstance);

                            Element virtualMachinesRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                    computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                    "VirtualMachinesRoleSizes");
                            if (virtualMachinesRoleSizesSequenceElement != null) {
                                for (int i3 = 0; i3 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .size(); i3 = i3 + 1) {
                                    org.w3c.dom.Element virtualMachinesRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(virtualMachinesRoleSizesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                            .get(i3));
                                    computeCapabilitiesInstance.getVirtualMachinesRoleSizes()
                                            .add(virtualMachinesRoleSizesElement.getTextContent());
                                }
                            }

                            Element webWorkerRoleSizesSequenceElement = XmlUtility.getElementByTagNameNS(
                                    computeCapabilitiesElement, "http://schemas.microsoft.com/windowsazure",
                                    "WebWorkerRoleSizes");
                            if (webWorkerRoleSizesSequenceElement != null) {
                                for (int i4 = 0; i4 < com.microsoft.windowsazure.core.utils.XmlUtility
                                        .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                                "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                        .size(); i4 = i4 + 1) {
                                    org.w3c.dom.Element webWorkerRoleSizesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                            .getElementsByTagNameNS(webWorkerRoleSizesSequenceElement,
                                                    "http://schemas.microsoft.com/windowsazure", "RoleSize")
                                            .get(i4));
                                    computeCapabilitiesInstance.getWebWorkerRoleSizes()
                                            .add(webWorkerRoleSizesElement.getTextContent());
                                }
                            }
                        }
                    }
                }

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

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

    /**
    * The Update Affinity Group operation updates the label and/or the
    * description for an affinity group for the specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for
    * more information)
    *
    * @param affinityGroupName Required. The name of the affinity group.
    * @param parameters Required. Parameters supplied to the Update Affinity
    * Group operation.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> updateAsync(final String affinityGroupName,
            final AffinityGroupUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return update(affinityGroupName, parameters);
            }
        });
    }

    /**
    * The Update Affinity Group operation updates the label and/or the
    * description for an affinity group for the specified subscription.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for
    * more information)
    *
    * @param affinityGroupName Required. The name of the affinity group.
    * @param parameters Required. Parameters supplied to the Update Affinity
    * Group 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 update(String affinityGroupName, AffinityGroupUpdateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (affinityGroupName == null) {
            throw new NullPointerException("affinityGroupName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
            throw new IllegalArgumentException("parameters.Description");
        }
        if (parameters.getLabel() == null) {
            throw new NullPointerException("parameters.Label");
        }
        if (parameters.getLabel().length() > 100) {
            throw new IllegalArgumentException("parameters.Label");
        }

        // 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("affinityGroupName", affinityGroupName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
        }

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

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

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

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

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

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

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

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

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

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