Example usage for org.w3c.dom Document createTextNode

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

Introduction

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

Prototype

public Text createTextNode(String data);

Source Link

Document

Creates a Text node given the specified string.

Usage

From source file:fr.inria.wimmics.coresetimer.CoreseTimer.java

public void writeStatistics() {
    Document doc = null;
    try {//w  w  w . j  ava 2  s .c o m
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        doc = dBuilder.newDocument();
        Element rootElement = doc.createElement("TestResult");

        Element inputs = doc.createElement("Inputs");

        Element inputFile = doc.createElement("Input");
        Text inputFileText = doc.createTextNode(test.getInput());
        inputFile.appendChild(inputFileText);

        Element request = doc.createElement("Request");
        Text requestText = doc.createTextNode(test.getRequest());
        request.appendChild(requestText);

        Element timestamp = doc.createElement("Timestamp");
        Text timestampText = doc.createTextNode(LocalDateTime.now().toString());
        timestamp.appendChild(timestampText);

        Element[] subElements = { inputFile, request, timestamp };
        for (Element e : subElements) {
            inputs.appendChild(e);
        }

        Element outputs = doc.createElement("Statistics");

        Element statsMemory = doc.createElement("CPU");
        Text statsMemoryText = doc.createTextNode(getStats().toString());
        statsMemory.appendChild(statsMemoryText);

        Element statsMemoryCoreseMem = doc.createElement("Memory");
        Text statsMemoryCoreseMemText = doc.createTextNode(getStatsMemory().toString());
        statsMemoryCoreseMem.appendChild(statsMemoryCoreseMemText);

        Element[] subElements2 = { statsMemory, statsMemoryCoreseMem };
        for (Element e : subElements2) {
            outputs.appendChild(e);
        }

        rootElement.appendChild(inputs);
        rootElement.appendChild(outputs);

        doc.appendChild(rootElement);

        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        DOMSource source = new DOMSource(doc);
        StreamResult streamResult = new StreamResult(new File(test.getOutputPath()));
        transformer.transform(source, streamResult);
        LOGGER.log(Level.INFO, "Results were written in:", test.getOutputPath());
    } catch (ParserConfigurationException | TransformerException ex) {
        LOGGER.log(Level.INFO, "Error when writing results:", ex.getMessage());
        ex.printStackTrace();
    }

}

From source file:com.mirth.connect.connectors.jdbc.DatabaseReceiver.java

/**
 * Convert a resultMap representing a message into XML.
 *///from w ww  .j a va  2  s.c om
private String resultMapToXml(Map<String, Object> resultMap) throws Exception {
    Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
    Element root = document.createElement("result");
    document.appendChild(root);

    for (Entry<String, Object> entry : resultMap.entrySet()) {
        String value = objectToString(entry.getValue());

        if (value != null) {
            Element child = document.createElement(entry.getKey());
            child.appendChild(document.createTextNode(value));
            root.appendChild(child);
        }
    }

    return new DocumentSerializer().toXML(document);
}

From source file:com.icesoft.faces.renderkit.dom_html_basic.MenuRenderer.java

protected void renderOption(FacesContext facesContext, UIComponent uiComponent, SelectItem selectItem,
        Element optionGroup, Object[] submittedValues, Object selectedValues) throws IOException {

    DOMContext domContext = DOMContext.getDOMContext(facesContext, uiComponent);

    Element select = (Element) domContext.getRootNode();
    Element option = domContext.createElement("option");

    if (optionGroup == null) {
        select.appendChild(option);//from  w  w  w.  j  a va2  s.c o  m
    } else {
        optionGroup.appendChild(option);
    }

    String valueString = formatComponentValue(facesContext, uiComponent, selectItem.getValue());
    option.setAttribute("value", valueString);

    boolean selected = isValueSelected(facesContext, selectItem, uiComponent, submittedValues, selectedValues);
    if (uiComponent instanceof HtmlSelectOneMenu) {
        if (submittedValues == null && selectedValues == null
                && (selectItem.getValue() == "" || selectItem.getValue() == null))
            selected = true;
    }

    if (selected) {
        option.setAttribute("selected", "selected");
    }
    if (selectItem.isDisabled()) {
        option.setAttribute("disabled", "disabled");
    }

    Document doc = domContext.getDocument();
    String label = selectItem.getLabel();
    Text labelNode = doc.createTextNode(label == null ? valueString : label);
    option.appendChild(labelNode);
}

