Example usage for org.w3c.dom Document createElementNS

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

Introduction

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

Prototype

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

Source Link

Document

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

Usage

From source file:de.qucosa.webapi.v1.DocumentResource.java

private void modifyDcDatastream(String pid, List<String> urns, String title)
        throws FedoraClientException, ParserConfigurationException, IOException, SAXException,
        TransformerException, XPathExpressionException {
    if ((urns == null || urns.isEmpty()) && (title == null || title.isEmpty()))
        return;/*from   w  ww.java  2 s .c o m*/

    InputStream dcStream = fedoraRepository.getDatastreamContent(pid, "DC");
    Document dcDocument = documentBuilder.parse(dcStream);

    if (urns != null) {
        for (String urnnbn : urns) {
            String urn = urnnbn.trim().toLowerCase();
            if (!(boolean) xPath.compile("//ns:identifier[text()='" + urn + "']").evaluate(dcDocument,
                    XPathConstants.BOOLEAN)) {
                Element newDcIdentifier = dcDocument.createElementNS("http://purl.org/dc/elements/1.1/",
                        "identifier");
                newDcIdentifier.setTextContent(urn);
                dcDocument.getDocumentElement().appendChild(newDcIdentifier);
            }
        }
    }

    if ((title != null) && (!title.isEmpty())) {
        Element dcTitle = (Element) dcDocument
                .getElementsByTagNameNS("http://purl.org/dc/elements/1.1/", "title").item(0);
        dcTitle.setTextContent(title);
    }

    InputStream modifiedDcStream = IOUtils.toInputStream(DOMSerializer.toString(dcDocument));
    fedoraRepository.modifyDatastreamContent(pid, "DC", "text/xml", modifiedDcStream);
}

From source file:be.fedict.eid.applet.service.signer.facets.XAdESXLSignatureFacet.java

