Example usage for org.w3c.dom Document appendChild

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

Introduction

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

Prototype

public Node appendChild(Node newChild) throws DOMException;

Source Link

Document

Adds the node newChild to the end of the list of children of this node.

Usage

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

/**
* Updates an internal load balancer associated with an existing deployment.
*
* @param serviceName Required. The name of the service.
* @param deploymentName Required. The name of the deployment.
* @param loadBalancerName Required. The name of the loadBalancer.
* @param parameters Required. Parameters supplied to the Update Load
* Balancer operation./*from  w  w  w.  j av  a  2  s.  c  om*/
* @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 status of the specified
* asynchronous operation, indicating whether it has succeeded, is
* inprogress, or has failed. Note that this status is distinct from the
* HTTP status code returned for the Get Operation Status operation itself.
* If the asynchronous operation succeeded, the response body includes the
* HTTP status code for the successful request. If the asynchronous
* operation failed, the response body includes the HTTP status code for
* the failed request and error information regarding the failure.
*/
@Override
public OperationStatusResponse beginUpdating(String serviceName, String deploymentName, String loadBalancerName,
        LoadBalancerUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serviceName == null) {
        throw new NullPointerException("serviceName");
    }
    if (deploymentName == null) {
        throw new NullPointerException("deploymentName");
    }
    if (loadBalancerName == null) {
        throw new NullPointerException("loadBalancerName");
    }
    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("serviceName", serviceName);
        tracingParameters.put("deploymentName", deploymentName);
        tracingParameters.put("loadBalancerName", loadBalancerName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginUpdatingAsync", 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 + "/loadbalancers/";
    url = url + URLEncoder.encode(loadBalancerName, "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 loadBalancerElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "LoadBalancer");
    requestDoc.appendChild(loadBalancerElement);

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

    if (parameters.getFrontendIPConfiguration() != null) {
        Element frontendIpConfigurationElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "FrontendIpConfiguration");
        loadBalancerElement.appendChild(frontendIpConfigurationElement);

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

        if (parameters.getFrontendIPConfiguration().getSubnetName() != null) {
            Element subnetNameElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                    "SubnetName");
            subnetNameElement.appendChild(
                    requestDoc.createTextNode(parameters.getFrontendIPConfiguration().getSubnetName()));
            frontendIpConfigurationElement.appendChild(subnetNameElement);
        }

        if (parameters.getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress() != null) {
            Element staticVirtualNetworkIPAddressElement = requestDoc.createElementNS(
                    "http://schemas.microsoft.com/windowsazure", "StaticVirtualNetworkIPAddress");
            staticVirtualNetworkIPAddressElement.appendChild(requestDoc.createTextNode(parameters
                    .getFrontendIPConfiguration().getStaticVirtualNetworkIPAddress().getHostAddress()));
            frontendIpConfigurationElement.appendChild(staticVirtualNetworkIPAddressElement);
        }
    }

    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
        OperationStatusResponse result = null;
        // Deserialize Response
        result = new OperationStatusResponse();
        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.github.lindenb.jvarkit.tools.ensembl.VcfEnsemblVepRest.java