From source file:Main.java

public static void copyInto(Node src, Node dest) throws DOMException {

    Document factory = dest.getOwnerDocument();

    //Node start = src;
    Node parent = null;//from  w  w w  . j a  v a 2  s . c  om
    Node place = src;

    // traverse source tree
    while (place != null) {

        // copy this node
        Node node = null;
        int type = place.getNodeType();
        switch (type) {
        case Node.CDATA_SECTION_NODE: {
            node = factory.createCDATASection(place.getNodeValue());
            break;
        }
        case Node.COMMENT_NODE: {
            node = factory.createComment(place.getNodeValue());
            break;
        }
        case Node.ELEMENT_NODE: {
            Element element = factory.createElement(place.getNodeName());
            node = element;
            NamedNodeMap attrs = place.getAttributes();
            int attrCount = attrs.getLength();
            for (int i = 0; i < attrCount; i++) {
                Attr attr = (Attr) attrs.item(i);
                String attrName = attr.getNodeName();
                String attrValue = attr.getNodeValue();
                element.setAttribute(attrName, attrValue);
            }
            break;
        }
        case Node.ENTITY_REFERENCE_NODE: {
            node = factory.createEntityReference(place.getNodeName());
            break;
        }
        case Node.PROCESSING_INSTRUCTION_NODE: {
            node = factory.createProcessingInstruction(place.getNodeName(), place.getNodeValue());
            break;
        }
        case Node.TEXT_NODE: {
            node = factory.createTextNode(place.getNodeValue());
            break;
        }
        default: {
            throw new IllegalArgumentException(
                    "can't copy node type, " + type + " (" + place.getNodeName() + ')');
        }
        }
        dest.appendChild(node);

        // iterate over children
        if (place.hasChildNodes()) {
            parent = place;
            place = place.getFirstChild();
            dest = node;
        } else if (parent == null) {
            place = null;
        } else {
            // advance
            place = place.getNextSibling();
            while (place == null && parent != null) {
                place = parent.getNextSibling();
                parent = parent.getParentNode();
                dest = dest.getParentNode();
            }
        }

    }

}

From source file:edu.wpi.margrave.MCommunicator.java

/**
 * We suspended stdin and stdout. Append what has accumulated to the response.
 * @param theResponse//from   ww w.ja  v a 2s .c  om
 */