public void postSign(Element signatureElement, List<X509Certificate> signingCertificateChain) {
    LOG.debug("XAdES-X-L post sign phase");
    for (X509Certificate xCert : signingCertificateChain) {
        LOG.debug("Cert chain: " + xCert.getSubjectX500Principal());
    }//from   w  w w. j av a2 s.com

    // check for XAdES-BES
    Element qualifyingPropertiesElement = (Element) findSingleNode(signatureElement,
            "ds:Object/xades:QualifyingProperties");
    if (null == qualifyingPropertiesElement) {
        throw new IllegalArgumentException("no XAdES-BES extension present");
    }

    // create basic XML container structure
    Document document = signatureElement.getOwnerDocument();
    String xadesNamespacePrefix;
    if (null != qualifyingPropertiesElement.getPrefix()) {
        xadesNamespacePrefix = qualifyingPropertiesElement.getPrefix() + ":";
    } else {
        xadesNamespacePrefix = "";
    }
    Element unsignedPropertiesElement = (Element) findSingleNode(qualifyingPropertiesElement,
            "xades:UnsignedProperties");
    if (null == unsignedPropertiesElement) {
        unsignedPropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedProperties");
        qualifyingPropertiesElement.appendChild(unsignedPropertiesElement);
    }
    Element unsignedSignaturePropertiesElement = (Element) findSingleNode(unsignedPropertiesElement,
            "xades:UnsignedSignatureProperties");
    if (null == unsignedSignaturePropertiesElement) {
        unsignedSignaturePropertiesElement = document.createElementNS(XADES_NAMESPACE,
                xadesNamespacePrefix + "UnsignedSignatureProperties");
        unsignedPropertiesElement.appendChild(unsignedSignaturePropertiesElement);
    }

    // create the XAdES-T time-stamp
    Node signatureValueNode = findSingleNode(signatureElement, "ds:SignatureValue");
    RevocationData tsaRevocationDataXadesT = new RevocationData();
    LOG.debug("creating XAdES-T time-stamp");
    XAdESTimeStampType signatureTimeStamp = createXAdESTimeStamp(Collections.singletonList(signatureValueNode),
            tsaRevocationDataXadesT, this.c14nAlgoId, this.timeStampService, this.objectFactory,
            this.xmldsigObjectFactory);

    // marshal the XAdES-T extension
    try {
        this.marshaller.marshal(this.objectFactory.createSignatureTimeStamp(signatureTimeStamp),
                unsignedSignaturePropertiesElement);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // xadesv141::TimeStampValidationData
    if (tsaRevocationDataXadesT.hasRevocationDataEntries()) {
        ValidationDataType validationData = createValidationData(tsaRevocationDataXadesT);
        try {
            this.marshaller.marshal(this.xades141ObjectFactory.createTimeStampValidationData(validationData),
                    unsignedSignaturePropertiesElement);
        } catch (JAXBException e) {
            throw new RuntimeException("JAXB error: " + e.getMessage(), e);
        }
    }

    if (null == this.revocationDataService) {
        /*
         * Without revocation data service we cannot construct the XAdES-C
         * extension.
         */
        return;
    }

    // XAdES-C: complete certificate refs
    CompleteCertificateRefsType completeCertificateRefs = this.objectFactory
            .createCompleteCertificateRefsType();
    CertIDListType certIdList = this.objectFactory.createCertIDListType();
    completeCertificateRefs.setCertRefs(certIdList);
    List<CertIDType> certIds = certIdList.getCert();
    for (int certIdx = 1; certIdx < signingCertificateChain.size(); certIdx++) {
        /*
         * We skip the signing certificate itself according to section
         * 4.4.3.2 of the XAdES 1.4.1 specification.
         */
        X509Certificate certificate = signingCertificateChain.get(certIdx);
        CertIDType certId = XAdESSignatureFacet.getCertID(certificate, this.objectFactory,
                this.xmldsigObjectFactory, this.digestAlgorithm, false);
        certIds.add(certId);
    }

    // XAdES-C: complete revocation refs
    CompleteRevocationRefsType completeRevocationRefs = this.objectFactory.createCompleteRevocationRefsType();
    RevocationData revocationData = this.revocationDataService.getRevocationData(signingCertificateChain);
    if (revocationData.hasCRLs()) {
        CRLRefsType crlRefs = this.objectFactory.createCRLRefsType();
        completeRevocationRefs.setCRLRefs(crlRefs);
        List<CRLRefType> crlRefList = crlRefs.getCRLRef();

        List<byte[]> crls = revocationData.getCRLs();
        for (byte[] encodedCrl : crls) {
            CRLRefType crlRef = this.objectFactory.createCRLRefType();
            crlRefList.add(crlRef);
            X509CRL crl;
            try {
                crl = (X509CRL) this.certificateFactory.generateCRL(new ByteArrayInputStream(encodedCrl));
            } catch (CRLException e) {
                throw new RuntimeException("CRL parse error: " + e.getMessage(), e);
            }

            CRLIdentifierType crlIdentifier = this.objectFactory.createCRLIdentifierType();
            crlRef.setCRLIdentifier(crlIdentifier);
            String issuerName;
            try {
                issuerName = PrincipalUtil.getIssuerX509Principal(crl).getName().replace(",", ", ");
            } catch (CRLException e) {
                throw new RuntimeException("CRL encoding error: " + e.getMessage(), e);
            }
            crlIdentifier.setIssuer(issuerName);
            crlIdentifier.setIssueTime(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(crl.getThisUpdate()).toGregorianCalendar()));
            crlIdentifier.setNumber(getCrlNumber(crl));

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(encodedCrl,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            crlRef.setDigestAlgAndValue(digestAlgAndValue);
        }
    }
    if (revocationData.hasOCSPs()) {
        OCSPRefsType ocspRefs = this.objectFactory.createOCSPRefsType();
        completeRevocationRefs.setOCSPRefs(ocspRefs);
        List<OCSPRefType> ocspRefList = ocspRefs.getOCSPRef();
        List<byte[]> ocsps = revocationData.getOCSPs();
        for (byte[] ocsp : ocsps) {
            OCSPRefType ocspRef = this.objectFactory.createOCSPRefType();
            ocspRefList.add(ocspRef);

            DigestAlgAndValueType digestAlgAndValue = XAdESSignatureFacet.getDigestAlgAndValue(ocsp,
                    this.objectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
            ocspRef.setDigestAlgAndValue(digestAlgAndValue);

            OCSPIdentifierType ocspIdentifier = this.objectFactory.createOCSPIdentifierType();
            ocspRef.setOCSPIdentifier(ocspIdentifier);
            OCSPResp ocspResp;
            try {
                ocspResp = new OCSPResp(ocsp);
            } catch (IOException e) {
                throw new RuntimeException("OCSP decoding error: " + e.getMessage(), e);
            }
            Object ocspResponseObject;
            try {
                ocspResponseObject = ocspResp.getResponseObject();
            } catch (OCSPException e) {
                throw new RuntimeException("OCSP error: " + e.getMessage(), e);
            }
            BasicOCSPResp basicOcspResp = (BasicOCSPResp) ocspResponseObject;
            Date producedAt = basicOcspResp.getProducedAt();
            ocspIdentifier.setProducedAt(this.datatypeFactory
                    .newXMLGregorianCalendar(new DateTime(producedAt).toGregorianCalendar()));

            ResponderIDType responderId = this.objectFactory.createResponderIDType();
            ocspIdentifier.setResponderID(responderId);
            RespID respId = basicOcspResp.getResponderId();
            ResponderID ocspResponderId = respId.toASN1Object();
            DERTaggedObject derTaggedObject = (DERTaggedObject) ocspResponderId.toASN1Object();
            if (2 == derTaggedObject.getTagNo()) {
                ASN1OctetString keyHashOctetString = (ASN1OctetString) derTaggedObject.getObject();
                responderId.setByKey(keyHashOctetString.getOctets());
            } else {
                X509Name name = X509Name.getInstance(derTaggedObject.getObject());
                responderId.setByName(name.toString());
            }
        }
    }

    // marshal XAdES-C
    NodeList unsignedSignaturePropertiesNodeList = ((Element) qualifyingPropertiesElement)
            .getElementsByTagNameNS(XADES_NAMESPACE, "UnsignedSignatureProperties");
    Node unsignedSignaturePropertiesNode = unsignedSignaturePropertiesNodeList.item(0);
    try {
        this.marshaller.marshal(this.objectFactory.createCompleteCertificateRefs(completeCertificateRefs),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createCompleteRevocationRefs(completeRevocationRefs),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X Type 1 timestamp
    List<Node> timeStampNodesXadesX1 = new LinkedList<Node>();
    timeStampNodesXadesX1.add(signatureValueNode);
    Node signatureTimeStampNode = findSingleNode(unsignedSignaturePropertiesNode, "xades:SignatureTimeStamp");
    timeStampNodesXadesX1.add(signatureTimeStampNode);
    Node completeCertificateRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteCertificateRefs");
    timeStampNodesXadesX1.add(completeCertificateRefsNode);
    Node completeRevocationRefsNode = findSingleNode(unsignedSignaturePropertiesNode,
            "xades:CompleteRevocationRefs");
    timeStampNodesXadesX1.add(completeRevocationRefsNode);

    RevocationData tsaRevocationDataXadesX1 = new RevocationData();
    LOG.debug("creating XAdES-X time-stamp");
    XAdESTimeStampType timeStampXadesX1 = createXAdESTimeStamp(timeStampNodesXadesX1, tsaRevocationDataXadesX1,
            this.c14nAlgoId, this.timeStampService, this.objectFactory, this.xmldsigObjectFactory);
    ValidationDataType timeStampXadesX1ValidationData;
    if (tsaRevocationDataXadesX1.hasRevocationDataEntries()) {
        timeStampXadesX1ValidationData = createValidationData(tsaRevocationDataXadesX1);
    } else {
        timeStampXadesX1ValidationData = null;
    }

    // marshal XAdES-X
    try {
        this.marshaller.marshal(this.objectFactory.createSigAndRefsTimeStamp(timeStampXadesX1),
                unsignedSignaturePropertiesNode);
        if (null != timeStampXadesX1ValidationData) {
            this.marshaller.marshal(
                    this.xades141ObjectFactory.createTimeStampValidationData(timeStampXadesX1ValidationData),
                    unsignedSignaturePropertiesNode);
        }
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    // XAdES-X-L
    CertificateValuesType certificateValues = this.objectFactory.createCertificateValuesType();
    List<Object> certificateValuesList = certificateValues.getEncapsulatedX509CertificateOrOtherCertificate();
    for (X509Certificate certificate : signingCertificateChain) {
        EncapsulatedPKIDataType encapsulatedPKIDataType = this.objectFactory.createEncapsulatedPKIDataType();
        try {
            encapsulatedPKIDataType.setValue(certificate.getEncoded());
        } catch (CertificateEncodingException e) {
            throw new RuntimeException("certificate encoding error: " + e.getMessage(), e);
        }
        certificateValuesList.add(encapsulatedPKIDataType);
    }
    RevocationValuesType revocationValues = createRevocationValues(revocationData);

    // marshal XAdES-X-L
    try {
        this.marshaller.marshal(this.objectFactory.createCertificateValues(certificateValues),
                unsignedSignaturePropertiesNode);
        this.marshaller.marshal(this.objectFactory.createRevocationValues(revocationValues),
                unsignedSignaturePropertiesNode);
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }
}

From source file:be.docarch.odt2braille.PEF.java

/**
 * maxPages: -1 = infinity/*from w  w  w.j a  v a2s  .c om*/
 */
private int addPagesToSection(Document document, Element sectionElement, File brailleFile, int maxRows,
        int maxCols, int maxPages) throws IOException, Exception {

    int pageCount = 0;

    FileInputStream fileInputStream = new FileInputStream(brailleFile);
    InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream, "UTF-8");
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

    Element pageElement;
    Element rowElement;
    Node textNode;
    String line;

    boolean nextPage = bufferedReader.ready() && (maxPages > pageCount || maxPages == -1);

    try {
        while (nextPage) {
            pageElement = document.createElementNS(pefNS, "page");
            for (int i = 0; i < maxRows; i++) {
                line = bufferedReader.readLine();
                if (line == null) {
                    throw new Exception("number of rows < " + maxRows);
                }
                line = line.replaceAll("\u2800", "\u0020").replaceAll("\u00A0", "\u0020")
                        .replaceAll("\uE00F", "\u002D").replaceAll("\uE000", "\u0020");
                if (line.length() > maxCols) {
                    throw new Exception("line length > " + maxCols);
                }
                rowElement = document.createElementNS(pefNS, "row");
                textNode = document.createTextNode(liblouisTable.toBraille(line));
                rowElement.appendChild(textNode);
                pageElement.appendChild(rowElement);
                if (IS_WINDOWS) {
                    bufferedReader.readLine();
                }
            }

            sectionElement.appendChild(pageElement);
            pageCount++;
            if (bufferedReader.read() != '\f') {
                throw new Exception("unexpected character, should be form feed");
            }
            nextPage = nextPage = bufferedReader.ready() && (maxPages > pageCount || maxPages == -1);
        }

    } finally {
        if (bufferedReader != null) {
            bufferedReader.close();
            inputStreamReader.close();
            fileInputStream.close();
        }
    }

    return pageCount;
}

From source file:com.microsoft.windowsazure.management.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see/*from  w w w  .  j  a  v a  2  s.c om*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Create Server Farm
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Create Server Farm operation response.
*/
@Override
public ServerFarmCreateResponse create(String webSpaceName, ServerFarmCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "createAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms";
    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;

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

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

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

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

    if (parameters.getCurrentNumberOfWorkers() != null) {
        Element currentNumberOfWorkersElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
        currentNumberOfWorkersElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers())));
        serverFarmElement.appendChild(currentNumberOfWorkersElement);
    }

    if (parameters.getCurrentWorkerSize() != null) {
        Element currentWorkerSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
        currentWorkerSizeElement
                .appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString()));
        serverFarmElement.appendChild(currentWorkerSizeElement);
    }

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

    Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "NumberOfWorkers");
    numberOfWorkersElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
    serverFarmElement.appendChild(numberOfWorkersElement);

    Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WorkerSize");
    workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
    serverFarmElement.appendChild(workerSizeElement);

    if (parameters.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Status");
        statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
        serverFarmElement.appendChild(statusElement);
    }

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

        Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarm");
        if (serverFarmElement2 != null) {
            Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement2 != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement2.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

            Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
            if (currentWorkerSizeElement2 != null) {
                ServerFarmWorkerSize currentWorkerSizeInstance;
                currentWorkerSizeInstance = ServerFarmWorkerSize
                        .valueOf(currentWorkerSizeElement2.getTextContent());
                result.setCurrentWorkerSize(currentWorkerSizeInstance);
            }

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

            Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
            if (numberOfWorkersElement2 != null) {
                int numberOfWorkersInstance;
                numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent());
                result.setNumberOfWorkers(numberOfWorkersInstance);
            }

            Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "WorkerSize");
            if (workerSizeElement2 != null) {
                ServerFarmWorkerSize workerSizeInstance;
                workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent());
                result.setWorkerSize(workerSizeInstance);
            }

            Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Status");
            if (statusElement2 != null) {
                ServerFarmStatus statusInstance;
                statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent());
                result.setStatus(statusInstance);
            }
        }

        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.websites.ServerFarmOperationsImpl.java

