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:gov.nij.bundles.intermediaries.ers.EntityResolutionMessageHandler.java

/**
 * This method takes the ER response and converts the Java objects to the Merge Response XML.
 * //from  w ww  . j  a va  2 s.c  o  m
 * @param entityContainerNode
 * @param results
 * @param recordLimit
 * @param attributeParametersNode
 * @return
 * @throws ParserConfigurationException
 * @throws XPathExpressionException
 * @throws TransformerException
 */
private Document createResponseMessage(Node entityContainerNode, EntityResolutionResults results,
        Node attributeParametersNode, int recordLimit) throws Exception {

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);

    Document resultDocument = dbf.newDocumentBuilder().newDocument();

    Element entityMergeResultMessageElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityMergeResultMessage");
    resultDocument.appendChild(entityMergeResultMessageElement);

    Element entityContainerElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "EntityContainer");
    entityMergeResultMessageElement.appendChild(entityContainerElement);

    NodeList inputEntityNodes = (NodeList) xpath.evaluate("er-ext:Entity", entityContainerNode,
            XPathConstants.NODESET);
    Collection<Element> inputEntityElements = null;
    if (attributeParametersNode == null) {
        inputEntityElements = new ArrayList<Element>();
    } else {
        inputEntityElements = TreeMultiset
                .create(new EntityElementComparator((Element) attributeParametersNode));
        //inputEntityElements = new ArrayList<Element>();
    }

    for (int i = 0; i < inputEntityNodes.getLength(); i++) {
        inputEntityElements.add((Element) inputEntityNodes.item(i));
    }

    if (attributeParametersNode == null) {
        LOG.warn("Attribute Parameters element was null, so records will not be sorted");
    }
    //Collections.sort((List<Element>) inputEntityElements, new EntityElementComparator((Element) attributeParametersNode));

    if (inputEntityElements.size() != inputEntityNodes.getLength()) {
        LOG.error("Lost elements in ER output sorting.  Input count=" + inputEntityNodes.getLength()
                + ", output count=" + inputEntityElements.size());
    }

    for (Element e : inputEntityElements) {
        Node clone = resultDocument.adoptNode(e.cloneNode(true));
        resultDocument.renameNode(clone, EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                e.getLocalName());
        entityContainerElement.appendChild(clone);
    }

    Element mergedRecordsElement = resultDocument
            .createElementNS(EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "MergedRecords");
    entityMergeResultMessageElement.appendChild(mergedRecordsElement);

    if (results != null) {

        List<RecordWrapper> records = results.getRecords();

        // Loop through RecordWrappers to extract info to create merged records
        for (RecordWrapper record : records) {
            LOG.debug("  !#!#!#!# Record 1, id=" + record.getExternalId() + ", externals="
                    + record.getRelatedIds());

            // Create Merged Record Container
            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            // Create Original Record Reference for 'first record'
            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", record.getExternalId());
            mergedRecordElement.appendChild(originalRecordRefElement);

            // Loop through and add any related records
            for (String relatedRecordId : record.getRelatedIds()) {
                originalRecordRefElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
                originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                        "ref", relatedRecordId);
                mergedRecordElement.appendChild(originalRecordRefElement);
            }

            // Create Merge Quality Element
            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            Set<AttributeStatistics> stats = results.getStatisticsForRecord(record.getExternalId());
            for (AttributeStatistics stat : stats) {
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(stat.getAttributeName());
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode(String.valueOf(stat.getAverageStringDistance()));
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument
                        .createTextNode(String.valueOf(stat.getStandardDeviationStringDistance()));
                sdElement.appendChild(contentNode);

            }
        }

    } else {

        for (Element e : inputEntityElements) {

            String id = e.getAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE, "id");

            Element mergedRecordElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergedRecord");
            mergedRecordsElement.appendChild(mergedRecordElement);

            Element originalRecordRefElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "OriginalRecordReference");
            originalRecordRefElement.setAttributeNS(EntityResolutionNamespaceContext.STRUCTURES_NAMESPACE,
                    "ref", id);
            mergedRecordElement.appendChild(originalRecordRefElement);

            Element mergeQualityElement = resultDocument.createElementNS(
                    EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "MergeQuality");
            mergedRecordElement.appendChild(mergeQualityElement);
            XPath xp = XPathFactory.newInstance().newXPath();
            xp.setNamespaceContext(new EntityResolutionNamespaceContext());
            NodeList attributeParameterNodes = (NodeList) xp.evaluate("er-ext:AttributeParameter",
                    attributeParametersNode, XPathConstants.NODESET);
            for (int i = 0; i < attributeParameterNodes.getLength(); i++) {
                String attributeName = xp.evaluate("er-ext:AttributeXPath", attributeParametersNode);
                Element stringDistanceStatsElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStatistics");
                mergeQualityElement.appendChild(stringDistanceStatsElement);
                Element xpathElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE, "AttributeXPath");
                stringDistanceStatsElement.appendChild(xpathElement);
                Node contentNode = resultDocument.createTextNode(attributeName);
                xpathElement.appendChild(contentNode);
                Element meanElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceMeanInRecord");
                stringDistanceStatsElement.appendChild(meanElement);
                contentNode = resultDocument.createTextNode("0.0");
                meanElement.appendChild(contentNode);
                Element sdElement = resultDocument.createElementNS(
                        EntityResolutionNamespaceContext.MERGE_RESULT_EXT_NAMESPACE,
                        "StringDistanceStandardDeviationInRecord");
                stringDistanceStatsElement.appendChild(sdElement);
                contentNode = resultDocument.createTextNode("0.0");
                sdElement.appendChild(contentNode);
            }

        }

    }

    Element recordLimitExceededElement = resultDocument.createElementNS(
            EntityResolutionNamespaceContext.MERGE_RESULT_NAMESPACE, "RecordLimitExceededIndicator");
    recordLimitExceededElement.setTextContent(new Boolean(results == null).toString());
    entityMergeResultMessageElement.appendChild(recordLimitExceededElement);

    return resultDocument;

}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

