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:com.microsoft.windowsazure.management.network.RouteOperationsImpl.java

/**
* Set the specified route for the provided table in this subscription.
*
* @param routeTableName Required. The name of the route table where the
* provided route will be set./*from w  w w .  j  a va 2  s  . c  o m*/
* @param routeName Required. The name of the route that will be set on the
* provided route table.
* @param parameters Required. The parameters necessary to create a new
* route table.
* @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 beginSetRoute(String routeTableName, String routeName, SetRouteParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (routeTableName == null) {
        throw new NullPointerException("routeTableName");
    }
    if (routeName == null) {
        throw new NullPointerException("routeName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

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

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

    if (parameters.getAddressPrefix() != null) {
        Element addressPrefixElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "AddressPrefix");
        addressPrefixElement.appendChild(requestDoc.createTextNode(parameters.getAddressPrefix()));
        routeElement.appendChild(addressPrefixElement);
    }

    if (parameters.getNextHop() != null) {
        Element nextHopTypeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "NextHopType");
        routeElement.appendChild(nextHopTypeElement);

        if (parameters.getNextHop().getType() != null) {
            Element typeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "Type");
            typeElement.appendChild(requestDoc.createTextNode(parameters.getNextHop().getType()));
            nextHopTypeElement.appendChild(typeElement);
        }

        if (parameters.getNextHop().getIpAddress() != null) {
            Element ipAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "IpAddress");
            ipAddressElement.appendChild(requestDoc.createTextNode(parameters.getNextHop().getIpAddress()));
            nextHopTypeElement.appendChild(ipAddressElement);
        }
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* The Update OS Image operation updates an OS image that in your image
* repository.  (see// w w w . j  a va  2s.c  om
* http://msdn.microsoft.com/en-us/library/windowsazure/jj157198.aspx for
* more information)
*
* @param imageName Required. The name of the virtual machine image to be
* updated.
* @param parameters Required. Parameters supplied to the Update Virtual
* Machine Image operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Parameters returned from the Create Virtual Machine Image
* operation.
*/
@Override
public VirtualMachineOSImageUpdateResponse update(String imageName,
        VirtualMachineOSImageUpdateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
    // Validate
    if (imageName == null) {
        throw new NullPointerException("imageName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Create Result
        VirtualMachineOSImageUpdateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineOSImageUpdateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

/**
* The Create OS Image operation adds an operating system image that is
* stored in a storage account and is available from the image repository.
* (see http://msdn.microsoft.com/en-us/library/windowsazure/jj157192.aspx
* for more information)/*  w w w. ja  v  a2 s .  c om*/
*
* @param parameters Required. Parameters supplied to the Create Virtual
* Machine Image operation.
* @throws InterruptedException Thrown when a thread is waiting, sleeping,
* or otherwise occupied, and the thread is interrupted, either before or
* during the activity. Occasionally a method may wish to test whether the
* current thread has been interrupted, and if so, to immediately throw
* this exception. The following code can be used to achieve this effect:
* @throws ExecutionException Thrown when attempting to retrieve the result
* of a task that aborted by throwing an exception. This exception can be
* inspected using the Throwable.getCause() method.
* @throws ServiceException Thrown if the server returned an error for the
* request.
* @throws IOException Thrown if there was an error setting up tracing for
* the request.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return Parameters returned from the Create Virtual Machine Image
* operation.
*/
@Override
public VirtualMachineOSImageCreateResponse create(VirtualMachineOSImageCreateParameters parameters)
        throws InterruptedException, ExecutionException, ServiceException, IOException,
        ParserConfigurationException, SAXException, TransformerException, URISyntaxException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getMediaLinkUri() == null) {
        throw new NullPointerException("parameters.MediaLinkUri");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getOperatingSystemType() == null) {
        throw new NullPointerException("parameters.OperatingSystemType");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Create Result
        VirtualMachineOSImageCreateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineOSImageCreateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.ext.portlet.epsos.EpsosHelperService.java

public static void fixNode(Document dom, XPath xpath, String path, String nodeName, String value) {
    try {//from  w  w w. j a  v  a 2s .c o m
        XPathExpression salRO = xpath.compile(path + "/" + nodeName);
        NodeList salRONodes = (NodeList) salRO.evaluate(dom, XPathConstants.NODESET);
        if (salRONodes.getLength() == 0) {
            XPathExpression salAddr = xpath.compile(path);
            NodeList salAddrNodes = (NodeList) salAddr.evaluate(dom, XPathConstants.NODESET);
            if (salAddrNodes.getLength() > 0) {
                for (int t = 0; t < salAddrNodes.getLength(); t++) {
                    Node AddrNode = salAddrNodes.item(t);
                    Node city = dom.createElement(nodeName);
                    Text cityValue = dom.createTextNode(value);
                    city.appendChild(cityValue);
                    AddrNode.appendChild(city);
                }
            }
        }
    } catch (Exception e) {
        _log.error("Error fixing node ...");
    }
}

From source file:at.ac.dbisinformatik.snowprofile.web.svgcreator.SVGCreator.java

/**
 * creates a SVG-Graph for given jsonDocument which includes ExtJS-SVG-Objects. The created SVG-Document will be converted in the given export type. 
 * /*from   w ww  .j a  va 2  s  . c  o m*/
 * @param jsonDocument
 * @param exportType
 * @param profileID
 * @return
 * @throws TransformerException
 * @throws URISyntaxException
 * @throws TranscoderException
 * @throws IOException
 */
public static ByteArrayOutputStream svgDocument(JsonArray jsonDocument, String exportType, String profileID)
        throws TransformerException, URISyntaxException, TranscoderException, IOException {

    ByteArrayOutputStream ret = null;

    DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
    String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
    Document doc = impl.createDocument(svgNS, "svg", null);

    // Get the root element (the 'svg' element).
    Element svgRoot = doc.getDocumentElement();

    // Set the width and height attributes on the root 'svg' element.
    svgRoot.setAttributeNS(null, "width", "1500");
    svgRoot.setAttributeNS(null, "height", "1500");
    JsonArray items = jsonDocument;

    for (int i = 0; i < items.size(); ++i) {
        String type = items.get(i).getAsJsonObject().get("type").getAsString();
        Element element = null;
        org.w3c.dom.Text test = null;
        String path = "";
        String width = "";
        String height = "";
        String x = "";
        String y = "";
        String fill = "";
        String text = "";
        String font = "";
        String fontFamily = "";
        String fontSize = "";
        String degrees = "";
        String stroke = "";
        String opacity = "";
        String src = "";
        switch (type) {
        case "rect":
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();
            opacity = items.get(i).getAsJsonObject().get("opacity").getAsString();

            // Create the rectangle.
            element = doc.createElementNS(svgNS, "rect");
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            element.setAttributeNS(null, "opacity", opacity);
            break;

        case "path":
            path = items.get(i).getAsJsonObject().get("path").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            stroke = items.get(i).getAsJsonObject().get("stroke").getAsString();

            // Create the path.
            element = doc.createElementNS(svgNS, "path");
            element.setAttributeNS(null, "d", path);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "stroke", stroke);
            break;

        case "image":
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();
            width = items.get(i).getAsJsonObject().get("width").getAsString();
            height = items.get(i).getAsJsonObject().get("height").getAsString();
            src = System.class.getResource("/at/ac/dbisinformatik/snowprofile/web/resources/"
                    + items.get(i).getAsJsonObject().get("src").getAsString()).toString();

            // Create the path.
            element = doc.createElementNS(svgNS, "image");
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            element.setAttributeNS(null, "width", width);
            element.setAttributeNS(null, "height", height);
            element.setAttributeNS(null, "xlink:href", src);
            break;

        case "text":
            text = items.get(i).getAsJsonObject().get("text").getAsString();
            fill = items.get(i).getAsJsonObject().get("fill").getAsString();
            font = items.get(i).getAsJsonObject().get("font").getAsString();
            x = items.get(i).getAsJsonObject().get("x").getAsString();
            y = items.get(i).getAsJsonObject().get("y").getAsString();

            // Transformation
            if (items.get(i).getAsJsonObject().get("rotate") != null) {
                JsonObject temp = items.get(i).getAsJsonObject().get("rotate").getAsJsonObject();
                degrees = temp.get("degrees").getAsString();
            }

            fontSize = font.split(" ")[0];
            fontFamily = font.split(" ")[1];

            // Create the text.
            test = doc.createTextNode(text);
            element = doc.createElementNS(svgNS, "text");
            element.setAttributeNS(null, "text", text);
            element.setAttributeNS(null, "fill", fill);
            element.setAttributeNS(null, "font-family", fontFamily);
            element.setAttributeNS(null, "font-size", fontSize);
            element.setAttributeNS(null, "x", x);
            element.setAttributeNS(null, "y", y);
            if (!degrees.equals("")) {
                // element.setAttributeNS(null, "transform",
                // "rotate(270 "+500+","+80+")");
            }
            element.appendChild(test);
            break;

        default:
            break;
        }

        // Attach the rectangle to the root 'svg' element.
        svgRoot.appendChild(element);
    }

    TransformerFactory tFactory = TransformerFactory.newInstance();
    Transformer transformer = tFactory.newTransformer();

    DOMSource source = new DOMSource(doc);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult result = new StreamResult(outputStream);
    transformer.transform(source, result);
    InputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());

    switch (exportType) {
    case "png":
        ret = createPNG(inputStream);
        break;

    case "jpg":
        ret = createJPG(inputStream);
        break;

    case "pdf":
        ret = createPDF(inputStream);
        break;

    default:
        break;
    }
    return ret;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        // Create Result
        VirtualMachineVMImageReplicateResponse result = null;
        // Deserialize Response
        if (statusCode == HttpStatus.SC_OK) {
            InputStream responseContent = httpResponse.getEntity().getContent();
            result = new VirtualMachineVMImageReplicateResponse();
            DocumentBuilderFactory documentBuilderFactory2 = DocumentBuilderFactory.newInstance();
            documentBuilderFactory2.setNamespaceAware(true);
            DocumentBuilder documentBuilder2 = documentBuilderFactory2.newDocumentBuilder();
            Document responseDoc = documentBuilder2.parse(new BOMInputStream(responseContent));

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

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

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

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

private static void jsonToXml(Object object, String objectKey, Element parentElement, boolean modifyElement,
        boolean includeDataType, boolean compactArray, String arrayChildrenTag) throws JSONException {
    Engine.logBeans.trace("Converting JSON to XML: object=" + object + "; objectKey=\"" + objectKey + "\"");

    Document doc = parentElement.getOwnerDocument();

    if ("_attachments".equals(parentElement.getNodeName()) && "item".equals(arrayChildrenTag)
            && object instanceof JSONObject) {
        // special case when retrieving attachments with Couch : attachment name is the object key
        ((JSONObject) object).put("name", objectKey);
        objectKey = "attachment";
    }//w w w .  ja  v a 2s  . c  om

    // Normalize object key
    String originalObjectKey = objectKey;
    if (objectKey != null) {
        objectKey = StringUtils.normalize(objectKey);
    }

    // JSON object value case
    if (object instanceof JSONObject) {
        JSONObject json = (JSONObject) object;

        Element element = doc.createElement(objectKey == null ? "object" : objectKey);
        if (objectKey != null && !objectKey.equals(originalObjectKey)) {
            element.setAttribute("originalKeyName", originalObjectKey);
        }

        if (compactArray || modifyElement) {
            if (objectKey == null) {
                element = parentElement;
            } else {
                parentElement.appendChild(element);
            }
        } else {
            parentElement.appendChild(element);
        }

        if (includeDataType) {
            element.setAttribute("type", "object");
        }

        String[] keys = new String[json.length()];

        int index = 0;
        for (Iterator<String> i = GenericUtils.cast(json.keys()); i.hasNext();) {
            keys[index++] = i.next();
        }

        Arrays.sort(keys);

        for (String key : keys) {
            jsonToXml(json.get(key), key, element, false, includeDataType, compactArray, arrayChildrenTag);
        }
    }
    // Array value case
    else if (object instanceof JSONArray) {
        JSONArray array = (JSONArray) object;
        int len = array.length();

        Element arrayElement = parentElement;
        String arrayItemObjectKey = arrayChildrenTag;
        if (!(compactArray || modifyElement)) {
            arrayElement = doc.createElement(objectKey == null ? "array" : objectKey);
            if (objectKey != null && !objectKey.equals(originalObjectKey)) {
                arrayElement.setAttribute("originalKeyName", originalObjectKey);
            }
            parentElement.appendChild(arrayElement);

            if (includeDataType) {
                arrayElement.setAttribute("type", "array");
                arrayElement.setAttribute("length", "" + len);
            }
        } else if (objectKey != null) {
            arrayItemObjectKey = objectKey;
        }

        for (int i = 0; i < len; i++) {
            Object itemArray = array.get(i);
            jsonToXml(itemArray, arrayItemObjectKey, arrayElement, false, includeDataType, compactArray,
                    arrayChildrenTag);
        }
    } else {
        Element element = doc.createElement(objectKey == null ? "value" : objectKey);
        if (objectKey != null && !objectKey.equals(originalObjectKey)) {
            element.setAttribute("originalKeyName", originalObjectKey);
        }

        parentElement.appendChild(element);

        if (JSONObject.NULL.equals(object)) {
            object = null;
        }

        if (object != null) {
            Text text = doc.createTextNode(object.toString());
            element.appendChild(text);
        }

        if (includeDataType) {
            String objectType = object == null ? "null" : object.getClass().getCanonicalName();
            if (objectType.startsWith("java.lang.")) {
                objectType = objectType.substring(10);
            }
            element.setAttribute("type", objectType.toLowerCase());
        }
    }

}