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

Java tutorial

Introduction

Here is the source code for com.microsoft.windowsazure.management.compute.VirtualMachineOSImageOperationsImpl.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.CollectionStringBuilder;
import com.microsoft.windowsazure.core.utils.XmlUtility;
import com.microsoft.windowsazure.exception.CloudError;
import com.microsoft.windowsazure.exception.ServiceException;
import com.microsoft.windowsazure.management.compute.models.ComputeImageAttributes;
import com.microsoft.windowsazure.management.compute.models.MarketplaceImageAttributes;
import com.microsoft.windowsazure.management.compute.models.Plan;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageCreateResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageGetDetailsResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageGetResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageListResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageReplicateParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageReplicateResponse;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateParameters;
import com.microsoft.windowsazure.management.compute.models.VirtualMachineOSImageUpdateResponse;
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.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.TimeZone;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
* The Service Management API includes operations for managing the OS images in
* your subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx for more
* information)
*/
public class VirtualMachineOSImageOperationsImpl
        implements ServiceOperations<ComputeManagementClientImpl>, VirtualMachineOSImageOperations {
    /**
    * Initializes a new instance of the VirtualMachineOSImageOperationsImpl
    * class.
    *
    * @param client Reference to the service client.
    */
    VirtualMachineOSImageOperationsImpl(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;
    }

    /**
    * Share an already replicated OS image. This operation is only for
    * publishers. You have to be registered as image publisher with Windows
    * Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine image to share.
    * @param permission Required. The sharing permission: public, msdn, or
    * private.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginSharingAsync(final String imageName, final String permission) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginSharing(imageName, permission);
            }
        });
    }

    /**
    * Share an already replicated OS image. This operation is only for
    * publishers. You have to be registered as image publisher with Windows
    * Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine image to share.
    * @param permission Required. The sharing permission: public, msdn, or
    * private.
    * @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 beginSharing(String imageName, String permission)
            throws IOException, ServiceException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }
        if (permission == null) {
            throw new NullPointerException("permission");
        }

        // 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("imageName", imageName);
            tracingParameters.put("permission", permission);
            CloudTracing.enter(invocationId, this, "beginSharingAsync", 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/images/";
        url = url + URLEncoder.encode(imageName, "UTF-8");
        url = url + "/shareasync";
        ArrayList<String> queryParameters = new ArrayList<String>();
        queryParameters.add("permission=" + URLEncoder.encode(permission, "UTF-8"));
        if (queryParameters.size() > 0) {
            url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
        }
        String baseUrl = this.getClient().getBaseUri().toString();
        // Trim '/' character from the end of baseUrl and beginning of url.
        if (baseUrl.charAt(baseUrl.length() - 1) == '/') {
            baseUrl = baseUrl.substring(0, (baseUrl.length() - 1) + 0);
        }
        if (url.charAt(0) == '/') {
            url = url.substring(1);
        }
        url = baseUrl + "/" + url;
        url = url.replace(" ", "%20");

        // Create HTTP transport objects
        HttpPut httpRequest = new HttpPut(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();
            }
        }
    }

    /**
    * Unreplicate an OS image to multiple target locations. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this. Note: The operation removes the
    * published copies of the user OS Image. It does not remove the actual
    * user OS Image. To remove the actual user OS Image, the publisher will
    * have to call Delete OS Image.
    *
    * @param imageName Required. The name of the virtual machine image to
    * replicate. Note: The OS Image Name should be the user OS Image, not the
    * published name of the OS Image.
    * @return A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public Future<OperationResponse> beginUnreplicatingAsync(final String imageName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationResponse>() {
            @Override
            public OperationResponse call() throws Exception {
                return beginUnreplicating(imageName);
            }
        });
    }

    /**
    * Unreplicate an OS image to multiple target locations. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this. Note: The operation removes the
    * published copies of the user OS Image. It does not remove the actual
    * user OS Image. To remove the actual user OS Image, the publisher will
    * have to call Delete OS Image.
    *
    * @param imageName Required. The name of the virtual machine image to
    * replicate. Note: The OS Image Name should be the user OS Image, not the
    * published name of the OS Image.
    * @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 beginUnreplicating(String imageName) throws IOException, ServiceException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }

        // 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("imageName", imageName);
            CloudTracing.enter(invocationId, this, "beginUnreplicatingAsync", 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/images/";
        url = url + URLEncoder.encode(imageName, "UTF-8");
        url = url + "/unreplicate";
        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("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
            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 Create OS Image operation adds an operating system image that is
    * stored in a storage account and is available from the image repository.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx
    * for more information)
    *
    * @param parameters Required. Parameters supplied to the Create Virtual
    * Machine Image operation.
    * @return Parameters returned from the Create Virtual Machine Image
    * operation.
    */
    @Override
    public Future<VirtualMachineOSImageCreateResponse> createAsync(
            final VirtualMachineOSImageCreateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineOSImageCreateResponse>() {
            @Override
            public VirtualMachineOSImageCreateResponse call() throws Exception {
                return create(parameters);
            }
        });
    }

    /**
    * The Create OS Image operation adds an operating system image that is
    * stored in a storage account and is available from the image repository.
    * (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx
    * for more information)
    *
    * @param parameters Required. Parameters supplied to the Create Virtual
    * Machine Image 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 Parameters returned from the Create Virtual Machine Image
    * operation.
    */
    @Override
    public VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException,
            ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
        // Validate
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getLabel() == null) {
            throw new NullPointerException("parameters.Label");
        }
        if (parameters.getMediaLinkUri() == null) {
            throw new NullPointerException("parameters.MediaLinkUri");
        }
        if (parameters.getName() == null) {
            throw new NullPointerException("parameters.Name");
        }
        if (parameters.getOperatingSystemType() == null) {
            throw new NullPointerException("parameters.OperatingSystemType");
        }

        // 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 + "/services/images";
        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 oSImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSImage");
        requestDoc.appendChild(oSImageElement);

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

        Element mediaLinkElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "MediaLink");
        mediaLinkElement.appendChild(requestDoc.createTextNode(parameters.getMediaLinkUri().toString()));
        oSImageElement.appendChild(mediaLinkElement);

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

        Element osElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OS");
        osElement.appendChild(requestDoc.createTextNode(parameters.getOperatingSystemType()));
        oSImageElement.appendChild(osElement);

        if (parameters.getEula() != null) {
            Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
            eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula()));
            oSImageElement.appendChild(eulaElement);
        }

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

        if (parameters.getImageFamily() != null) {
            Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ImageFamily");
            imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily()));
            oSImageElement.appendChild(imageFamilyElement);
        }

        if (parameters.getPublishedDate() != null) {
            Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "PublishedDate");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            publishedDateElement.appendChild(
                    requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
            oSImageElement.appendChild(publishedDateElement);
        }

        Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "IsPremium");
        isPremiumElement
                .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase()));
        oSImageElement.appendChild(isPremiumElement);

        Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ShowInGui");
        showInGuiElement
                .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase()));
        oSImageElement.appendChild(showInGuiElement);

        if (parameters.getPrivacyUri() != null) {
            Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "PrivacyUri");
            privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
            oSImageElement.appendChild(privacyUriElement);
        }

        if (parameters.getIconUri() != null) {
            Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "IconUri");
            iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri()));
            oSImageElement.appendChild(iconUriElement);
        }

        if (parameters.getRecommendedVMSize() != null) {
            Element recommendedVMSizeElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
            recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize()));
            oSImageElement.appendChild(recommendedVMSizeElement);
        }

        if (parameters.getSmallIconUri() != null) {
            Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SmallIconUri");
            smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri()));
            oSImageElement.appendChild(smallIconUriElement);
        }

        if (parameters.getLanguage() != null) {
            Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Language");
            languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage()));
            oSImageElement.appendChild(languageElement);
        }

        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
            VirtualMachineOSImageCreateResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineOSImageCreateResponse();
                DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
                documentBuilderFactory2.setNamespaceAware(true);
                DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
                Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

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

                    Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "Category");
                    if (categoryElement != null) {
                        String categoryInstance;
                        categoryInstance = categoryElement.getTextContent();
                        result.setCategory(categoryInstance);
                    }

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

                    Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                    if (logicalSizeInGBElement != null) {
                        double logicalSizeInGBInstance;
                        logicalSizeInGBInstance = DatatypeConverter
                                .parseDouble(logicalSizeInGBElement.getTextContent());
                        result.setLogicalSizeInGB(logicalSizeInGBInstance);
                    }

                    Element mediaLinkElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "MediaLink");
                    if (mediaLinkElement2 != null) {
                        URI mediaLinkInstance;
                        mediaLinkInstance = new URI(mediaLinkElement2.getTextContent());
                        result.setMediaLinkUri(mediaLinkInstance);
                    }

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

                    Element osElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "OS");
                    if (osElement2 != null) {
                        String osInstance;
                        osInstance = osElement2.getTextContent();
                        result.setOperatingSystemType(osInstance);
                    }

                    Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement2 != null) {
                        String eulaInstance;
                        eulaInstance = eulaElement2.getTextContent();
                        result.setEula(eulaInstance);
                    }

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

                    Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                    if (imageFamilyElement2 != null) {
                        String imageFamilyInstance;
                        imageFamilyInstance = imageFamilyElement2.getTextContent();
                        result.setImageFamily(imageFamilyInstance);
                    }

                    Element publishedDateElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement2 != null && publishedDateElement2.getTextContent() != null
                            && !publishedDateElement2.getTextContent().isEmpty()) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement2.getTextContent());
                        result.setPublishedDate(publishedDateInstance);
                    }

                    Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "PublisherName");
                    if (publisherNameElement != null) {
                        String publisherNameInstance;
                        publisherNameInstance = publisherNameElement.getTextContent();
                        result.setPublisherName(publisherNameInstance);
                    }

                    Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "IsPremium");
                    if (isPremiumElement2 != null && isPremiumElement2.getTextContent() != null
                            && !isPremiumElement2.getTextContent().isEmpty()) {
                        boolean isPremiumInstance;
                        isPremiumInstance = DatatypeConverter
                                .parseBoolean(isPremiumElement2.getTextContent().toLowerCase());
                        result.setIsPremium(isPremiumInstance);
                    }

                    Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                    if (showInGuiElement2 != null && showInGuiElement2.getTextContent() != null
                            && !showInGuiElement2.getTextContent().isEmpty()) {
                        boolean showInGuiInstance;
                        showInGuiInstance = DatatypeConverter
                                .parseBoolean(showInGuiElement2.getTextContent().toLowerCase());
                        result.setShowInGui(showInGuiInstance);
                    }

                    Element privacyUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement2 != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement2.getTextContent());
                        result.setPrivacyUri(privacyUriInstance);
                    }

                    Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "IconUri");
                    if (iconUriElement2 != null) {
                        String iconUriInstance;
                        iconUriInstance = iconUriElement2.getTextContent();
                        result.setIconUri(iconUriInstance);
                    }

                    Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                    if (recommendedVMSizeElement2 != null) {
                        String recommendedVMSizeInstance;
                        recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent();
                        result.setRecommendedVMSize(recommendedVMSizeInstance);
                    }

                    Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                    if (smallIconUriElement2 != null) {
                        String smallIconUriInstance;
                        smallIconUriInstance = smallIconUriElement2.getTextContent();
                        result.setSmallIconUri(smallIconUriInstance);
                    }

                    Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "Language");
                    if (languageElement2 != null) {
                        String languageInstance;
                        languageInstance = languageElement2.getTextContent();
                        result.setLanguage(languageInstance);
                    }

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

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

    /**
    * The Delete OS Image operation deletes the specified OS image from your
    * image repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157203.aspx for
    * more information)
    *
    * @param imageName Required. The name of the image to delete.
    * @param deleteFromStorage Required. Specifies that the source blob for the
    * image 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 A standard service response including an HTTP status code and
    * request ID.
    */
    @Override
    public OperationResponse delete(String imageName, boolean deleteFromStorage)
            throws IOException, ServiceException, InterruptedException, ExecutionException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }

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

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/images/";
        url = url + URLEncoder.encode(imageName, "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_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 OS Image operation retrieves the details for an operating system
    * image from the image repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for
    * more information)
    *
    * @param imageName Required. The name of the OS image to retrieve.
    * @return A virtual machine image associated with your subscription.
    */
    @Override
    public Future<VirtualMachineOSImageGetResponse> getAsync(final String imageName) {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineOSImageGetResponse>() {
            @Override
            public VirtualMachineOSImageGetResponse call() throws Exception {
                return get(imageName);
            }
        });
    }

    /**
    * The Get OS Image operation retrieves the details for an operating system
    * image from the image repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for
    * more information)
    *
    * @param imageName Required. The name of the OS image to retrieve.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @throws ParserConfigurationException Thrown if there was a serious
    * configuration error with the document parser.
    * @throws SAXException Thrown if there was an error parsing the XML
    * response.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return A virtual machine image associated with your subscription.
    */
    @Override
    public VirtualMachineOSImageGetResponse get(String imageName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }

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

                Element oSImageElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "OSImage");
                if (oSImageElement != null) {
                    Element affinityGroupElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "AffinityGroup");
                    if (affinityGroupElement != null) {
                        String affinityGroupInstance;
                        affinityGroupInstance = affinityGroupElement.getTextContent();
                        result.setAffinityGroup(affinityGroupInstance);
                    }

                    Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "Category");
                    if (categoryElement != null) {
                        String categoryInstance;
                        categoryInstance = categoryElement.getTextContent();
                        result.setCategory(categoryInstance);
                    }

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

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

                    Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                    if (logicalSizeInGBElement != null) {
                        double logicalSizeInGBInstance;
                        logicalSizeInGBInstance = DatatypeConverter
                                .parseDouble(logicalSizeInGBElement.getTextContent());
                        result.setLogicalSizeInGB(logicalSizeInGBInstance);
                    }

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

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

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

                    Element eulaElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement != null) {
                        String eulaInstance;
                        eulaInstance = eulaElement.getTextContent();
                        result.setEula(eulaInstance);
                    }

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

                    Element imageFamilyElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                    if (imageFamilyElement != null) {
                        String imageFamilyInstance;
                        imageFamilyInstance = imageFamilyElement.getTextContent();
                        result.setImageFamily(imageFamilyInstance);
                    }

                    Element showInGuiElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                    if (showInGuiElement != null && showInGuiElement.getTextContent() != null
                            && !showInGuiElement.getTextContent().isEmpty()) {
                        boolean showInGuiInstance;
                        showInGuiInstance = DatatypeConverter
                                .parseBoolean(showInGuiElement.getTextContent().toLowerCase());
                        result.setShowInGui(showInGuiInstance);
                    }

                    Element publishedDateElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement != null) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement.getTextContent());
                        result.setPublishedDate(publishedDateInstance);
                    }

                    Element isPremiumElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "IsPremium");
                    if (isPremiumElement != null && isPremiumElement.getTextContent() != null
                            && !isPremiumElement.getTextContent().isEmpty()) {
                        boolean isPremiumInstance;
                        isPremiumInstance = DatatypeConverter
                                .parseBoolean(isPremiumElement.getTextContent().toLowerCase());
                        result.setIsPremium(isPremiumInstance);
                    }

                    Element iconUriElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "IconUri");
                    if (iconUriElement != null) {
                        String iconUriInstance;
                        iconUriInstance = iconUriElement.getTextContent();
                        result.setIconUri(iconUriInstance);
                    }

                    Element privacyUriElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement.getTextContent());
                        result.setPrivacyUri(privacyUriInstance);
                    }

                    Element recommendedVMSizeElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                    if (recommendedVMSizeElement != null) {
                        String recommendedVMSizeInstance;
                        recommendedVMSizeInstance = recommendedVMSizeElement.getTextContent();
                        result.setRecommendedVMSize(recommendedVMSizeInstance);
                    }

                    Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "PublisherName");
                    if (publisherNameElement != null) {
                        String publisherNameInstance;
                        publisherNameInstance = publisherNameElement.getTextContent();
                        result.setPublisherName(publisherNameInstance);
                    }

                    Element smallIconUriElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                    if (smallIconUriElement != null) {
                        String smallIconUriInstance;
                        smallIconUriInstance = smallIconUriElement.getTextContent();
                        result.setSmallIconUri(smallIconUriInstance);
                    }

                    Element languageElement = XmlUtility.getElementByTagNameNS(oSImageElement,
                            "http://schemas.microsoft.com/windowsazure", "Language");
                    if (languageElement != null) {
                        String languageInstance;
                        languageInstance = languageElement.getTextContent();
                        result.setLanguage(languageInstance);
                    }

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

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

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

    /**
    * Gets OS Image's properties and its replication details. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine image to
    * replicate.
    * @return The Get Details OS Images operation response.
    */
    @Override
    public Future<VirtualMachineOSImageGetDetailsResponse> getDetailsAsync(final String imageName) {
        return this.getClient().getExecutorService()
                .submit(new Callable<VirtualMachineOSImageGetDetailsResponse>() {
                    @Override
                    public VirtualMachineOSImageGetDetailsResponse call() throws Exception {
                        return getDetails(imageName);
                    }
                });
    }

    /**
    * Gets OS Image's properties and its replication details. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine image to
    * replicate.
    * @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 Details OS Images operation response.
    */
    @Override
    public VirtualMachineOSImageGetDetailsResponse getDetails(String imageName)
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }

        // 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("imageName", imageName);
            CloudTracing.enter(invocationId, this, "getDetailsAsync", 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/images/";
        url = url + URLEncoder.encode(imageName, "UTF-8");
        url = url + "/details";
        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
            VirtualMachineOSImageGetDetailsResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineOSImageGetDetailsResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element oSImageDetailsElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "OSImageDetails");
                if (oSImageDetailsElement != null) {
                    Element isCorruptedElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsCorrupted");
                    if (isCorruptedElement != null && isCorruptedElement.getTextContent() != null
                            && !isCorruptedElement.getTextContent().isEmpty()) {
                        boolean isCorruptedInstance;
                        isCorruptedInstance = DatatypeConverter
                                .parseBoolean(isCorruptedElement.getTextContent().toLowerCase());
                        result.setIsCorrupted(isCorruptedInstance);
                    }

                    Element replicationProgressSequenceElement = XmlUtility.getElementByTagNameNS(
                            oSImageDetailsElement, "http://schemas.microsoft.com/windowsazure",
                            "ReplicationProgress");
                    if (replicationProgressSequenceElement != null) {
                        for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(replicationProgressSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "ReplicationProgressElement")
                                .size(); i1 = i1 + 1) {
                            org.w3c.dom.Element replicationProgressElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                    .getElementsByTagNameNS(replicationProgressSequenceElement,
                                            "http://schemas.microsoft.com/windowsazure",
                                            "ReplicationProgressElement")
                                    .get(i1));
                            VirtualMachineOSImageGetDetailsResponse.ReplicationProgressElement replicationProgressElementInstance = new VirtualMachineOSImageGetDetailsResponse.ReplicationProgressElement();
                            result.getReplicationProgress().add(replicationProgressElementInstance);

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

                            Element progressElement = XmlUtility.getElementByTagNameNS(replicationProgressElement,
                                    "http://schemas.microsoft.com/windowsazure", "Progress");
                            if (progressElement != null) {
                                String progressInstance;
                                progressInstance = progressElement.getTextContent();
                                replicationProgressElementInstance.setProgress(progressInstance);
                            }
                        }
                    }

                    Element computeImageAttributesElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "ComputeImageAttributes");
                    if (computeImageAttributesElement != null) {
                        ComputeImageAttributes computeImageAttributesInstance = new ComputeImageAttributes();
                        result.setComputeImageAttributes(computeImageAttributesInstance);

                        Element offerElement = XmlUtility.getElementByTagNameNS(computeImageAttributesElement,
                                "http://schemas.microsoft.com/windowsazure", "Offer");
                        if (offerElement != null) {
                            String offerInstance;
                            offerInstance = offerElement.getTextContent();
                            computeImageAttributesInstance.setOffer(offerInstance);
                        }

                        Element skuElement = XmlUtility.getElementByTagNameNS(computeImageAttributesElement,
                                "http://schemas.microsoft.com/windowsazure", "Sku");
                        if (skuElement != null) {
                            String skuInstance;
                            skuInstance = skuElement.getTextContent();
                            computeImageAttributesInstance.setSku(skuInstance);
                        }

                        Element versionElement = XmlUtility.getElementByTagNameNS(computeImageAttributesElement,
                                "http://schemas.microsoft.com/windowsazure", "Version");
                        if (versionElement != null) {
                            String versionInstance;
                            versionInstance = versionElement.getTextContent();
                            computeImageAttributesInstance.setVersion(versionInstance);
                        }
                    }

                    Element marketplaceImageAttributesElement = XmlUtility.getElementByTagNameNS(
                            oSImageDetailsElement, "http://schemas.microsoft.com/windowsazure",
                            "MarketplaceImageAttributes");
                    if (marketplaceImageAttributesElement != null) {
                        MarketplaceImageAttributes marketplaceImageAttributesInstance = new MarketplaceImageAttributes();
                        result.setMarketplaceImageAttributes(marketplaceImageAttributesInstance);

                        Element publisherIdElement = XmlUtility.getElementByTagNameNS(
                                marketplaceImageAttributesElement, "http://schemas.microsoft.com/windowsazure",
                                "PublisherId");
                        if (publisherIdElement != null) {
                            String publisherIdInstance;
                            publisherIdInstance = publisherIdElement.getTextContent();
                            marketplaceImageAttributesInstance.setPublisherId(publisherIdInstance);
                        }

                        Element planElement = XmlUtility.getElementByTagNameNS(marketplaceImageAttributesElement,
                                "http://schemas.microsoft.com/windowsazure", "Plan");
                        if (planElement != null) {
                            Plan planInstance = new Plan();
                            marketplaceImageAttributesInstance.setPlan(planInstance);

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

                            Element publisherElement = XmlUtility.getElementByTagNameNS(planElement,
                                    "http://schemas.microsoft.com/windowsazure", "Publisher");
                            if (publisherElement != null) {
                                String publisherInstance;
                                publisherInstance = publisherElement.getTextContent();
                                planInstance.setPublisher(publisherInstance);
                            }

                            Element productElement = XmlUtility.getElementByTagNameNS(planElement,
                                    "http://schemas.microsoft.com/windowsazure", "Product");
                            if (productElement != null) {
                                String productInstance;
                                productInstance = productElement.getTextContent();
                                planInstance.setProduct(productInstance);
                            }
                        }
                    }

                    Element affinityGroupElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "AffinityGroup");
                    if (affinityGroupElement != null) {
                        String affinityGroupInstance;
                        affinityGroupInstance = affinityGroupElement.getTextContent();
                        result.setAffinityGroup(affinityGroupInstance);
                    }

                    Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "Category");
                    if (categoryElement != null) {
                        String categoryInstance;
                        categoryInstance = categoryElement.getTextContent();
                        result.setCategory(categoryInstance);
                    }

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

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

                    Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                    if (logicalSizeInGBElement != null) {
                        double logicalSizeInGBInstance;
                        logicalSizeInGBInstance = DatatypeConverter
                                .parseDouble(logicalSizeInGBElement.getTextContent());
                        result.setLogicalSizeInGB(logicalSizeInGBInstance);
                    }

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

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

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

                    Element eulaElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement != null) {
                        String eulaInstance;
                        eulaInstance = eulaElement.getTextContent();
                        result.setEula(eulaInstance);
                    }

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

                    Element imageFamilyElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                    if (imageFamilyElement != null) {
                        String imageFamilyInstance;
                        imageFamilyInstance = imageFamilyElement.getTextContent();
                        result.setImageFamily(imageFamilyInstance);
                    }

                    Element showInGuiElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                    if (showInGuiElement != null && showInGuiElement.getTextContent() != null
                            && !showInGuiElement.getTextContent().isEmpty()) {
                        boolean showInGuiInstance;
                        showInGuiInstance = DatatypeConverter
                                .parseBoolean(showInGuiElement.getTextContent().toLowerCase());
                        result.setShowInGui(showInGuiInstance);
                    }

                    Element publishedDateElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement != null) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement.getTextContent());
                        result.setPublishedDate(publishedDateInstance);
                    }

                    Element isPremiumElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "IsPremium");
                    if (isPremiumElement != null && isPremiumElement.getTextContent() != null
                            && !isPremiumElement.getTextContent().isEmpty()) {
                        boolean isPremiumInstance;
                        isPremiumInstance = DatatypeConverter
                                .parseBoolean(isPremiumElement.getTextContent().toLowerCase());
                        result.setIsPremium(isPremiumInstance);
                    }

                    Element iconUriElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "IconUri");
                    if (iconUriElement != null) {
                        String iconUriInstance;
                        iconUriInstance = iconUriElement.getTextContent();
                        result.setIconUri(iconUriInstance);
                    }

                    Element privacyUriElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement.getTextContent());
                        result.setPrivacyUri(privacyUriInstance);
                    }

                    Element recommendedVMSizeElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                    if (recommendedVMSizeElement != null) {
                        String recommendedVMSizeInstance;
                        recommendedVMSizeInstance = recommendedVMSizeElement.getTextContent();
                        result.setRecommendedVMSize(recommendedVMSizeInstance);
                    }

                    Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "PublisherName");
                    if (publisherNameElement != null) {
                        String publisherNameInstance;
                        publisherNameInstance = publisherNameElement.getTextContent();
                        result.setPublisherName(publisherNameInstance);
                    }

                    Element smallIconUriElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                    if (smallIconUriElement != null) {
                        String smallIconUriInstance;
                        smallIconUriInstance = smallIconUriElement.getTextContent();
                        result.setSmallIconUri(smallIconUriInstance);
                    }

                    Element languageElement = XmlUtility.getElementByTagNameNS(oSImageDetailsElement,
                            "http://schemas.microsoft.com/windowsazure", "Language");
                    if (languageElement != null) {
                        String languageInstance;
                        languageInstance = languageElement.getTextContent();
                        result.setLanguage(languageInstance);
                    }

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

            }
            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 OS Images operation retrieves a list of the operating system
    * images from the image repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.aspx for
    * more information)
    *
    * @return The List OS Images operation response.
    */
    @Override
    public Future<VirtualMachineOSImageListResponse> listAsync() {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineOSImageListResponse>() {
            @Override
            public VirtualMachineOSImageListResponse call() throws Exception {
                return list();
            }
        });
    }

    /**
    * The List OS Images operation retrieves a list of the operating system
    * images from the image repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157191.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.
    * @throws URISyntaxException Thrown if there was an error parsing a URI in
    * the response.
    * @return The List OS Images operation response.
    */
    @Override
    public VirtualMachineOSImageListResponse list()
            throws IOException, ServiceException, ParserConfigurationException, SAXException, URISyntaxException {
        // Validate

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

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/images";
        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
            VirtualMachineOSImageListResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineOSImageListResponse();
                DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
                documentBuilderFactory.setNamespaceAware(true);
                DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
                Document responseDoc = documentBuilder.parse(new BOMInputStream(responseContent));

                Element imagesSequenceElement = XmlUtility.getElementByTagNameNS(responseDoc,
                        "http://schemas.microsoft.com/windowsazure", "Images");
                if (imagesSequenceElement != null) {
                    for (int i1 = 0; i1 < com.microsoft.windowsazure.core.utils.XmlUtility
                            .getElementsByTagNameNS(imagesSequenceElement,
                                    "http://schemas.microsoft.com/windowsazure", "OSImage")
                            .size(); i1 = i1 + 1) {
                        org.w3c.dom.Element imagesElement = ((org.w3c.dom.Element) com.microsoft.windowsazure.core.utils.XmlUtility
                                .getElementsByTagNameNS(imagesSequenceElement,
                                        "http://schemas.microsoft.com/windowsazure", "OSImage")
                                .get(i1));
                        VirtualMachineOSImageListResponse.VirtualMachineOSImage oSImageInstance = new VirtualMachineOSImageListResponse.VirtualMachineOSImage();
                        result.getImages().add(oSImageInstance);

                        Element affinityGroupElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "AffinityGroup");
                        if (affinityGroupElement != null) {
                            String affinityGroupInstance;
                            affinityGroupInstance = affinityGroupElement.getTextContent();
                            oSImageInstance.setAffinityGroup(affinityGroupInstance);
                        }

                        Element categoryElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "Category");
                        if (categoryElement != null) {
                            String categoryInstance;
                            categoryInstance = categoryElement.getTextContent();
                            oSImageInstance.setCategory(categoryInstance);
                        }

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

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

                        Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                        if (logicalSizeInGBElement != null) {
                            double logicalSizeInGBInstance;
                            logicalSizeInGBInstance = DatatypeConverter
                                    .parseDouble(logicalSizeInGBElement.getTextContent());
                            oSImageInstance.setLogicalSizeInGB(logicalSizeInGBInstance);
                        }

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

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

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

                        Element eulaElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "Eula");
                        if (eulaElement != null) {
                            String eulaInstance;
                            eulaInstance = eulaElement.getTextContent();
                            oSImageInstance.setEula(eulaInstance);
                        }

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

                        Element imageFamilyElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                        if (imageFamilyElement != null) {
                            String imageFamilyInstance;
                            imageFamilyInstance = imageFamilyElement.getTextContent();
                            oSImageInstance.setImageFamily(imageFamilyInstance);
                        }

                        Element showInGuiElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                        if (showInGuiElement != null && showInGuiElement.getTextContent() != null
                                && !showInGuiElement.getTextContent().isEmpty()) {
                            boolean showInGuiInstance;
                            showInGuiInstance = DatatypeConverter
                                    .parseBoolean(showInGuiElement.getTextContent().toLowerCase());
                            oSImageInstance.setShowInGui(showInGuiInstance);
                        }

                        Element publishedDateElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                        if (publishedDateElement != null) {
                            Calendar publishedDateInstance;
                            publishedDateInstance = DatatypeConverter
                                    .parseDateTime(publishedDateElement.getTextContent());
                            oSImageInstance.setPublishedDate(publishedDateInstance);
                        }

                        Element isPremiumElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "IsPremium");
                        if (isPremiumElement != null && isPremiumElement.getTextContent() != null
                                && !isPremiumElement.getTextContent().isEmpty()) {
                            boolean isPremiumInstance;
                            isPremiumInstance = DatatypeConverter
                                    .parseBoolean(isPremiumElement.getTextContent().toLowerCase());
                            oSImageInstance.setIsPremium(isPremiumInstance);
                        }

                        Element privacyUriElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                        if (privacyUriElement != null) {
                            URI privacyUriInstance;
                            privacyUriInstance = new URI(privacyUriElement.getTextContent());
                            oSImageInstance.setPrivacyUri(privacyUriInstance);
                        }

                        Element recommendedVMSizeElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                        if (recommendedVMSizeElement != null) {
                            String recommendedVMSizeInstance;
                            recommendedVMSizeInstance = recommendedVMSizeElement.getTextContent();
                            oSImageInstance.setRecommendedVMSize(recommendedVMSizeInstance);
                        }

                        Element publisherNameElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "PublisherName");
                        if (publisherNameElement != null) {
                            String publisherNameInstance;
                            publisherNameInstance = publisherNameElement.getTextContent();
                            oSImageInstance.setPublisherName(publisherNameInstance);
                        }

                        Element pricingDetailLinkElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "PricingDetailLink");
                        if (pricingDetailLinkElement != null) {
                            URI pricingDetailLinkInstance;
                            pricingDetailLinkInstance = new URI(pricingDetailLinkElement.getTextContent());
                            oSImageInstance.setPricingDetailUri(pricingDetailLinkInstance);
                        }

                        Element iconUriElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "IconUri");
                        if (iconUriElement != null) {
                            String iconUriInstance;
                            iconUriInstance = iconUriElement.getTextContent();
                            oSImageInstance.setIconUri(iconUriInstance);
                        }

                        Element smallIconUriElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                        if (smallIconUriElement != null) {
                            String smallIconUriInstance;
                            smallIconUriInstance = smallIconUriElement.getTextContent();
                            oSImageInstance.setSmallIconUri(smallIconUriInstance);
                        }

                        Element languageElement = XmlUtility.getElementByTagNameNS(imagesElement,
                                "http://schemas.microsoft.com/windowsazure", "Language");
                        if (languageElement != null) {
                            String languageInstance;
                            languageInstance = languageElement.getTextContent();
                            oSImageInstance.setLanguage(languageInstance);
                        }

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

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

    /**
    * Replicate an OS image to multiple target locations. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine OS image to
    * replicate.
    * @param parameters Required. Parameters supplied to the Replicate Virtual
    * Machine Image operation.
    * @return The response body contains the published name of the image.
    */
    @Override
    public Future<VirtualMachineOSImageReplicateResponse> replicateAsync(final String imageName,
            final VirtualMachineOSImageReplicateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineOSImageReplicateResponse>() {
            @Override
            public VirtualMachineOSImageReplicateResponse call() throws Exception {
                return replicate(imageName, parameters);
            }
        });
    }

    /**
    * Replicate an OS image to multiple target locations. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine OS image to
    * replicate.
    * @param parameters Required. Parameters supplied to the Replicate Virtual
    * Machine Image operation.
    * @throws ParserConfigurationException Thrown if there was an error
    * configuring the parser for the response body.
    * @throws SAXException Thrown if there was an error parsing the response
    * body.
    * @throws TransformerException Thrown if there was an error creating the
    * DOM transformer.
    * @throws IOException Signals that an I/O exception of some sort has
    * occurred. This class is the general class of exceptions produced by
    * failed or interrupted I/O operations.
    * @throws ServiceException Thrown if an unexpected response is found.
    * @return The response body contains the published name of the image.
    */
    @Override
    public VirtualMachineOSImageReplicateResponse replicate(String imageName,
            VirtualMachineOSImageReplicateParameters parameters)
            throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getComputeImageAttributes() == null) {
            throw new NullPointerException("parameters.ComputeImageAttributes");
        }
        if (parameters.getComputeImageAttributes().getOffer() == null) {
            throw new NullPointerException("parameters.ComputeImageAttributes.Offer");
        }
        if (parameters.getComputeImageAttributes().getSku() == null) {
            throw new NullPointerException("parameters.ComputeImageAttributes.Sku");
        }
        if (parameters.getComputeImageAttributes().getVersion() == null) {
            throw new NullPointerException("parameters.ComputeImageAttributes.Version");
        }
        if (parameters.getMarketplaceImageAttributes() != null) {
            if (parameters.getMarketplaceImageAttributes().getPlan() == null) {
                throw new NullPointerException("parameters.MarketplaceImageAttributes.Plan");
            }
            if (parameters.getMarketplaceImageAttributes().getPlan().getName() == null) {
                throw new NullPointerException("parameters.MarketplaceImageAttributes.Plan.Name");
            }
            if (parameters.getMarketplaceImageAttributes().getPlan().getProduct() == null) {
                throw new NullPointerException("parameters.MarketplaceImageAttributes.Plan.Product");
            }
            if (parameters.getMarketplaceImageAttributes().getPlan().getPublisher() == null) {
                throw new NullPointerException("parameters.MarketplaceImageAttributes.Plan.Publisher");
            }
            if (parameters.getMarketplaceImageAttributes().getPublisherId() == null) {
                throw new NullPointerException("parameters.MarketplaceImageAttributes.PublisherId");
            }
        }

        // 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("imageName", imageName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "replicateAsync", 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/images/";
        url = url + URLEncoder.encode(imageName, "UTF-8");
        url = url + "/replicate";
        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 replicationInputElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "ReplicationInput");
        requestDoc.appendChild(replicationInputElement);

        if (parameters.getTargetLocations() != null) {
            if (parameters.getTargetLocations() instanceof LazyCollection == false
                    || ((LazyCollection) parameters.getTargetLocations()).isInitialized()) {
                Element targetLocationsSequenceElement = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "TargetLocations");
                for (String targetLocationsItem : parameters.getTargetLocations()) {
                    Element targetLocationsItemElement = requestDoc
                            .createElementNS("http://schemas.microsoft.com/windowsazure", "Region");
                    targetLocationsItemElement.appendChild(requestDoc.createTextNode(targetLocationsItem));
                    targetLocationsSequenceElement.appendChild(targetLocationsItemElement);
                }
                replicationInputElement.appendChild(targetLocationsSequenceElement);
            }
        }

        Element computeImageAttributesElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "ComputeImageAttributes");
        replicationInputElement.appendChild(computeImageAttributesElement);

        Element offerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Offer");
        offerElement.appendChild(requestDoc.createTextNode(parameters.getComputeImageAttributes().getOffer()));
        computeImageAttributesElement.appendChild(offerElement);

        Element skuElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Sku");
        skuElement.appendChild(requestDoc.createTextNode(parameters.getComputeImageAttributes().getSku()));
        computeImageAttributesElement.appendChild(skuElement);

        Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Version");
        versionElement.appendChild(requestDoc.createTextNode(parameters.getComputeImageAttributes().getVersion()));
        computeImageAttributesElement.appendChild(versionElement);

        if (parameters.getMarketplaceImageAttributes() != null) {
            Element marketplaceImageAttributesElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "MarketplaceImageAttributes");
            replicationInputElement.appendChild(marketplaceImageAttributesElement);

            Element publisherIdElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "PublisherId");
            publisherIdElement.appendChild(
                    requestDoc.createTextNode(parameters.getMarketplaceImageAttributes().getPublisherId()));
            marketplaceImageAttributesElement.appendChild(publisherIdElement);

            Element planElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Plan");
            marketplaceImageAttributesElement.appendChild(planElement);

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

            Element publisherElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Publisher");
            publisherElement.appendChild(
                    requestDoc.createTextNode(parameters.getMarketplaceImageAttributes().getPlan().getPublisher()));
            planElement.appendChild(publisherElement);

            Element productElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Product");
            productElement.appendChild(
                    requestDoc.createTextNode(parameters.getMarketplaceImageAttributes().getPlan().getProduct()));
            planElement.appendChild(productElement);
        }

        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
            VirtualMachineOSImageReplicateResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineOSImageReplicateResponse();
                DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
                documentBuilderFactory2.setNamespaceAware(true);
                DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
                Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

                Element virtualMachineOSImageReplicateResponseElement = XmlUtility
                        .getElementByTagNameNS(responseDoc, "", "VirtualMachineOSImageReplicateResponse");
                if (virtualMachineOSImageReplicateResponseElement != null) {
                    Element stringElement = XmlUtility
                            .getElementByTagNameNS(virtualMachineOSImageReplicateResponseElement, "", "string");
                    if (stringElement != null) {
                    }
                }

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

    /**
    * Share an already replicated OS image. This operation is only for
    * publishers. You have to be registered as image publisher with Windows
    * Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine image to share.
    * @param permission Required. The sharing permission: public, msdn, or
    * private.
    * @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> shareAsync(final String imageName, final String permission) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return share(imageName, permission);
            }
        });
    }

    /**
    * Share an already replicated OS image. This operation is only for
    * publishers. You have to be registered as image publisher with Windows
    * Azure to be able to call this.
    *
    * @param imageName Required. The name of the virtual machine image to share.
    * @param permission Required. The sharing permission: public, msdn, or
    * private.
    * @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 share(String imageName, String permission)
            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("imageName", imageName);
            tracingParameters.put("permission", permission);
            CloudTracing.enter(invocationId, this, "shareAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachineOSImagesOperations()
                    .beginSharingAsync(imageName, permission).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();
            }
        }
    }

    /**
    * Unreplicate an OS image to multiple target locations. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this. Note: The operation removes the
    * published copies of the user OS Image. It does not remove the actual
    * user OS Image. To remove the actual user OS Image, the publisher will
    * have to call Delete OS Image.
    *
    * @param imageName Required. The name of the virtual machine image to
    * replicate. Note: The OS Image Name should be the user OS Image, not the
    * published name of the OS Image.
    * @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> unreplicateAsync(final String imageName) {
        return this.getClient().getExecutorService().submit(new Callable<OperationStatusResponse>() {
            @Override
            public OperationStatusResponse call() throws Exception {
                return unreplicate(imageName);
            }
        });
    }

    /**
    * Unreplicate an OS image to multiple target locations. This operation is
    * only for publishers. You have to be registered as image publisher with
    * Windows Azure to be able to call this. Note: The operation removes the
    * published copies of the user OS Image. It does not remove the actual
    * user OS Image. To remove the actual user OS Image, the publisher will
    * have to call Delete OS Image.
    *
    * @param imageName Required. The name of the virtual machine image to
    * replicate. Note: The OS Image Name should be the user OS Image, not the
    * published name of the OS Image.
    * @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 unreplicate(String imageName)
            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("imageName", imageName);
            CloudTracing.enter(invocationId, this, "unreplicateAsync", tracingParameters);
        }
        try {
            if (shouldTrace) {
                client2 = this.getClient().withRequestFilterLast(new ClientRequestTrackingHandler(invocationId))
                        .withResponseFilterLast(new ClientRequestTrackingHandler(invocationId));
            }

            OperationResponse response = client2.getVirtualMachineOSImagesOperations()
                    .beginUnreplicatingAsync(imageName).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 OS Image operation updates an OS image that in your image
    * repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for
    * more information)
    *
    * @param imageName Required. The name of the virtual machine image to be
    * updated.
    * @param parameters Required. Parameters supplied to the Update Virtual
    * Machine Image operation.
    * @return Parameters returned from the Create Virtual Machine Image
    * operation.
    */
    @Override
    public Future<VirtualMachineOSImageUpdateResponse> updateAsync(final String imageName,
            final VirtualMachineOSImageUpdateParameters parameters) {
        return this.getClient().getExecutorService().submit(new Callable<VirtualMachineOSImageUpdateResponse>() {
            @Override
            public VirtualMachineOSImageUpdateResponse call() throws Exception {
                return update(imageName, parameters);
            }
        });
    }

    /**
    * The Update OS Image operation updates an OS image that in your image
    * repository.  (see
    * http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for
    * more information)
    *
    * @param imageName Required. The name of the virtual machine image to be
    * updated.
    * @param parameters Required. Parameters supplied to the Update Virtual
    * Machine Image 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 Parameters returned from the Create Virtual Machine Image
    * operation.
    */
    @Override
    public VirtualMachineOSImageUpdateResponse update(String imageName,
            VirtualMachineOSImageUpdateParameters parameters)
            throws InterruptedException, ExecutionException, ServiceException, IOException,
            ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
        // Validate
        if (imageName == null) {
            throw new NullPointerException("imageName");
        }
        if (parameters == null) {
            throw new NullPointerException("parameters");
        }
        if (parameters.getLabel() == null) {
            throw new NullPointerException("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("imageName", imageName);
            tracingParameters.put("parameters", parameters);
            CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
        }

        // Construct URL
        String url = "";
        url = url + "/";
        if (this.getClient().getCredentials().getSubscriptionId() != null) {
            url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
        }
        url = url + "/services/images/";
        url = url + URLEncoder.encode(imageName, "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 oSImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSImage");
        requestDoc.appendChild(oSImageElement);

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

        if (parameters.getEula() != null) {
            Element eulaElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Eula");
            eulaElement.appendChild(requestDoc.createTextNode(parameters.getEula()));
            oSImageElement.appendChild(eulaElement);
        }

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

        if (parameters.getImageFamily() != null) {
            Element imageFamilyElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ImageFamily");
            imageFamilyElement.appendChild(requestDoc.createTextNode(parameters.getImageFamily()));
            oSImageElement.appendChild(imageFamilyElement);
        }

        if (parameters.isShowInGui() != null) {
            Element showInGuiElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "ShowInGui");
            showInGuiElement.appendChild(
                    requestDoc.createTextNode(Boolean.toString(parameters.isShowInGui()).toLowerCase()));
            oSImageElement.appendChild(showInGuiElement);
        }

        if (parameters.getPublishedDate() != null) {
            Element publishedDateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "PublishedDate");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSSSSS'Z'");
            simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
            publishedDateElement.appendChild(
                    requestDoc.createTextNode(simpleDateFormat.format(parameters.getPublishedDate().getTime())));
            oSImageElement.appendChild(publishedDateElement);
        }

        if (parameters.isPremium() != null) {
            Element isPremiumElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "IsPremium");
            isPremiumElement
                    .appendChild(requestDoc.createTextNode(Boolean.toString(parameters.isPremium()).toLowerCase()));
            oSImageElement.appendChild(isPremiumElement);
        }

        if (parameters.getPrivacyUri() != null) {
            Element privacyUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "PrivacyUri");
            privacyUriElement.appendChild(requestDoc.createTextNode(parameters.getPrivacyUri().toString()));
            oSImageElement.appendChild(privacyUriElement);
        }

        if (parameters.getIconUri() != null) {
            Element iconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "IconUri");
            iconUriElement.appendChild(requestDoc.createTextNode(parameters.getIconUri()));
            oSImageElement.appendChild(iconUriElement);
        }

        if (parameters.getRecommendedVMSize() != null) {
            Element recommendedVMSizeElement = requestDoc
                    .createElementNS("http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
            recommendedVMSizeElement.appendChild(requestDoc.createTextNode(parameters.getRecommendedVMSize()));
            oSImageElement.appendChild(recommendedVMSizeElement);
        }

        if (parameters.getSmallIconUri() != null) {
            Element smallIconUriElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SmallIconUri");
            smallIconUriElement.appendChild(requestDoc.createTextNode(parameters.getSmallIconUri()));
            oSImageElement.appendChild(smallIconUriElement);
        }

        if (parameters.getLanguage() != null) {
            Element languageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Language");
            languageElement.appendChild(requestDoc.createTextNode(parameters.getLanguage()));
            oSImageElement.appendChild(languageElement);
        }

        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
            VirtualMachineOSImageUpdateResponse result = null;
            // Deserialize Response
            if (statusCode == HttpStatus.SC_OK) {
                InputStream responseContent = httpResponse.getEntity().getContent();
                result = new VirtualMachineOSImageUpdateResponse();
                DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
                documentBuilderFactory2.setNamespaceAware(true);
                DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
                Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

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

                    Element categoryElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "Category");
                    if (categoryElement != null) {
                        String categoryInstance;
                        categoryInstance = categoryElement.getTextContent();
                        result.setCategory(categoryInstance);
                    }

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

                    Element logicalSizeInGBElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "LogicalSizeInGB");
                    if (logicalSizeInGBElement != null) {
                        double logicalSizeInGBInstance;
                        logicalSizeInGBInstance = DatatypeConverter
                                .parseDouble(logicalSizeInGBElement.getTextContent());
                        result.setLogicalSizeInGB(logicalSizeInGBInstance);
                    }

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

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

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

                    Element eulaElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "Eula");
                    if (eulaElement2 != null) {
                        String eulaInstance;
                        eulaInstance = eulaElement2.getTextContent();
                        result.setEula(eulaInstance);
                    }

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

                    Element imageFamilyElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "ImageFamily");
                    if (imageFamilyElement2 != null) {
                        String imageFamilyInstance;
                        imageFamilyInstance = imageFamilyElement2.getTextContent();
                        result.setImageFamily(imageFamilyInstance);
                    }

                    Element publishedDateElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "PublishedDate");
                    if (publishedDateElement2 != null && publishedDateElement2.getTextContent() != null
                            && !publishedDateElement2.getTextContent().isEmpty()) {
                        Calendar publishedDateInstance;
                        publishedDateInstance = DatatypeConverter
                                .parseDateTime(publishedDateElement2.getTextContent());
                        result.setPublishedDate(publishedDateInstance);
                    }

                    Element publisherNameElement = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "PublisherName");
                    if (publisherNameElement != null) {
                        String publisherNameInstance;
                        publisherNameInstance = publisherNameElement.getTextContent();
                        result.setPublisherName(publisherNameInstance);
                    }

                    Element isPremiumElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "IsPremium");
                    if (isPremiumElement2 != null && isPremiumElement2.getTextContent() != null
                            && !isPremiumElement2.getTextContent().isEmpty()) {
                        boolean isPremiumInstance;
                        isPremiumInstance = DatatypeConverter
                                .parseBoolean(isPremiumElement2.getTextContent().toLowerCase());
                        result.setIsPremium(isPremiumInstance);
                    }

                    Element showInGuiElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "ShowInGui");
                    if (showInGuiElement2 != null && showInGuiElement2.getTextContent() != null
                            && !showInGuiElement2.getTextContent().isEmpty()) {
                        boolean showInGuiInstance;
                        showInGuiInstance = DatatypeConverter
                                .parseBoolean(showInGuiElement2.getTextContent().toLowerCase());
                        result.setShowInGui(showInGuiInstance);
                    }

                    Element privacyUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "PrivacyUri");
                    if (privacyUriElement2 != null) {
                        URI privacyUriInstance;
                        privacyUriInstance = new URI(privacyUriElement2.getTextContent());
                        result.setPrivacyUri(privacyUriInstance);
                    }

                    Element iconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "IconUri");
                    if (iconUriElement2 != null) {
                        String iconUriInstance;
                        iconUriInstance = iconUriElement2.getTextContent();
                        result.setIconUri(iconUriInstance);
                    }

                    Element recommendedVMSizeElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "RecommendedVMSize");
                    if (recommendedVMSizeElement2 != null) {
                        String recommendedVMSizeInstance;
                        recommendedVMSizeInstance = recommendedVMSizeElement2.getTextContent();
                        result.setRecommendedVMSize(recommendedVMSizeInstance);
                    }

                    Element smallIconUriElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "SmallIconUri");
                    if (smallIconUriElement2 != null) {
                        String smallIconUriInstance;
                        smallIconUriInstance = smallIconUriElement2.getTextContent();
                        result.setSmallIconUri(smallIconUriInstance);
                    }

                    Element languageElement2 = XmlUtility.getElementByTagNameNS(oSImageElement2,
                            "http://schemas.microsoft.com/windowsazure", "Language");
                    if (languageElement2 != null) {
                        String languageInstance;
                        languageInstance = languageElement2.getTextContent();
                        result.setLanguage(languageInstance);
                    }

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

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