public <T> Element marshalElementToDom(JAXBElement<T> jaxbElement, Document doc) throws JAXBException {
    if (doc == null) {
        doc = DOMUtil.getDocument();/* ww w. j a  va  2s . c o  m*/
    }

    Element element = doc.createElementNS(jaxbElement.getName().getNamespaceURI(),
            jaxbElement.getName().getLocalPart());
    marshalElementToDom(jaxbElement, element);

    return (Element) element.getFirstChild();
}

From source file:com.verisign.epp.codec.gen.EPPUtil.java

/**
 * Encode a <code>String</code> in XML with a given XML namespace and tag
 * name./*from  ww w .j  a v  a2s. com*/
 * 
 * @param aDocument
 *            DOM Document of <code>aRoot</code>. This parameter also acts
 *            as a factory for XML elements.
 * @param aRoot
 *            XML Element to add children nodes to. For example, the root
 *            node could be &ltdomain:update&gt
 * @param aString
 *            <code>String</code> to add.
 * @param aNS
 *            XML namespace of the element. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @exception EPPEncodeException
 *                Error encoding the <code>String</code>.
 */
public static void encodeString(Document aDocument, Element aRoot, String aString, String aNS, String aTagName)
        throws EPPEncodeException {
    if (aString != null) {
        Element currElm = aDocument.createElementNS(aNS, aTagName);
        Text currVal = aDocument.createTextNode(aString);

        currElm.appendChild(currVal);
        aRoot.appendChild(currElm);
    }
}

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

/**
* Changes the administrative password of an existing Azure SQL Database
* Server for a given subscription.//from  www. j a  v  a  2 s  . com
*
* @param serverName Required. The name of the Azure SQL Database Server
* that will have the administrator password changed.
* @param parameters Required. The necessary parameters for modifying the
* adminstrator password for a server.
* @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 changeAdministratorPassword(String serverName,
        ServerChangeAdministratorPasswordParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (serverName == null) {
        throw new NullPointerException("serverName");
    }
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getNewPassword() == null) {
        throw new NullPointerException("parameters.NewPassword");
    }

    // 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, "changeAdministratorPasswordAsync", 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");
    ArrayList<String> queryParameters = new ArrayList<String>();
    queryParameters.add("op=ResetPassword");
    if (queryParameters.size() > 0) {
        url = url + "?" + CollectionStringBuilder.join(queryParameters, "&");
    }
    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 administratorLoginPasswordElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword");
    requestDoc.appendChild(administratorLoginPasswordElement);

    administratorLoginPasswordElement.appendChild(requestDoc.createTextNode(parameters.getNewPassword()));

    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.verisign.epp.codec.gen.EPPUtil.java

/**
 * Encode a <code>Boolean</code> in XML with a given XML namespace and tag
 * name. If aBoolean is <code>null</code> an element is not added.
 * //  w  ww  . java2 s.c o m
 * @param aDocument
 *            DOM Document of <code>aRoot</code>. This parameter also acts
 *            as a factory for XML elements.
 * @param aRoot
 *            XML Element to add children nodes to. For example, the root
 *            node could be &ltdomain:update&gt
 * @param aBoolean
 *            <code>Boolean</code> to add.
 * @param aNS
 *            XML namespace of the element. For example, for domain element
 *            this is "urn:iana:xmlns:domain".
 * @param aTagName
 *            Tag name of the element including an optional namespace
 *            prefix. For example, the tag name for the domain name is
 *            "domain:name".
 * @exception EPPEncodeException
 *                Error encoding the <code>Boolean</code>.
 */