/**
* You can create a server farm by issuing an HTTP POST request. Only one
* server farm per webspace is permitted. You can retrieve server farm
* details by using HTTP GET, change server farm properties by using HTTP
* PUT, and delete a server farm by using HTTP DELETE. A request body is
* required for server farm creation (HTTP POST) and server farm update
* (HTTP PUT). Warning: Creating a server farm changes your webspace's
* Compute Mode from Shared to Dedicated. You will be charged from the
* moment the server farm is created, even if all your sites are still
* running in Free mode.  (see/*from  ww w.j a v a  2s  .c  o  m*/
* http://msdn.microsoft.com/en-us/library/windowsazure/dn194277.aspx for
* more information)
*
* @param webSpaceName Required. The name of the web space.
* @param parameters Required. Parameters supplied to the Update Server Farm
* operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @throws URISyntaxException Thrown if there was an error parsing a URI in
* the response.
* @return The Update Server Farm operation response.
*/
@Override
public ServerFarmUpdateResponse update(String webSpaceName, ServerFarmUpdateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException,
        URISyntaxException {
    // Validate
    if (webSpaceName == null) {
        throw new NullPointerException("webSpaceName");
    }
    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("webSpaceName", webSpaceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "updateAsync", tracingParameters);
    }

    // Construct URL
    String url = "/" + (this.getClient().getCredentials().getSubscriptionId() != null
            ? this.getClient().getCredentials().getSubscriptionId().trim()
            : "") + "/services/WebSpaces/" + webSpaceName.trim() + "/ServerFarms/DefaultServerFarm";
    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;

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

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

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

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

    if (parameters.getCurrentNumberOfWorkers() != null) {
        Element currentNumberOfWorkersElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
        currentNumberOfWorkersElement.appendChild(
                requestDoc.createTextNode(Integer.toString(parameters.getCurrentNumberOfWorkers())));
        serverFarmElement.appendChild(currentNumberOfWorkersElement);
    }

    if (parameters.getCurrentWorkerSize() != null) {
        Element currentWorkerSizeElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
        currentWorkerSizeElement
                .appendChild(requestDoc.createTextNode(parameters.getCurrentWorkerSize().toString()));
        serverFarmElement.appendChild(currentWorkerSizeElement);
    }

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

    Element numberOfWorkersElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "NumberOfWorkers");
    numberOfWorkersElement
            .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getNumberOfWorkers())));
    serverFarmElement.appendChild(numberOfWorkersElement);

    Element workerSizeElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "WorkerSize");
    workerSizeElement.appendChild(requestDoc.createTextNode(parameters.getWorkerSize().toString()));
    serverFarmElement.appendChild(workerSizeElement);

    if (parameters.getStatus() != null) {
        Element statusElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
                "Status");
        statusElement.appendChild(requestDoc.createTextNode(parameters.getStatus().toString()));
        serverFarmElement.appendChild(statusElement);
    }

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

        Element serverFarmElement2 = XmlUtility.getElementByTagNameNS(responseDoc,
                "http://schemas.microsoft.com/windowsazure", "ServerFarm");
        if (serverFarmElement2 != null) {
            Element currentNumberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentNumberOfWorkers");
            if (currentNumberOfWorkersElement2 != null) {
                int currentNumberOfWorkersInstance;
                currentNumberOfWorkersInstance = DatatypeConverter
                        .parseInt(currentNumberOfWorkersElement2.getTextContent());
                result.setCurrentNumberOfWorkers(currentNumberOfWorkersInstance);
            }

            Element currentWorkerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "CurrentWorkerSize");
            if (currentWorkerSizeElement2 != null) {
                ServerFarmWorkerSize currentWorkerSizeInstance;
                currentWorkerSizeInstance = ServerFarmWorkerSize
                        .valueOf(currentWorkerSizeElement2.getTextContent());
                result.setCurrentWorkerSize(currentWorkerSizeInstance);
            }

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

            Element numberOfWorkersElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "NumberOfWorkers");
            if (numberOfWorkersElement2 != null) {
                int numberOfWorkersInstance;
                numberOfWorkersInstance = DatatypeConverter.parseInt(numberOfWorkersElement2.getTextContent());
                result.setNumberOfWorkers(numberOfWorkersInstance);
            }

            Element workerSizeElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "WorkerSize");
            if (workerSizeElement2 != null) {
                ServerFarmWorkerSize workerSizeInstance;
                workerSizeInstance = ServerFarmWorkerSize.valueOf(workerSizeElement2.getTextContent());
                result.setWorkerSize(workerSizeInstance);
            }

            Element statusElement2 = XmlUtility.getElementByTagNameNS(serverFarmElement2,
                    "http://schemas.microsoft.com/windowsazure", "Status");
            if (statusElement2 != null) {
                ServerFarmStatus statusInstance;
                statusInstance = ServerFarmStatus.valueOf(statusElement2.getTextContent());
                result.setStatus(statusInstance);
            }
        }

        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.scheduler.CloudServiceOperationsImpl.java