protected static void addBuffers(Document theResponse) {
    // add in any supplemental or error information
    Element envOutChild = theResponse.createElementNS(null, "EXTRA-OUT");
    envOutChild.appendChild(theResponse.createTextNode(MEnvironment.outBuffer.toString()));
    Element envErrChild = theResponse.createElementNS(null, "EXTRA-ERR");
    envErrChild.appendChild(theResponse.createTextNode(MEnvironment.errorBuffer.toString()));

    // Clear out the "out" and "error" buffers.
    MEnvironment.errorBuffer.getBuffer().setLength(0);
    MEnvironment.outBuffer.getBuffer().setLength(0);

    theResponse.getDocumentElement().appendChild(envOutChild);
    theResponse.getDocumentElement().appendChild(envErrChild);
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected String getSummariesXML(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it/* w  w  w .  j  a  v  a2 s  .  c  o m*/
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        Source source = new DOMSource(response);
        StringWriter stringWriter = new StringWriter();
        Result result = new StreamResult(stringWriter);
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer transformer = factory.newTransformer();
        transformer.transform(source, result);
        return stringWriter.getBuffer().toString();
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return "";
}

From source file:org.apache.camel.component.cm.CMSenderOneMessageImpl.java

private String createXml(final CMMessage message) {

    try {/*from   w  ww. j a  v a2s  . co  m*/

        final ByteArrayOutputStream xml = new ByteArrayOutputStream();
        final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);

        // Get the DocumentBuilder
        final DocumentBuilder docBuilder = factory.newDocumentBuilder();

        // Create blank DOM Document
        final DOMImplementation impl = docBuilder.getDOMImplementation();
        final Document doc = impl.createDocument(null, "MESSAGES", null);

        // ROOT Element es MESSAGES
        final Element root = doc.getDocumentElement();

        // AUTHENTICATION element
        final Element authenticationElement = doc.createElement("AUTHENTICATION");
        final Element productTokenElement = doc.createElement("PRODUCTTOKEN");
        authenticationElement.appendChild(productTokenElement);
        final Text productTokenValue = doc.createTextNode("" + productToken);
        productTokenElement.appendChild(productTokenValue);
        root.appendChild(authenticationElement);

        // MSG Element
        final Element msgElement = doc.createElement("MSG");
        root.appendChild(msgElement);

        // <FROM>VALUE</FROM>
        final Element fromElement = doc.createElement("FROM");
        fromElement.appendChild(doc.createTextNode(message.getSender()));
        msgElement.appendChild(fromElement);

        // <BODY>VALUE</BODY>
        final Element bodyElement = doc.createElement("BODY");
        bodyElement.appendChild(doc.createTextNode(message.getMessage()));
        msgElement.appendChild(bodyElement);

        // <TO>VALUE</TO>
        final Element toElement = doc.createElement("TO");
        toElement.appendChild(doc.createTextNode(message.getPhoneNumber()));
        msgElement.appendChild(toElement);

        // <DCS>VALUE</DCS> - if UNICODE - messageOut.isGSM338Enc
        // false
        if (message.isUnicode()) {
            final Element dcsElement = doc.createElement("DCS");
            dcsElement.appendChild(doc.createTextNode("8"));
            msgElement.appendChild(dcsElement);
        }

        // <REFERENCE>VALUE</REFERENCE> -Alfanum
        final String id = message.getIdAsString();
        if (id != null && !id.isEmpty()) {
            final Element refElement = doc.createElement("REFERENCE");
            refElement.appendChild(doc.createTextNode("" + message.getIdAsString()));
            msgElement.appendChild(refElement);
        }

        // <MINIMUMNUMBEROFMESSAGEPARTS>1</MINIMUMNUMBEROFMESSAGEPARTS>
        // <MAXIMUMNUMBEROFMESSAGEPARTS>8</MAXIMUMNUMBEROFMESSAGEPARTS>
        if (message.isMultipart()) {
            final Element minMessagePartsElement = doc.createElement("MINIMUMNUMBEROFMESSAGEPARTS");
            minMessagePartsElement.appendChild(doc.createTextNode("1"));
            msgElement.appendChild(minMessagePartsElement);

            final Element maxMessagePartsElement = doc.createElement("MAXIMUMNUMBEROFMESSAGEPARTS");
            maxMessagePartsElement.appendChild(doc.createTextNode(Integer.toString(message.getMultiparts())));
            msgElement.appendChild(maxMessagePartsElement);
        }

        // Creatate XML as String
        final Transformer aTransformer = TransformerFactory.newInstance().newTransformer();
        aTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        final Source src = new DOMSource(doc);
        final Result dest = new StreamResult(xml);
        aTransformer.transform(src, dest);
        return xml.toString();
    } catch (final TransformerException e) {
        LOG.error("Cant serialize CMMessage {}: ", message, e);
        throw new XMLConstructionException(e);
    } catch (final ParserConfigurationException e) {
        LOG.error("Cant serialize CMMessage {}: ", message, e);
        throw new XMLConstructionException(e);
    }
}

From source file:edu.toronto.cs.cidb.ncbieutils.NCBIEUtilsAccessService.java