public static void encodeBoolean(Document aDocument, Element aRoot, Boolean aBoolean, String aNS,
        String aTagName) throws EPPEncodeException {
    if (aBoolean != null) {
        Element currElm = aDocument.createElementNS(aNS, aTagName);

        String xmlValue;

        if (aBoolean.booleanValue()) {
            xmlValue = "1";
        } else {
            xmlValue = "0";
        }

        Text currVal = aDocument.createTextNode(xmlValue);

        currElm.appendChild(currVal);
        aRoot.appendChild(currElm);
    }
}

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

/**
* Provisions a new SQL Database server in a subscription.
*
* @param parameters Required. The parameters needed to provision a server.
* @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.// w  w w .j  ava 2s.c o m
* @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 returned from the Create Server operation.  This
* contains all the information returned from the service when a server is
* created.
*/
@Override
public ServerCreateResponse create(ServerCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }
    if (parameters.getAdministratorPassword() == null) {
        throw new NullPointerException("parameters.AdministratorPassword");
    }
    if (parameters.getAdministratorUserName() == null) {
        throw new NullPointerException("parameters.AdministratorUserName");
    }
    if (parameters.getLocation() == null) {
        throw new NullPointerException("parameters.Location");
    }

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

    // Construct URL
    String url = "";
    url = url + "/";
    if (this.getClient().getCredentials().getSubscriptionId() != null) {
        url = url + URLEncoder.encode(this.getClient().getCredentials().getSubscriptionId(), "UTF-8");
    }
    url = url + "/services/sqlservers/servers";
    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 serverElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
            "Server");
    requestDoc.appendChild(serverElement);

    Element administratorLoginElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLogin");
    administratorLoginElement.appendChild(requestDoc.createTextNode(parameters.getAdministratorUserName()));
    serverElement.appendChild(administratorLoginElement);

    Element administratorLoginPasswordElement = requestDoc
            .createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/", "AdministratorLoginPassword");
    administratorLoginPasswordElement
            .appendChild(requestDoc.createTextNode(parameters.getAdministratorPassword()));
    serverElement.appendChild(administratorLoginPasswordElement);

    Element locationElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
            "Location");
    locationElement.appendChild(requestDoc.createTextNode(parameters.getLocation()));
    serverElement.appendChild(locationElement);

    if (parameters.getVersion() != null) {
        Element versionElement = requestDoc.createElementNS("http://schemas.microsoft.com/sqlazure/2010/12/",
                "Version");
        versionElement.appendChild(requestDoc.createTextNode(parameters.getVersion()));
        serverElement.appendChild(versionElement);
    }

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

            Element serverNameElement = XmlUtility.getElementByTagNameNS(responseDoc,
                    "http://schemas.microsoft.com/sqlazure/2010/12/", "ServerName");
            if (serverNameElement != null) {
                Attr fullyQualifiedDomainNameAttribute = serverNameElement.getAttributeNodeNS(
                        "http://schemas.microsoft.com/sqlazure/2010/12/", "FullyQualifiedDomainName");
                if (fullyQualifiedDomainNameAttribute != null) {
                    result.setFullyQualifiedDomainName(fullyQualifiedDomainNameAttribute.getValue());
                }

                result.setServerName(serverNameElement.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.ManagementCertificateOperationsImpl.java

/**
* The Create Management Certificate operation adds a certificate to the
* list of management certificates. Management certificates, which are also
* known as subscription certificates, authenticate clients attempting to
* connect to resources associated with your Azure subscription.  (see
* http://msdn.microsoft.com/en-us/library/windowsazure/jj154123.aspx for
* more information)//  w  ww  .  j  a  va 2  s . c  o  m
*
* @param parameters Required. Parameters supplied to the Create Management
* Certificate 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(ManagementCertificateCreateParameters parameters)
        throws ParserConfigurationException, SAXException, TransformerException, IOException, ServiceException {
    // Validate
    if (parameters == null) {
        throw new NullPointerException("parameters");
    }

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

    if (parameters.getPublicKey() != null) {
        Element subscriptionCertificatePublicKeyElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificatePublicKey");
        subscriptionCertificatePublicKeyElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getPublicKey())));
        subscriptionCertificateElement.appendChild(subscriptionCertificatePublicKeyElement);
    }

    if (parameters.getThumbprint() != null) {
        Element subscriptionCertificateThumbprintElement = requestDoc.createElementNS(
                "http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateThumbprint");
        subscriptionCertificateThumbprintElement
                .appendChild(requestDoc.createTextNode(parameters.getThumbprint()));
        subscriptionCertificateElement.appendChild(subscriptionCertificateThumbprintElement);
    }

    if (parameters.getData() != null) {
        Element subscriptionCertificateDataElement = requestDoc
                .createElementNS("http://schemas.microsoft.com/windowsazure", "SubscriptionCertificateData");
        subscriptionCertificateDataElement
                .appendChild(requestDoc.createTextNode(Base64.encode(parameters.getData())));
        subscriptionCertificateElement.appendChild(subscriptionCertificateDataElement);
    }

    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:chat.viska.xmpp.HandshakerPipe.java

private void initiateResourceBinding() {
    if (pipeline == null) {
        throw new IllegalStateException();
    }/*from   ww w.  j  a v a2  s  .  c o  m*/
    this.resourceBindingIqId = UUID.randomUUID().toString();
    final Document iq = XmlWrapperStanza.createIq(Stanza.IqType.SET, resourceBindingIqId, Jid.EMPTY, Jid.EMPTY);
    final Element bind = (Element) iq.getDocumentElement()
            .appendChild(iq.createElementNS(CommonXmlns.RESOURCE_BINDING, "bind"));
    if (!this.presetResource.isEmpty()) {
        final Element resource = (Element) bind.appendChild(iq.createElement("resource"));
        resource.setTextContent(this.presetResource);
    }
    this.pipeline.write(iq);
}

From source file:com.evolveum.midpoint.prism.util.JaxbTestUtil.java

public <T> Element marshalObjectToDom(T jaxbObject, QName elementQName, Document doc) throws JAXBException {
    if (doc == null) {
        doc = DOMUtil.getDocument();//from w  w  w.  ja  v  a  2  s .  com
    }

    JAXBElement<T> jaxbElement = new JAXBElement<T>(elementQName, (Class<T>) jaxbObject.getClass(), jaxbObject);
    Element element = doc.createElementNS(elementQName.getNamespaceURI(), elementQName.getLocalPart());
    marshalElementToDom(jaxbElement, element);

    return (Element) element.getFirstChild();
}

From source file:marytts.tools.install.ComponentDescription.java

public Document createComponentXML() throws ParserConfigurationException {
    DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance();
    fact.setNamespaceAware(true);// w ww . j  ava  2 s.  c  om
    Document doc = fact.newDocumentBuilder().newDocument();
    Element root = (Element) doc.appendChild(doc.createElementNS(installerNamespaceURI, "marytts-install"));
    Element desc = (Element) root
            .appendChild(doc.createElementNS(installerNamespaceURI, getComponentTypeString()));
    desc.setAttribute("locale", MaryUtils.locale2xmllang(locale));
    desc.setAttribute("name", name);
    desc.setAttribute("version", version);
    Element descriptionElt = (Element) desc
            .appendChild(doc.createElementNS(installerNamespaceURI, "description"));
    descriptionElt.setTextContent(description);
    Element licenseElt = (Element) desc.appendChild(doc.createElementNS(installerNamespaceURI, "license"));
    if (license != null) {
        licenseElt.setAttribute("href", license.toString());
    }
    Element packageElt = (Element) desc.appendChild(doc.createElementNS(installerNamespaceURI, "package"));
    packageElt.setAttribute("size", Integer.toString(packageSize));
    packageElt.setAttribute("md5sum", packageMD5);
    packageElt.setAttribute("filename", packageFilename);
    for (URL l : locations) {
        // Serialize the location without the filename:
        String urlString = l.toString();
        boolean isFolder = false;
        if (urlString.endsWith(packageFilename)) {
            urlString = urlString.substring(0, urlString.length() - packageFilename.length());
            isFolder = true;
        }
        Element lElt = (Element) packageElt.appendChild(doc.createElementNS(installerNamespaceURI, "location"));
        lElt.setAttribute("href", urlString);
        lElt.setAttribute("folder", String.valueOf(isFolder));
    }
    if (installedFilesNames != null) {
        Element filesElement = (Element) desc.appendChild(doc.createElementNS(installerNamespaceURI, "files"));
        filesElement.setTextContent(installedFilesNames);
    }
    return doc;
}