/**
* Create a cloud service.//from   w  ww  .  ja  va  2s  .  co m
*
* @param cloudServiceName Required. The cloud service name.
* @param parameters Required. Parameters supplied to the Create cloud
* service operation.
* @throws ParserConfigurationException Thrown if there was an error
* configuring the parser for the response body.
* @throws SAXException Thrown if there was an error parsing the response
* body.
* @throws TransformerException Thrown if there was an error creating the
* DOM transformer.
* @throws IOException Signals that an I/O exception of some sort has
* occurred. This class is the general class of exceptions produced by
* failed or interrupted I/O operations.
* @throws ServiceException Thrown if an unexpected response is found.
* @return A standard service response including an HTTP status code and
* request ID.
*/
@Override
public OperationResponse beginCreating(String cloudServiceName, CloudServiceCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (cloudServiceName == null) {
        throw new NullPointerException("cloudServiceName");
    }
    if (cloudServiceName.length() > 100) {
        throw new IllegalArgumentException("cloudServiceName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getDescription() == null) {
        throw new NullPointerException("parameters.Description");
    }
    if (parameters.getDescription().length() > 1024) {
        throw new IllegalArgumentException("parameters.Description");
    }
    if (parameters.getGeoRegion() == null) {
        throw new NullPointerException("parameters.GeoRegion");
    }
    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("cloudServiceName", cloudServiceName);
        tracingParameters.put("parameters", parameters);
        CloudTracing.enter(invocationId, this, "beginCreatingAsync", tracingParameters);
    }

    // Construct URL
    String url = "";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/CloudServices/";
    url = url + URLEncoder.encode(cloudServiceName, "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", "2013-03-01");

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

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

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

    Element descriptionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "Description");
    descriptionElement.appendChild(requestDoc.createTextNode(parameters.getDescription()));
    cloudServiceElement.appendChild(descriptionElement);

    Element geoRegionElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure",
            "GeoRegion");
    geoRegionElement.appendChild(requestDoc.createTextNode(parameters.getGeoRegion()));
    cloudServiceElement.appendChild(geoRegionElement);

    if (parameters.getEmail() != null) {
        Element emailElement = requestDoc.createElementNS("http://schemas.microsoft.com/windowsazure", "Email");
        emailElement.appendChild(requestDoc.createTextNode(parameters.getEmail()));
        cloudServiceElement.appendChild(emailElement);
    }

    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.collabnet.tracker.core.PTrackerWebServicesClient.java

