Example usage for org.w3c.dom Document createElementNS

List of usage examples for org.w3c.dom Document createElementNS

Introduction

In this page you can find the example usage for org.w3c.dom Document createElementNS.

Prototype

public Element createElementNS(String namespaceURI, String qualifiedName) throws DOMException;

Source Link

Document

Creates an element of the given qualified name and namespace URI.

Usage

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineDiskOperationsImpl.java

/**
* The Update Data Disk operation updates the specified data disk attached
* to the specified virtual machine.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157190.aspx for
* more information)//w w w  .  j  av a  2s. c  o  m
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of the deployment.
* @param roleName Required. The name of the role to add the data disk to.
* @param logicalUnitNumber Required. The logical unit number of the disk.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine Data Disk operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse updateDataDisk(String serviceName, String deploymentName, String roleName,
        int logicalUnitNumber, VirtualMachineDataDiskUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (roleName == null) {
        throw new NullPointerException("roleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getHostCaching() == null) {
        throw new NullPointerException("parameters.HostCaching");
    }
    if (parameters.getMediaLinkUri() == null) {
        throw new NullPointerException("parameters.MediaLinkUri");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roles/";
    url = url + URLEncoder.encode(roleName, "UTF-8");
    url = url + "/DataDisks/";
    url = url + URLEncoder.encode(Integer.toString(logicalUnitNumber), "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 dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "DataVirtualHardDisk");
    requestDoc.appendChild(dataVirtualHardDiskElement);

    Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "HostCaching");
    hostCachingElement.appendChild(requestDoc.createTextNode(parameters.getHostCaching()));
    dataVirtualHardDiskElement.appendChild(hostCachingElement);

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

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

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

    Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "LogicalDiskSizeInGB");
    logicalDiskSizeInGBElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogicalDiskSizeInGB())));
    dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement);

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineDiskOperationsImpl.java

/**
* The Create Data Disk operation adds a data disk to a virtual machine.
* There are three ways to create the data disk using the Add Data Disk
* operation. Option 1 - Attach an empty data disk to the role by
* specifying the disk label and location of the disk image. Do not include
* the DiskName and SourceMediaLink elements in the request body. Include
* the MediaLink element and reference a blob that is in the same
* geographical region as the role. You can also omit the MediaLink
* element. In this usage, Azure will create the data disk in the storage
* account configured as default for the role. Option 2 - Attach an
* existing data disk that is in the image repository. Do not include the
* DiskName and SourceMediaLink elements in the request body. Specify the
* data disk to use by including the DiskName element. Note: If included
* the in the response body, the MediaLink and LogicalDiskSizeInGB elements
* are ignored. Option 3 - Specify the location of a blob in your storage
* account that contain a disk image to use. Include the SourceMediaLink
* element. Note: If the MediaLink element isincluded, it is ignored.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157199.aspx for
* more information)/*from   w ww.  ja va 2  s.com*/
*
* @param serviceName Required. The name of your service.
* @param deploymentName Required. The name of the deployment.
* @param roleName Required. The name of the role to add the data disk to.
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Data Disk operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreatingDataDisk(String serviceName, String deploymentName, String roleName,
        VirtualMachineDataDiskCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (roleName == null) {
        throw new NullPointerException("roleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getHostCaching() == null) {
        throw new NullPointerException("parameters.HostCaching");
    }
    if (parameters.getMediaLinkUri() == null) {
        throw new NullPointerException("parameters.MediaLinkUri");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/hostedservices/";
    url = url + URLEncoder.encode(serviceName, "UTF-8");
    url = url + "/deployments/";
    url = url + URLEncoder.encode(deploymentName, "UTF-8");
    url = url + "/roles/";
    url = url + URLEncoder.encode(roleName, "UTF-8");
    url = url + "/DataDisks";
    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 dataVirtualHardDiskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "DataVirtualHardDisk");
    requestDoc.appendChild(dataVirtualHardDiskElement);

    Element hostCachingElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "HostCaching");
    hostCachingElement.appendChild(requestDoc.createTextNode(parameters.getHostCaching()));
    dataVirtualHardDiskElement.appendChild(hostCachingElement);

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

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

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

    Element logicalDiskSizeInGBElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "LogicalDiskSizeInGB");
    logicalDiskSizeInGBElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getLogicalDiskSizeInGB())));
    dataVirtualHardDiskElement.appendChild(logicalDiskSizeInGBElement);

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

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineDiskOperationsImpl.java