@Override
protected Collection<Throwable> doVcfToVcf(final String inputName, final VcfIterator vcfIn,
        final VariantContextWriter out) throws IOException {
    final java.util.Base64.Encoder base64Encoder = java.util.Base64.getEncoder();
    final SequenceOntologyTree soTree = SequenceOntologyTree.getInstance();
    VCFHeader header = vcfIn.getHeader();
    List<VariantContext> buffer = new ArrayList<>(this.batchSize + 1);
    VCFHeader h2 = new VCFHeader(header);
    addMetaData(h2);//from   w ww  . j a  v  a  2  s  . co m

    if (!xmlBase64) {
        h2.addMetaDataLine(new VCFInfoHeaderLine(TAG, VCFHeaderLineCount.UNBOUNDED, VCFHeaderLineType.String,
                "VEP Transcript Consequences. Format :(biotype|cdnaStart|cdnaEnd|cdsStart|cdsEnd|geneId|geneSymbol|geneSymbolSource|hgnc|strand|transcript|variantAllele|so_acns)"));
    } else {
        h2.addMetaDataLine(
                new VCFInfoHeaderLine(TAG, 1, VCFHeaderLineType.String, "VEP xml answer encoded as base 64"));
    }

    out.writeHeader(h2);
    SAMSequenceDictionaryProgress progress = new SAMSequenceDictionaryProgress(header);
    for (;;) {
        VariantContext ctx = null;
        if (vcfIn.hasNext()) {
            buffer.add((ctx = progress.watch(vcfIn.next())));
        }
        if (ctx == null || buffer.size() >= this.batchSize) {
            if (!buffer.isEmpty()) {
                if (!xmlBase64) {
                    Opt opt = vep(buffer);
                    for (VariantContext ctx2 : buffer) {
                        VariantContextBuilder vcb = new VariantContextBuilder(ctx2);
                        final String inputStr = createInputContext(ctx2);
                        Data mydata = null;
                        for (Data data : opt.getData()) {
                            if (!inputStr.equals(data.getInput()))
                                continue;
                            mydata = data;
                            break;
                        }
                        if (mydata == null) {
                            LOG.info("No Annotation found for " + inputStr);
                            out.add(ctx2);
                            continue;
                        }
                        List<String> infoList = new ArrayList<>();
                        List<TranscriptConsequences> csql = mydata.getTranscriptConsequences();
                        for (int i = 0; i < csql.size(); ++i) {
                            TranscriptConsequences csq = csql.get(i);
                            StringBuilder sb = new StringBuilder();
                            sb.append(empty(csq.getBiotype())).append("|").append(empty(csq.getCdnaStart()))
                                    .append("|").append(empty(csq.getCdnaEnd())).append("|")
                                    .append(empty(csq.getCdsStart())).append("|").append(empty(csq.getCdsEnd()))
                                    .append("|").append(empty(csq.getGeneId())).append("|")
                                    .append(empty(csq.getGeneSymbol())).append("|")
                                    .append(empty(csq.getGeneSymbolSource())).append("|")
                                    .append(empty(csq.getHgncId())).append("|").append(empty(csq.getStrand()))
                                    .append("|").append(empty(csq.getTranscriptId())).append("|")
                                    .append(empty(csq.getVariantAllele())).append("|");
                            List<String> terms = csq.getConsequenceTerms();
                            for (int j = 0; j < terms.size(); ++j) {
                                if (j > 0)
                                    sb.append("&");
                                SequenceOntologyTree.Term term = soTree.getTermByLabel(terms.get(j));
                                if (term == null) {
                                    sb.append(terms.get(j));
                                    LOG.warn("No SO:Term found for " + terms.get(j));
                                } else {
                                    sb.append(term.getAcn());
                                }
                            }
                            infoList.add(sb.toString());
                        }
                        if (!infoList.isEmpty()) {
                            vcb.attribute(TAG, infoList);
                        }

                        out.add(vcb.make());
                    }
                } //end of not(XML base 64)
                else {
                    Document opt = vepxml(buffer);
                    Element root = opt.getDocumentElement();
                    if (!root.getNodeName().equals("opt"))
                        throw new IOException("Bad root node " + root.getNodeName());

                    for (VariantContext ctx2 : buffer) {
                        String inputStr = createInputContext(ctx2);
                        Document newdom = null;

                        //loop over <data/>
                        for (Node dataNode = root.getFirstChild(); dataNode != null; dataNode = dataNode
                                .getNextSibling()) {
                            if (dataNode.getNodeType() != Node.ELEMENT_NODE)
                                continue;
                            Attr att = Element.class.cast(dataNode).getAttributeNode("input");
                            if (att == null) {
                                LOG.warn("no @input in <data/>");
                                continue;
                            }

                            if (!att.getValue().equals(inputStr))
                                continue;
                            if (newdom == null) {
                                newdom = this.documentBuilder.newDocument();
                                newdom.appendChild(newdom.createElement("opt"));
                            }
                            newdom.getDocumentElement().appendChild(newdom.importNode(dataNode, true));
                        }
                        if (newdom == null) {
                            LOG.warn("No Annotation found for " + inputStr);
                            out.add(ctx2);
                            continue;
                        }
                        StringWriter sw = new StringWriter();
                        try {
                            this.xmlSerializer.transform(new DOMSource(newdom), new StreamResult(sw));
                        } catch (TransformerException err) {
                            throw new IOException(err);
                        }
                        VariantContextBuilder vcb = new VariantContextBuilder(ctx2);
                        vcb.attribute(TAG, base64Encoder.encodeToString(sw.toString().getBytes())
                                .replaceAll("[\\s=]", ""));
                        out.add(vcb.make());
                    }
                } //end of XML base 64
            }
            if (ctx == null)
                break;
            buffer.clear();
        }
        if (out.checkError())
            break;
    }
    progress.finish();
    return RETURN_OK;
}