protected List<Map<String, Object>> getSummaries(List<String> idList) {
    // response example at
    // http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esummary.fcgi?db=omim&id=190685,605298,604829,602917,601088,602523,602259
    // response type: XML
    // return it/*from  w  w w . jav  a  2 s .  c  o m*/
    String queryList = getSerializedList(idList);
    String url = composeURL(TERM_SUMMARY_QUERY_SCRIPT, TERM_SUMMARY_PARAM_NAME, queryList);
    try {
        Document response = readXML(url);
        NodeList nodes = response.getElementsByTagName("Item");
        // OMIM titles are all UPPERCASE, try to fix this
        for (int i = 0; i < nodes.getLength(); ++i) {
            Node n = nodes.item(i);
            if (n.getNodeType() == Node.ELEMENT_NODE) {
                if (n.getFirstChild() != null) {
                    n.replaceChild(response.createTextNode(fixCase(n.getTextContent())), n.getFirstChild());
                }
            }
        }
        List<Map<String, Object>> result = new LinkedList<Map<String, Object>>();
        nodes = response.getElementsByTagName("DocSum");
        for (int i = 0; i < nodes.getLength(); ++i) {
            Element n = (Element) nodes.item(i);
            Map<String, Object> doc = new HashMap<String, Object>();
            doc.put("id", n.getElementsByTagName("Id").item(0).getTextContent());
            NodeList items = n.getElementsByTagName("Item");
            for (int j = 0; j < items.getLength(); ++j) {
                Element item = (Element) items.item(j);
                if ("List".equals(item.getAttribute("Type"))) {
                    NodeList subitems = item.getElementsByTagName("Item");
                    if (subitems.getLength() > 0) {
                        List<String> values = new ArrayList<String>(subitems.getLength());
                        for (int k = 0; k < subitems.getLength(); ++k) {
                            values.add(subitems.item(k).getTextContent());
                        }
                        doc.put(item.getAttribute("Name"), values);
                    }
                } else {
                    String value = item.getTextContent();
                    if (StringUtils.isNotEmpty(value)) {
                        doc.put(item.getAttribute("Name"), value);
                    }
                }
            }
            result.add(doc);
        }
        return result;
    } catch (Exception ex) {
        this.logger.error("Error while trying to retrieve summaries for ids " + idList + " "
                + ex.getClass().getName() + " " + ex.getMessage(), ex);
    }
    return Collections.emptyList();
}

From source file:com.verisign.epp.codec.signedMark.EPPEncodedSignedMark.java

/**
 * Sets all this instance's data in the given XML document
 * //from  w  w  w  .  ja v a 2  s . c o  m
 * @param aDocument
 *        a DOM Document to attach data to.
 * @return The root element of this component.
 * @throws EPPEncodeException
 *         Thrown if any errors prevent encoding.
 */
public Element encode(Document aDocument) throws EPPEncodeException {
    cat.debug("EPPEncodedSignedMark.encode(Document): enter");

    if (aDocument == null) {
        throw new EPPEncodeException("aDocument is null" + " on in EPPSignedMark.encode(Document)");
    }

    Element root = aDocument.createElementNS(NS, NS_PREFIX + ":" + ELM_ENCODED_SIGNED_MARK_LOCALNAME);

    byte[] signedMarkXml = super.encode();

    String base64EncodedText = new String(Base64.encodeBase64(signedMarkXml, true));

    Text currVal = aDocument.createTextNode(base64EncodedText);
    root.appendChild(currVal);
    cat.debug("EPPEncodedSignedMark.encode(Document): exit - encoded");
    return root;
}

From source file:de.crowdcode.movmvn.plugin.general.GeneralPlugin.java

private Element createPomRootAndTitle(Document doc) {
    Element rootElement = doc.createElement("project");
    doc.appendChild(rootElement);//from  w w w .jav  a2  s  . c o m
    rootElement.setAttribute("xmlns", "http://maven.apache.org/POM/4.0.0");
    rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
    rootElement.setAttribute("xsi:schemaLocation",
            "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd");

    Element modelVersion = doc.createElement("modelVersion");
    modelVersion.appendChild(doc.createTextNode("4.0.0"));
    rootElement.appendChild(modelVersion);

    createPomGroupArtifactVersion(doc, rootElement, "de.xxx", context.getProjectName(), "1.0.0-SNAPSHOT");

    Element packaging = doc.createElement("packaging");
    packaging.appendChild(doc.createTextNode("jar"));
    rootElement.appendChild(packaging);
    Element name = doc.createElement("name");
    name.appendChild(doc.createTextNode(context.getProjectName()));
    rootElement.appendChild(name);
    Element url = doc.createElement("url");
    url.appendChild(doc.createTextNode("http://maven.apache.org"));
    rootElement.appendChild(url);
    return rootElement;
}