/**
* The Add Disk operation adds a disk to the user image repository. The disk
* can be an operating system disk or a data disk.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for
* more information)//from w  w  w .ja va  2s. co  m
*
* @param name Required. The name of the disk being updated.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine Disk 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return A virtual machine disk associated with your subscription.
*/
@Override
public VirtualMachineDiskUpdateResponse updateDisk(String name, VirtualMachineDiskUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (name == null) {
        throw new NullPointerException("name");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

    // Tracing
    boolean shouldTrace = CloudTracing.getIsEnabled();
    String invocationId = null;
    if (shouldTrace) {
        invocationId = Long.toString(CloudTracing.getNextInvocationId());
        HashMap<String, Object> tracingParameters = new HashMap<String, Object>();
        tracingParameters.put("name", name);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateDiskAsync", 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/disks/";
    url = url + URLEncoder.encode(name, "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 diskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Disk");
    requestDoc.appendChild(diskElement);

    if (parameters.isHasOperatingSystem() != null) {
        Element hasOperatingSystemElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "HasOperatingSystem");
        hasOperatingSystemElement.appendChild(
                requestDoc.createTextNode(Boolean.toString(parameters.isHasOperatingSystem()).toLowerCase()));
        diskElement.appendChild(hasOperatingSystemElement);
    }

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

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

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

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

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

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

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

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

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

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

                Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB");
                if (logicalDiskSizeInGBElement != null) {
                    int logicalDiskSizeInGBInstance;
                    logicalDiskSizeInGBInstance = DatatypeConverter
                            .parseInt(logicalDiskSizeInGBElement.getTextContent());
                    result.setLogicalSizeInGB(logicalDiskSizeInGBInstance);
                }

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

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

                Element isPremiumElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "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 iOTypeElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "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();
        }
    }
}

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineDiskOperationsImpl.java

/**
* The Create Disk operation adds a disk to the user image repository. The
* disk can be an operating system disk or a data disk.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157178.aspx for
* more information)/*from  ww w  . java 2 s.  c o m*/
*
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Disk 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.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return A virtual machine disk associated with your subscription.
*/
@Override
public VirtualMachineDiskCreateResponse createDisk(VirtualMachineDiskCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        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");
    }

    // 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, "createDiskAsync", 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/disks";
    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 diskElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Disk");
    requestDoc.appendChild(diskElement);

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

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

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

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

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

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

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

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

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

                Element logicalDiskSizeInGBElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "http://schemas.microsoft.com/windowsazure", "LogicalDiskSizeInGB");
                if (logicalDiskSizeInGBElement != null) {
                    int logicalDiskSizeInGBInstance;
                    logicalDiskSizeInGBInstance = DatatypeConverter
                            .parseInt(logicalDiskSizeInGBElement.getTextContent());
                    result.setLogicalSizeInGB(logicalDiskSizeInGBInstance);
                }

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

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

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

                Element attachedToElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "http://schemas.microsoft.com/windowsazure", "AttachedTo");
                if (attachedToElement != null) {
                    VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails attachedToInstance = new VirtualMachineDiskCreateResponse.VirtualMachineDiskUsageDetails();
                    result.setUsageDetails(attachedToInstance);

                    Element hostedServiceNameElement = XmlUtility.getElementByTagNameNS(attachedToElement,
                            "http://schemas.microsoft.com/windowsazure", "HostedServiceName");
                    if (hostedServiceNameElement != null) {
                        String hostedServiceNameInstance;
                        hostedServiceNameInstance = hostedServiceNameElement.getTextContent();
                        attachedToInstance.setHostedServiceName(hostedServiceNameInstance);
                    }

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

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

                Element isPremiumElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "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 iOTypeElement = XmlUtility.getElementByTagNameNS(diskElement2,
                        "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();
        }
    }
}

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineVMImageOperationsImpl.java

/**
* Replicate an VM 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 vmImageName Required. The name of the virtual machine image to
* replicate./*  ww  w  . ja  v  a 2  s  . com*/
* @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 VirtualMachineVMImageReplicateResponse replicate(String vmImageName,
        VirtualMachineVMImageReplicateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (vmImageName == null) {
        throw new NullPointerException("vmImageName");
    }
    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");
        }
    }
    if (parameters.getTargetLocations() == null) {
        throw new NullPointerException("parameters.TargetLocations");
    }

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

            Element virtualMachineVMImageReplicateResponseElement = XmlUtility
                    .getElementByTagNameNS(responseDoc, "", "VirtualMachineVMImageReplicateResponse");
            if (virtualMachineVMImageReplicateResponseElement != null) {
                Element stringElement = XmlUtility
                        .getElementByTagNameNS(virtualMachineVMImageReplicateResponseElement, "", "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();
        }
    }
}

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineOSImageOperationsImpl.java