public ClientArtifactListXMLHelper createOrUpdateArtifactList(Document doc, List<ClientArtifact> artifacts,
        Long lastReadOn) throws Exception {
    EngineConfiguration config = mClient.getEngineConfiguration();
    DispatcherService service = new DispatcherServiceLocator(config);
    URL portAddress = mClient.constructServiceURL("/ws/Dispatcher");
    Dispatcher theService = service.getDispatcher(portAddress);
    Element root = doc.getDocumentElement();

    Element artifactListNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "artifactList");
    root.appendChild(artifactListNode);/*ww w.j a v a  2 s.co m*/

    // TODO: Move all the below code to clientArtifact.java?

    HashMap<String, Integer> nameSpaces = new HashMap<String, Integer>();
    //List<String> nameSpaces = new ArrayList<String>();
    int nameSpaceCount = 1;
    nameSpaces.put(DEFAULT_NAMESPACE, nameSpaceCount);

    for (int i = 0; i < artifacts.size(); i++) {
        ClientArtifact ca = artifacts.get(i);
        String nsXNameSpace = ca.getNamespace();
        String artifactType = ca.getTagName();
        //int nsCtr;
        // check if the namespace alrady exists in the xml so far
        if (nameSpaces.get(nsXNameSpace) == null) {
            nameSpaces.put(nsXNameSpace, ++nameSpaceCount);
        }

        String nsNumberString = "ns" + nameSpaces.get(nsXNameSpace) + ":";

        Element artifactNode = doc.createElementNS(nsXNameSpace, nsNumberString + artifactType);
        artifactListNode.appendChild(artifactNode);

        Element modByNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + MODIFIED_BY_FIELD_NAME);
        modByNode.appendChild(doc.createTextNode(mClient.getUserName()));
        artifactNode.appendChild(modByNode);
        if (lastReadOn != null) {
            Element lastReadNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + LAST_READ_ON_FIELD_NAME);
            lastReadNode.appendChild(doc.createTextNode(Long.toString(lastReadOn)));
            artifactNode.appendChild(lastReadNode);
        } else {
            Element lastReadNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + LAST_READ_ON_FIELD_NAME);
            lastReadNode.appendChild(doc.createTextNode(Long.toString(new Date().getTime())));
            artifactNode.appendChild(lastReadNode);
        }

        // Add each attribute
        Map<String, List<String>> textAttributes = ca.getAttributes();

        for (Map.Entry<String, List<String>> attributeEntry : textAttributes.entrySet()) {
            String attribute = attributeEntry.getKey();
            List<String> values = attributeEntry.getValue();

            // strip the namespace from the attribute key
            String[] parts = attribute.substring(1).split("\\}");
            String attributeNamespace = parts[0];
            attribute = parts[1];
            if (nameSpaces.get(attributeNamespace) == null) {
                nameSpaces.put(attributeNamespace, ++nameSpaceCount);
            }
            nsNumberString = "ns" + nameSpaces.get(attributeNamespace) + ":";
            Element attributeNode = doc.createElementNS(attributeNamespace, nsNumberString + attribute);
            if (values.size() > 1 || (attributeNamespace.equals(DEFAULT_NAMESPACE) && attribute.equals("id"))) {
                for (String value : values) {
                    if (!(StringUtils.isEmpty(value))) {

                        Element valueNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:value");
                        //valueNode.setNodeValue(value);
                        value = TrackerUtil.removeInvalidXmlCharacters(value);
                        valueNode.appendChild(doc.createTextNode(value));
                        attributeNode.appendChild(valueNode);
                    }
                }
            } else {
                // TODO: consider the namespace of the attributes?
                //attributeNode.setNodeValue(values.get(0));
                String value = values.get(0);
                value = TrackerUtil.removeInvalidXmlCharacters(value);
                if (value == null)
                    value = "";
                attributeNode.appendChild(doc.createTextNode(value));
            }
            artifactNode.appendChild(attributeNode);
        }
        List<ClientArtifactComment> comments = ca.getComments();
        for (ClientArtifactComment comment : comments) {
            String commentText = comment.getCommentText();
            Element commentNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:" + "comment");
            Element textNode = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "text");
            commentText = TrackerUtil.removeInvalidXmlCharacters(commentText);
            textNode.appendChild(doc.createTextNode(commentText));
            commentNode.appendChild(textNode);
            artifactNode.appendChild(commentNode);
        }

        //            Element reasonNode = doc.createElementNS("urn:ws.tracker.collabnet.com", "ns1:"+"reason");
        //            reasonNode.appendChild(doc.createTextNode("Synchronized by Connector"));
        //            artifactNode.appendChild(reasonNode);
    } // for every artifact

    Element sendMail = doc.createElementNS(DEFAULT_NAMESPACE, "ns1:" + "sendEmail");
    sendMail.appendChild(doc.createTextNode("true"));
    root.appendChild(sendMail);

    if (log.isDebugEnabled())
        this.printDocument(doc);

    Response r = theService.execute(toRequest(doc));
    Document result = toDocument(r);
    if (log.isDebugEnabled())
        this.printDocument(result);
    ClientArtifactListXMLHelper helper = new ClientArtifactListXMLHelper(result);
    return helper;
}