From source file:com.aurel.track.admin.customize.category.report.execute.ReportBeansToLaTeXConverter.java

/**
 * Convert the result set into an XML structure.
 *
 * @param items/* ww  w .  j  a  v a  2  s  .c  om*/
 * @param withHistory
 * @param locale
 * @param personBean
 * @param filterName
 * @param filterExpression
 * @param useProjectSpecificID
 * @param outfileName
 * @return
 */
public Document convertToDOM(List<ReportBean> items, boolean withHistory, Locale locale, TPersonBean personBean,
        String filterName, String filterExpression, boolean useProjectSpecificID, String outfileName) {
    Document doc = null;

    try {

        DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

        // root elements
        doc = docBuilder.newDocument();
        Element rootElement = doc.createElement("pdfFile");
        doc.appendChild(rootElement);

        // set attribute to staff element
        Attr attr = doc.createAttribute("file");
        outfileName = outfileName.replace(".tex", ".pdf");
        attr.setValue(latexTmpDir + File.separator + outfileName);
        rootElement.setAttributeNode(attr);

    } catch (FactoryConfigurationError e) {
        LOGGER.error("Creating the DOM document failed with FactoryConfigurationError:" + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    } catch (ParserConfigurationException e) {
        LOGGER.error("Creating the DOM document failed with ParserConfigurationException: " + e.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(e));
        return null;
    }

    return doc;
}

From source file:com.microsoft.windowsazure.management.sql.FirewallRuleOperationsImpl.java

/**
* Adds a new server-level Firewall Rule for an Azure SQL Database Server.
*
* @param serverName Required. The name of the Azure SQL Database Server to
* which this rule will be applied.// www  .ja  va2 s .  co  m
* @param parameters Required. The parameters for the Create Firewall Rule
* 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 Contains the response to a Create Firewall Rule operation.
*/
@Override
public FirewallRuleCreateResponse create(String serverName, FirewallRuleCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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("serverName", serverName);
        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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/firewallrules";
    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", "2012-03-01");

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

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

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

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

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

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

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                FirewallRule serviceResourceInstance = new FirewallRule();
                result.setFirewallRule(serviceResourceInstance);

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        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.AffinityGroupOperationsImpl.java

/**
* The Update Affinity Group operation updates the label and/or the
* description for an affinity group for the specified subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715316.aspx for
* more information)//from   w w w  . j  a  v  a  2  s.c  o m
*
* @param affinityGroupName Required. The name of the affinity group.
* @param parameters Required. Parameters supplied to the Update Affinity
* Group operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse update(String affinityGroupName, AffinityGroupUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (affinityGroupName == null) {
        throw new NullPointerException("affinityGroupName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }

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

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

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

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

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

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

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

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

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

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

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

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

From source file:com.microsoft.windowsazure.management.sql.FirewallRuleOperationsImpl.java

/**
* Updates an existing server-level Firewall Rule for an Azure SQL Database
* Server.//w  w  w .ja  va 2 s.com
*
* @param serverName Required. The name of the Azure SQL Database Server
* that has the Firewall Rule to be updated.
* @param ruleName Required. The name of the Firewall Rule to be updated.
* @param parameters Required. The parameters for the Update Firewall Rule
* 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 Represents the firewall rule update response.
*/
@Override
public FirewallRuleUpdateResponse update(String serverName, String ruleName,
        FirewallRuleUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (ruleName == null) {
        throw new NullPointerException("ruleName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getEndIPAddress() == null) {
        throw new NullPointerException("parameters.EndIPAddress");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }
    if (parameters.getStartIPAddress() == null) {
        throw new NullPointerException("parameters.StartIPAddress");
    }

    // 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("serverName", serverName);
        tracingParameters.put("ruleName", ruleName);
        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/sqlservers/servers/";
    url = url + URLEncoder.encode(serverName, "UTF-8");
    url = url + "/firewallrules/";
    url = url + URLEncoder.encode(ruleName, "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", "2012-03-01");

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

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

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

    Element startIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "StartIPAddress");
    startIPAddressElement
            .appendChild(requestDoc.createTextNode(parameters.getStartIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(startIPAddressElement);

    Element endIPAddressElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "EndIPAddress");
    endIPAddressElement.appendChild(requestDoc.createTextNode(parameters.getEndIPAddress().getHostAddress()));
    serviceResourceElement.appendChild(endIPAddressElement);

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

            Element serviceResourceElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/windowsazure", "ServiceResource");
            if (serviceResourceElement2 != null) {
                FirewallRule serviceResourceInstance = new FirewallRule();
                result.setFirewallRule(serviceResourceInstance);

                Element startIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "StartIPAddress");
                if (startIPAddressElement2 != null) {
                    InetAddress startIPAddressInstance;
                    startIPAddressInstance = InetAddress.getByName(startIPAddressElement2.getTextContent());
                    serviceResourceInstance.setStartIPAddress(startIPAddressInstance);
                }

                Element endIPAddressElement2 = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "EndIPAddress");
                if (endIPAddressElement2 != null) {
                    InetAddress endIPAddressInstance;
                    endIPAddressInstance = InetAddress.getByName(endIPAddressElement2.getTextContent());
                    serviceResourceInstance.setEndIPAddress(endIPAddressInstance);
                }

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

                Element typeElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "Type");
                if (typeElement != null) {
                    String typeInstance;
                    typeInstance = typeElement.getTextContent();
                    serviceResourceInstance.setType(typeInstance);
                }

                Element stateElement = XmlUtility.getElementByTagNameNS(serviceResourceElement2,
                        "http://schemas.microsoft.com/windowsazure", "State");
                if (stateElement != null) {
                    String stateInstance;
                    stateInstance = stateElement.getTextContent();
                    serviceResourceInstance.setState(stateInstance);
                }
            }

        }
        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.hp.application.automation.tools.results.RunResultRecorder.java