/**
* 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./*from   w w w.j  a  va  2s.c om*/
* @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();
        }
    }
}

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineVMImageOperationsImpl.java

/**
* The Update VM Image operation updates a VM image that in your image
* repository./* w w  w .  j  a  v  a 2  s  .  c  o  m*/
*
* @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 A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse update(String imageName, VirtualMachineVMImageUpdateParameters 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/vmimages/";
    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 vMImageElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "VMImage");
    requestDoc.appendChild(vMImageElement);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    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())));
        vMImageElement.appendChild(publishedDateElement);
    }

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.network.RouteOperationsImpl.java

/**
* Create the specified route table for this subscription.
*
* @param parameters Required. The parameters necessary to create a new
* route table.// w ww. j  a  va2  s .c o  m
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreateRouteTable(CreateRouteTableParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

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

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

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

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.compute.VirtualMachineVMImageOperationsImpl.java

/**
* The Create VM Image operation creates a VM image that in your image
* repository.  (see/*from w w  w  . ja v a  2s . c  o m*/
* http://msdn.microsoft.com/en-us/library/azure/dn775054.aspx for more
* information)
*
* @param parameters Required. Parameters supplied to the virtual machine VM
* image create operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(VirtualMachineVMImageCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDataDiskConfigurations() != null) {
        for (DataDiskConfigurationCreateParameters dataDiskConfigurationsParameterItem : parameters
                .getDataDiskConfigurations()) {
            if (dataDiskConfigurationsParameterItem.getMediaLink() == null) {
                throw new NullPointerException("parameters.DataDiskConfigurations.MediaLink");
            }
        }
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getOSDiskConfiguration() == null) {
        throw new NullPointerException("parameters.OSDiskConfiguration");
    }
    if (parameters.getOSDiskConfiguration().getMediaLink() == null) {
        throw new NullPointerException("parameters.OSDiskConfiguration.MediaLink");
    }
    if (parameters.getOSDiskConfiguration().getOS() == null) {
        throw new NullPointerException("parameters.OSDiskConfiguration.OS");
    }
    if (parameters.getOSDiskConfiguration().getOSState() == null) {
        throw new NullPointerException("parameters.OSDiskConfiguration.OSState");
    }

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

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

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

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

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

    Element oSDiskConfigurationElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "OSDiskConfiguration");
    vMImageElement.appendChild(oSDiskConfigurationElement);

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

    Element oSStateElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "OSState");
    oSStateElement.appendChild(requestDoc.createTextNode(parameters.getOSDiskConfiguration().getOSState()));
    oSDiskConfigurationElement.appendChild(oSStateElement);

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

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

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

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

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

                Element mediaLinkElement2 = requestDoc
                        .createElementNS("http://schemas.microsoft.com/windowsazure", "MediaLink");
                mediaLinkElement2.appendChild(
                        requestDoc.createTextNode(dataDiskConfigurationsItem.getMediaLink().toString()));
                dataDiskConfigurationElement.appendChild(mediaLinkElement2);
            }
            vMImageElement.appendChild(dataDiskConfigurationsSequenceElement);
        }
    }

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

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

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

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

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

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

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

    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())));
        vMImageElement.appendChild(publishedDateElement);
    }

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.network.RouteOperationsImpl.java

/**
* Set the specified route table for the provided subnet in the provided
* virtual network in this subscription./*  w  w w .  ja v a  2s . c om*/
*
* @param vnetName Required. The name of the virtual network that contains
* the provided subnet.
* @param subnetName Required. The name of the subnet that the route table
* will be added to.
* @param parameters Required. The parameters necessary to add a route table
* to the provided subnet.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginAddRouteTableToSubnet(String vnetName, String subnetName,
        AddRouteTableToSubnetParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (vnetName == null) {
        throw new NullPointerException("vnetName");
    }
    if (subnetName == null) {
        throw new NullPointerException("subnetName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/networking/virtualnetwork/";
    url = url + URLEncoder.encode(vnetName, "UTF-8");
    url = url + "/subnets/";
    url = url + URLEncoder.encode(subnetName, "UTF-8");
    url = url + "/routetables";
    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 routeTableAssociationElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/windowsazure", "RouteTableAssociation");
    requestDoc.appendChild(routeTableAssociationElement);

    if (parameters.getRouteTableName() != null) {
        Element routeTableNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "RouteTableName");
        routeTableNameElement.appendChild(requestDoc.createTextNode(parameters.getRouteTableName()));
        routeTableAssociationElement.appendChild(routeTableNameElement);
    }

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

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

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

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