From source file:com.sap.research.roo.addon.nwcloud.NWCloudOperationsImpl.java

/**
 * This is the command "nwcloud enable-jpa". It will configure the JPA persistence layer in a
 * way that will use the HANA Cloud persistence service.
 *///from w ww .  j  av  a  2 s  .co m
public void nwcloudEnableJPA() {

    // TODO
    // One could check here if ECLIPSELINK is used as JPA provider in persistence.xml
    // and abort, if something else is used.

    // 1. Copy the "persistence.xml" from the addon resources to the directory
    //    "src\main\resources\META-INF\persistence.xml" of the project.
    //    -> the existing "persistence.xml" will be overwritten, so we will do
    //       a backup before to be able to revert this operation.

    // Get the META-INF dir of the current project ("src\main\resources\META-INF")
    // (Later in the packaged WAR this directory will reside in "WEB-INF\classes\META-INF".) 
    String dirWebMetaInf = this.getPathResolved(Path.SRC_MAIN_RESOURCES, "META-INF");
    // Backup "persistence.xml" which is located in this folder
    this.backup(dirWebMetaInf + File.separatorChar + "persistence.xml", null);
    // Overwrite the existing "persistence.xml" with the one included in the resources of our addon
    copyFileFromAddonToProject(dirWebMetaInf, "persistence.xml",
            "HANA Cloud JPA persistency config (needs EclipseLink)");

    // --------------------------------------------------------------------------------

    // 2. Backup "src\main\webapp\WEB-INF\web.xml" first, and then modify it by inserting
    //    the following to declare the DataSource which the application server should
    //    fetch from the environment and provide to the web app through JNDI.
    //      <resource-ref>
    //         <res-ref-name>jdbc/DefaultDB</res-ref-name>
    //         <res-type>javax.sql.DataSource</res-type>
    //      </resource-ref>

    // Get the WEB-INF dir ("src\main\webapp\WEB-INF"), where the "web.xml" is located.
    String dirWebInf = this.getPathResolved(Path.SRC_MAIN_WEBAPP, "WEB-INF");
    String fileWebXml = dirWebInf + File.separatorChar + "web.xml";

    // Backup "src\main\webapp\META-INF\web.xml"
    this.backup(fileWebXml, null);

    // Insert declaration for app server in "web.xml" to import DataSource from environment to JNDI

    // Read "web.xml" and store reference to root Element
    Document document = XmlUtils.readXml(fileManager.getInputStream(fileWebXml));
    Element root = document.getDocumentElement();

    // Add JNDI ressource definition for JPA data source to use (if it does not yet exist)
    if (XmlUtils.findFirstElement("/web-app/resource-ref/resource-ref-name[text()='jdbc/DefaultDB']",
            root) == null) {

        // Create needed DOM elements
        String elemNamespace = "http://java.sun.com/xml/ns/javaee";
        Element resRefElement = document.createElementNS(elemNamespace, "resource-ref");
        Element resRefNameElement = document.createElementNS(elemNamespace, "res-ref-name");
        Node resRefNameElementText = document.createTextNode("jdbc/DefaultDB");
        Element resRefTypeElement = document.createElementNS(elemNamespace, "res-type");
        Node resRefTypeElementText = document.createTextNode("javax.sql.DataSource");

        // Connect and insert elements in XML document
        resRefNameElement.appendChild(resRefNameElementText);
        resRefTypeElement.appendChild(resRefTypeElementText);
        resRefElement.appendChild(resRefNameElement);
        resRefElement.appendChild(resRefTypeElement);
        root.appendChild(resRefElement);

        // Update "web.xml"
        String descriptionOfChange = "Added JNDI ressource for JPA datasource";
        fileManager.createOrUpdateTextFileIfRequired(fileWebXml, XmlUtils.nodeToString(document),
                descriptionOfChange, true);

    }

    // --------------------------------------------------------------------------------

    // 3. Modify "src\main\resources\META-INF\spring\applicationContext.xml"
    //    - Remove the existing declaration of the "dataSource" bean
    //         <bean class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" id="dataSource">
    //            [...]
    //         </bean>
    //    - Insert statement to fetch dataSource from JNDI (as created by application server)
    //         <jee:jndi-lookup id="dataSource" jndi-name="jdbc/DefaultDB" />

    // Get the Spring config file of the current project ("src\main\resources\META-INF\spring\applicationContext.xml")
    // and create a backup of it, so we're able to revert the changes.
    String fileSpringConf = this.getPathResolved(Path.SPRING_CONFIG_ROOT, "applicationContext.xml");
    this.backup(fileSpringConf, null);

    // Read "applicationContext.xml" and store reference to root Element
    document = XmlUtils.readXml(fileManager.getInputStream(fileSpringConf));
    root = document.getDocumentElement();

    // Loop through all bean elements and remove all beans having id "dataSource"
    String descriptionOfChange = "";
    List<Element> beanElements = XmlUtils.findElements("/beans/bean", root);
    for (Element beanElement : beanElements) {
        // Did we find the bean with the id "dataSource"?
        if (beanElement.getAttribute("id").equalsIgnoreCase("dataSource")) {
            Node parent = beanElement.getParentNode();
            parent.removeChild(beanElement);
            DomUtils.removeTextNodes(parent);
            descriptionOfChange = "Removed bean storing static datasource";
            // We will not break the loop (even though we could theoretically), just in case there is more than one such bean declared            
        }
    }

    // Update "applicationContext.xml" file if something has changed
    fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document),
            descriptionOfChange, true);

    // Add bean for dynamic JNDI lookup of datasource (if it does not yet exist)
    if (XmlUtils.findFirstElement("/beans/jndi-lookup[@id='dataSource']", root) == null) {

        Element newJndiElement = document.createElementNS("http://www.springframework.org/schema/jee",
                "jee:jndi-lookup");
        newJndiElement.setAttribute("id", "dataSource");
        newJndiElement.setAttribute("jndi-name", "jdbc/DefaultDB");
        root.appendChild(newJndiElement);
        descriptionOfChange = "Added bean for dynamic JNDI lookup of datasource";

        // Update "applicationContext.xml"
        fileManager.createOrUpdateTextFileIfRequired(fileSpringConf, XmlUtils.nodeToString(document),
                descriptionOfChange, true);

    }

}

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