private void writeReportMetaData2XML(List<ReportMetaData> htmlReportsInfo, String xmlFile,
        TaskListener _logger) {//from ww w .j  a  v a  2  s . co m

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        _logger.error("Failed creating xml doc report: " + e);
        return;
    }
    Document doc = builder.newDocument();
    Element root = doc.createElement("reports_data");
    doc.appendChild(root);

    for (ReportMetaData htmlReportInfo : htmlReportsInfo) {
        String disPlayName = htmlReportInfo.getDisPlayName();
        String urlName = htmlReportInfo.getUrlName();
        String resourceURL = htmlReportInfo.getResourceURL();
        String dateTime = htmlReportInfo.getDateTime();
        String status = htmlReportInfo.getStatus();
        String isHtmlReport = htmlReportInfo.getIsHtmlReport() ? "true" : "false";
        Element elmReport = doc.createElement(REPORT_NAME_FIELD);
        elmReport.setAttribute("disPlayName", disPlayName);
        elmReport.setAttribute("urlName", urlName);
        elmReport.setAttribute("resourceURL", resourceURL);
        elmReport.setAttribute("dateTime", dateTime);
        elmReport.setAttribute("status", status);
        elmReport.setAttribute("isHtmlreport", isHtmlReport);
        root.appendChild(elmReport);

    }

    try {
        write2XML(doc, xmlFile);
    } catch (TransformerException e) {
        _logger.error("Failed transforming xml file: " + e);
    } catch (FileNotFoundException e) {
        _logger.error("Failed to find " + xmlFile + ": " + e);
    }
}

