Example usage for org.w3c.dom Document createTextNode

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

Introduction

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

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveWatchlists() {
    try {//w w  w. ja  va  2s  . c  o  m
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();
        root.setAttribute("nextId", String.valueOf(watchlistsNextId)); //$NON-NLS-1$

        for (Iterator iter = watchlistsMap.values().iterator(); iter.hasNext();) {
            Watchlist watchlist = (Watchlist) iter.next();

            Element element = document.createElement("watchlist"); //$NON-NLS-1$
            element.setAttribute("id", String.valueOf(watchlist.getId())); //$NON-NLS-1$
            root.appendChild(element);

            Element node = document.createElement("title"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(watchlist.getDescription()));
            element.appendChild(node);
            node = document.createElement("style"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(watchlist.getStyle())));
            element.appendChild(node);
            if (watchlist.getCurrency() != null) {
                node = document.createElement("currency"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(watchlist.getCurrency().getCurrencyCode()));
                element.appendChild(node);
            }
            if (watchlist.getDefaultFeed() != null) {
                node = document.createElement("feed"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(watchlist.getDefaultFeed()));
                element.appendChild(node);
            }

            Element columnsNode = document.createElement("columns"); //$NON-NLS-1$
            element.appendChild(columnsNode);

            for (Iterator iter2 = watchlist.getColumns().iterator(); iter2.hasNext();) {
                WatchlistColumn column = (WatchlistColumn) iter2.next();

                Element columnNode = document.createElement("column"); //$NON-NLS-1$
                columnNode.setAttribute("id", column.getId()); //$NON-NLS-1$
                columnsNode.appendChild(columnNode);
            }

            Element itemsNode = document.createElement("items"); //$NON-NLS-1$
            element.appendChild(itemsNode);

            int itemIndex = 1;
            for (Iterator itemIter = watchlist.getItems().iterator(); itemIter.hasNext();) {
                WatchlistItem item = (WatchlistItem) itemIter.next();
                item.setId(new Integer(itemIndex++));
                item.setParent(watchlist);
                item.setRepository(this);

                Element itemNode = document.createElement("security"); //$NON-NLS-1$
                itemNode.setAttribute("id", String.valueOf(item.getSecurity().getId())); //$NON-NLS-1$
                itemsNode.appendChild(itemNode);

                if (item.getPosition() != null && item.getPosition().intValue() != 0) {
                    node = document.createElement("position"); //$NON-NLS-1$
                    node.appendChild(document.createTextNode(String.valueOf(item.getPosition())));
                    itemNode.appendChild(node);
                }
                if (item.getPaidPrice() != null && item.getPaidPrice().doubleValue() != 0) {
                    node = document.createElement("paid"); //$NON-NLS-1$
                    node.appendChild(document.createTextNode(String.valueOf(item.getPaidPrice())));
                    itemNode.appendChild(node);
                }

                int alertIndex = 1;
                for (Iterator alertIter = item.getAlerts().iterator(); alertIter.hasNext();) {
                    Alert alert = (Alert) alertIter.next();
                    alert.setId(new Integer(alertIndex++));

                    Element alertNode = document.createElement("alert"); //$NON-NLS-1$
                    alertNode.setAttribute("pluginId", alert.getPluginId()); //$NON-NLS-1$
                    if (alert.getLastSeen() != null)
                        alertNode.setAttribute("lastSeen", dateTimeFormat.format(alert.getLastSeen())); //$NON-NLS-1$
                    alertNode.setAttribute("popup", String.valueOf(alert.isPopup())); //$NON-NLS-1$
                    alertNode.setAttribute("hilight", String.valueOf(alert.isHilight())); //$NON-NLS-1$
                    itemNode.appendChild(alertNode);

                    for (Iterator paramIter = alert.getParameters().keySet().iterator(); paramIter.hasNext();) {
                        String key = (String) paramIter.next();

                        node = document.createElement("param"); //$NON-NLS-1$
                        node.setAttribute("key", key); //$NON-NLS-1$
                        node.appendChild(document.createTextNode((String) alert.getParameters().get(key)));
                        alertNode.appendChild(node);
                    }
                }
            }
        }

        saveDocument(document, "", "watchlists.xml"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

From source file:com.marklogic.client.functionaltest.TestBiTemporal.java

private DOMHandle getXMLDocumentHandle(String startValidTime, String endValidTime, String address, String uri)
        throws Exception {

    Document domDocument = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = domDocument.createElement("root");

    // System start and End time
    Node systemNode = root.appendChild(domDocument.createElement("system"));
    systemNode.appendChild(domDocument.createElement(systemStartERIName));
    systemNode.appendChild(domDocument.createElement(systemEndERIName));

    // Valid start and End time
    Node validNode = root.appendChild(domDocument.createElement("valid"));

    Node validStartNode = validNode.appendChild(domDocument.createElement(validStartERIName));
    validStartNode.appendChild(domDocument.createTextNode(startValidTime));
    validNode.appendChild(validStartNode);

    Node validEndNode = validNode.appendChild(domDocument.createElement(validEndERIName));
    validEndNode.appendChild(domDocument.createTextNode(endValidTime));
    validNode.appendChild(validEndNode);

    // Address/*from  w  w  w.j  a v  a  2s . c om*/
    Node addressNode = root.appendChild(domDocument.createElement("Address"));
    addressNode.appendChild(domDocument.createTextNode(address));

    // uri
    Node uriNode = root.appendChild(domDocument.createElement("uri"));
    uriNode.appendChild(domDocument.createTextNode(uri));
    domDocument.appendChild(root);

    String domString = ((DOMImplementationLS) DocumentBuilderFactory.newInstance().newDocumentBuilder()
            .getDOMImplementation()).createLSSerializer().writeToString(domDocument);

    System.out.println(domString);

    DOMHandle handle = new DOMHandle().with(domDocument);

    return handle;
}

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)/*from   ww w  .ja  v a2 s  .  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:net.sourceforge.eclipsetrader.core.internal.XMLRepository.java

private void saveOrders() {
    try {// w  ww .j av  a  2s.  c  om
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        builder.setErrorHandler(errorHandler);
        Document document = builder.getDOMImplementation().createDocument(null, "data", null); //$NON-NLS-1$

        Element root = document.getDocumentElement();
        root.setAttribute("nextId", String.valueOf(orderNextId)); //$NON-NLS-1$

        for (Iterator iter = allOrders().iterator(); iter.hasNext();) {
            Order order = (Order) iter.next();

            Element element = document.createElement("order"); //$NON-NLS-1$
            element.setAttribute("id", String.valueOf(order.getId())); //$NON-NLS-1$
            element.setAttribute("pluginId", order.getPluginId()); //$NON-NLS-1$
            element.setAttribute("security", String.valueOf(order.getSecurity().getId())); //$NON-NLS-1$
            root.appendChild(element);

            Element node = document.createElement("date"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(dateTimeFormat.format(order.getDate())));
            element.appendChild(node);
            if (order.getExchange() != null) {
                node = document.createElement("exchange"); //$NON-NLS-1$
                node.setAttribute("id", order.getExchange().getId()); //$NON-NLS-1$
                node.appendChild(document.createTextNode(order.getExchange().toString()));
                element.appendChild(node);
            }
            node = document.createElement("orderId"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(order.getOrderId()));
            element.appendChild(node);
            node = document.createElement("side"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getSide())));
            element.appendChild(node);
            node = document.createElement("type"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getType())));
            element.appendChild(node);
            node = document.createElement("quantity"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getQuantity())));
            element.appendChild(node);
            node = document.createElement("price"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getPrice())));
            element.appendChild(node);
            node = document.createElement("stopPrice"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getStopPrice())));
            element.appendChild(node);
            node = document.createElement("filledQuantity"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getFilledQuantity())));
            element.appendChild(node);
            node = document.createElement("averagePrice"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getAveragePrice())));
            element.appendChild(node);
            if (order.getValidity() != null) {
                node = document.createElement("validity"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(String.valueOf(order.getValidity())));
                element.appendChild(node);
            }
            node = document.createElement("status"); //$NON-NLS-1$
            node.appendChild(document.createTextNode(String.valueOf(order.getStatus())));
            element.appendChild(node);
            if (order.getAccount() != null) {
                node = document.createElement("account"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(String.valueOf(order.getAccount().getId())));
                element.appendChild(node);
            }
            if (order.getText() != null) {
                node = document.createElement("text"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(order.getText()));
                element.appendChild(node);
            }
            if (order.getMessage() != null) {
                node = document.createElement("message"); //$NON-NLS-1$
                node.appendChild(document.createTextNode(order.getMessage()));
                element.appendChild(node);
            }

            for (Iterator paramIter = order.getParams().keySet().iterator(); paramIter.hasNext();) {
                String key = (String) paramIter.next();
                node = document.createElement("param"); //$NON-NLS-1$
                node.setAttribute("key", key); //$NON-NLS-1$
                node.setAttribute("value", (String) order.getParams().get(key)); //$NON-NLS-1$
                element.appendChild(node);
            }
        }

        saveDocument(document, "", "orders.xml"); //$NON-NLS-1$ //$NON-NLS-2$

    } catch (Exception e) {
        log.error(e.toString(), e);
    }
}

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 w w  .  j a v  a2  s .  c  om
*
* @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 . jav a  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.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginUpdatingDisk(String name, VirtualMachineDiskUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // 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, "beginUpdatingDiskAsync", 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_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 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)//  w w w .j  a v  a2  s.co  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.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)/*w ww .  ja v  a2s  .  c  o  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.VirtualMachineVMImageOperationsImpl.java

/**
* The Update VM Image operation updates a VM image that in your image
* repository.//  w w w  .  jav a  2s  . c om
*
* @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.compute.VirtualMachineVMImageOperationsImpl.java

/**
* The Create VM Image operation creates a VM image that in your image
* repository.  (see/*from   w  w w  . j a  v  a2s  .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();
        }
    }
}