/**
* Exports an Azure SQL Database into a DACPAC file in Azure Blob Storage.
*
* @param serverName Required. The name of the Azure SQL Database Server in
* which the database to export resides.//  w ww .j a  v  a  2 s . c  o m
* @param parameters Optional. The parameters needed to initiate the export
* 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 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 response that the service returns once an import
* or export operation has been initiated.
*/
@Override
public DacImportExportResponse export(String serverName, DacExportParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters != null) {
        if (parameters.getBlobCredentials() != null) {
            if (parameters.getBlobCredentials().getStorageAccessKey() == null) {
                throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey");
            }
            if (parameters.getBlobCredentials().getUri() == null) {
                throw new NullPointerException("parameters.BlobCredentials.Uri");
            }
        }
        if (parameters.getConnectionInfo() != null) {
            if (parameters.getConnectionInfo().getDatabaseName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.DatabaseName");
            }
            if (parameters.getConnectionInfo().getPassword() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.Password");
            }
            if (parameters.getConnectionInfo().getServerName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.ServerName");
            }
            if (parameters.getConnectionInfo().getUserName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.UserName");
            }
        }
    }

    // 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, "exportAsync", 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 + "/DacOperations/Export";
    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();

    if (parameters != null) {
        Element exportInputElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "ExportInput");
        requestDoc.appendChild(exportInputElement);

        if (parameters.getBlobCredentials() != null) {
            Element blobCredentialsElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "BlobCredentials");
            exportInputElement.appendChild(blobCredentialsElement);

            Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                    "type");
            typeAttribute.setValue("BlobStorageAccessKeyCredentials");
            blobCredentialsElement.setAttributeNode(typeAttribute);

            Element uriElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Uri");
            uriElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString()));
            blobCredentialsElement.appendChild(uriElement);

            Element storageAccessKeyElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "StorageAccessKey");
            storageAccessKeyElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey()));
            blobCredentialsElement.appendChild(storageAccessKeyElement);
        }

        if (parameters.getConnectionInfo() != null) {
            Element connectionInfoElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ConnectionInfo");
            exportInputElement.appendChild(connectionInfoElement);

            Element databaseNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "DatabaseName");
            databaseNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName()));
            connectionInfoElement.appendChild(databaseNameElement);

            Element passwordElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Password");
            passwordElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword()));
            connectionInfoElement.appendChild(passwordElement);

            Element serverNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ServerName");
            serverNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName()));
            connectionInfoElement.appendChild(serverNameElement);

            Element userNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "UserName");
            userNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName()));
            connectionInfoElement.appendChild(userNameElement);
        }
    }

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

            Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/2003/10/Serialization/", "guid");
            if (guidElement != null) {
                result.setGuid(guidElement.getTextContent());
            }

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