From source file:com.photon.phresco.framework.rest.api.RepositoryService.java

private static Document constructGitTree(List<String> branchList, List<String> tagLists, String url,
        String appDirName) throws PhrescoException {
    try {//from  ww  w  .  j a va2 s. c o  m
        DocumentBuilderFactory documentFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentFactory.newDocumentBuilder();
        Document doc = documentBuilder.newDocument();

        Element rootElement = doc.createElement(ROOT);
        doc.appendChild(rootElement);

        Element rootItem = doc.createElement(ITEM);
        rootItem.setAttribute(TYPE, FOLDER);
        rootItem.setAttribute(NAME, ROOT_ITEM);

        rootElement.appendChild(rootItem);

        Element urlItem = doc.createElement(ITEM);
        urlItem.setAttribute(TYPE, FOLDER);
        urlItem.setAttribute(NAME, url);

        rootItem.appendChild(urlItem);

        Element branchItem = doc.createElement(ITEM);
        branchItem.setAttribute(TYPE, FOLDER);
        branchItem.setAttribute(NAME, BRANCHES);
        branchItem.setAttribute(URL, url);
        urlItem.appendChild(branchItem);

        for (String branch : branchList) {
            String branchName = branch.substring(branch.lastIndexOf("/") + 1, branch.length());
            Element branchItems = doc.createElement(ITEM);
            branchItems.setAttribute(TYPE, FILE);
            branchItems.setAttribute(NAME, branchName);
            branchItems.setAttribute(URL, url);
            branchItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            branchItems.setAttribute(NATURE, BRANCHES);
            branchItem.appendChild(branchItems);
        }

        Element tagItem = doc.createElement(ITEM);
        tagItem.setAttribute(TYPE, FOLDER);
        tagItem.setAttribute(NAME, TAGS);
        tagItem.setAttribute(URL, url);
        urlItem.appendChild(tagItem);

        for (String tag : tagLists) {
            Element tagItems = doc.createElement(ITEM);
            tagItems.setAttribute(TYPE, FILE);
            tagItems.setAttribute(NAME, tag);
            tagItems.setAttribute(URL, url);
            tagItems.setAttribute(REQ_APP_DIR_NAME, appDirName);
            tagItems.setAttribute(NATURE, TAGS);
            tagItem.appendChild(tagItems);
        }

        return doc;
    } catch (ParserConfigurationException e) {
        throw new PhrescoException(e);
    }
}

From source file:org.apache.cxf.cwiki.SiteExporter.java

private void checkVersion() throws ParserConfigurationException, IOException {
    Document doc = DOMUtils.createDocument();
    Element el = doc.createElementNS(SOAPNS, "ns1:getServerInfo");
    Element el2 = doc.createElement("in0");
    el.appendChild(el2);/*from w ww.  java  2 s.c  om*/
    el2.setTextContent(loginToken);
    doc.appendChild(el);

    doc = getDispatch().invoke(doc);
    el = DOMUtils.getFirstElement(DOMUtils.getFirstElement(doc.getDocumentElement()));
    while (el != null) {
        if ("majorVersion".equals(el.getLocalName())) {
            String major = DOMUtils.getContent(el);
            if (Integer.parseInt(major) >= 5) {
                apiVersion = 2;
                ((java.io.Closeable) dispatch).close();
                dispatch = null;
            }
        }

        el = DOMUtils.getNextElement(el);
    }
}

From source file:com.microsoft.windowsazure.management.AffinityGroupOperationsImpl.java

/**
* The Create Affinity Group operation creates a new affinity group for the
* specified subscription.  (see/*from   www  . java  2s .co m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/gg715317.aspx for
* more information)
*
* @param parameters Required. Parameters supplied to the Create Affinity
* Group operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse create(AffinityGroupCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() != null && parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getLabel() == null) {
        throw new NullPointerException("parameters.Label");
    }
    if (parameters.getLabel().length() > 100) {
        throw new IllegalArgumentException("parameters.Label");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }
    if (parameters.getName() == null) {
        throw new NullPointerException("parameters.Name");
    }

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

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

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

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

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

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

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

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

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

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

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

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

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

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