/**
* Initiates an Import of a DACPAC file from Azure Blob Storage into a Azure
* SQL Database./*from w  w  w .  j  a  va  2 s  . c  o m*/
*
* @param serverName Required. The name of the Azure SQL Database Server
* into which the database is being imported.
* @param parameters Optional. The parameters needed to initiated the Import
* 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 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 response that the service returns once an import
* or export operation has been initiated.
*/
@Override
public DacImportExportResponse importMethod(String serverName, DacImportParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters != null) {
        if (parameters.getBlobCredentials() != null) {
            if (parameters.getBlobCredentials().getStorageAccessKey() == null) {
                throw new NullPointerException("parameters.BlobCredentials.StorageAccessKey");
            }
            if (parameters.getBlobCredentials().getUri() == null) {
                throw new NullPointerException("parameters.BlobCredentials.Uri");
            }
        }
        if (parameters.getConnectionInfo() != null) {
            if (parameters.getConnectionInfo().getDatabaseName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.DatabaseName");
            }
            if (parameters.getConnectionInfo().getPassword() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.Password");
            }
            if (parameters.getConnectionInfo().getServerName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.ServerName");
            }
            if (parameters.getConnectionInfo().getUserName() == null) {
                throw new NullPointerException("parameters.ConnectionInfo.UserName");
            }
        }
    }

    // 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, "importMethodAsync", 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 + "/DacOperations/Import";
    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();

    if (parameters != null) {
        Element importInputElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "ImportInput");
        requestDoc.appendChild(importInputElement);

        if (parameters.getAzureEdition() != null) {
            Element azureEditionElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "AzureEdition");
            azureEditionElement.appendChild(requestDoc.createTextNode(parameters.getAzureEdition()));
            importInputElement.appendChild(azureEditionElement);
        }

        if (parameters.getBlobCredentials() != null) {
            Element blobCredentialsElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "BlobCredentials");
            importInputElement.appendChild(blobCredentialsElement);

            Attr typeAttribute = requestDoc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance",
                    "type");
            typeAttribute.setValue("BlobStorageAccessKeyCredentials");
            blobCredentialsElement.setAttributeNode(typeAttribute);

            Element uriElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Uri");
            uriElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getUri().toString()));
            blobCredentialsElement.appendChild(uriElement);

            Element storageAccessKeyElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "StorageAccessKey");
            storageAccessKeyElement.appendChild(
                    requestDoc.createTextNode(parameters.getBlobCredentials().getStorageAccessKey()));
            blobCredentialsElement.appendChild(storageAccessKeyElement);
        }

        if (parameters.getConnectionInfo() != null) {
            Element connectionInfoElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ConnectionInfo");
            importInputElement.appendChild(connectionInfoElement);

            Element databaseNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "DatabaseName");
            databaseNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getDatabaseName()));
            connectionInfoElement.appendChild(databaseNameElement);

            Element passwordElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "Password");
            passwordElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getPassword()));
            connectionInfoElement.appendChild(passwordElement);

            Element serverNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "ServerName");
            serverNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getServerName()));
            connectionInfoElement.appendChild(serverNameElement);

            Element userNameElement = requestDoc.createElementNS(
                    "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                    "UserName");
            userNameElement
                    .appendChild(requestDoc.createTextNode(parameters.getConnectionInfo().getUserName()));
            connectionInfoElement.appendChild(userNameElement);
        }

        Element databaseSizeInGBElement = requestDoc.createElementNS(
                "http://schemas.datacontract.org/2004/07/Microsoft.SqlServer.Management.Dac.ServiceTypes",
                "DatabaseSizeInGB");
        databaseSizeInGBElement
                .appendChild(requestDoc.createTextNode(Integer.toString(parameters.getDatabaseSizeInGB())));
        importInputElement.appendChild(databaseSizeInGBElement);
    }

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

            Element guidElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/2003/10/Serialization/", "guid");
            if (guidElement != null) {
                result.setGuid(guidElement.getTextContent());
            }

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