Example usage for org.w3c.dom Node CDATA_SECTION_NODE

List of usage examples for org.w3c.dom Node CDATA_SECTION_NODE

Introduction

In this page you can find the example usage for org.w3c.dom Node CDATA_SECTION_NODE.

Prototype

short CDATA_SECTION_NODE

To view the source code for org.w3c.dom Node CDATA_SECTION_NODE.

Click Source Link

Document

The node is a CDATASection.

Usage

From source file:org.bigbluebutton.impl.BBBProxyImpl.java

protected static Map<String, Object> processNode(Node _node) {
    Map<String, Object> map = new HashMap<String, Object>();
    NodeList responseNodes = _node.getChildNodes();
    for (int i = 0; i < responseNodes.getLength(); i++) {
        Node node = responseNodes.item(i);
        String nodeName = node.getNodeName().trim();
        if (node.getChildNodes().getLength() == 1
                && (node.getChildNodes().item(0).getNodeType() == org.w3c.dom.Node.TEXT_NODE
                        || node.getChildNodes().item(0).getNodeType() == org.w3c.dom.Node.CDATA_SECTION_NODE)) {
            String nodeValue = node.getTextContent();
            map.put(nodeName, nodeValue != null ? nodeValue.trim() : null);

        } else if (node.getChildNodes().getLength() == 0 && node.getNodeType() != org.w3c.dom.Node.TEXT_NODE
                && node.getNodeType() != org.w3c.dom.Node.CDATA_SECTION_NODE) {
            map.put(nodeName, "");

        } else if (node.getChildNodes().getLength() >= 1
                && node.getChildNodes().item(0).getChildNodes().item(0)
                        .getNodeType() != org.w3c.dom.Node.TEXT_NODE
                && node.getChildNodes().item(0).getChildNodes().item(0)
                        .getNodeType() != org.w3c.dom.Node.CDATA_SECTION_NODE) {

            List<Object> list = new ArrayList<Object>();
            for (int c = 0; c < node.getChildNodes().getLength(); c++) {
                Node n = node.getChildNodes().item(c);
                list.add(processNode(n));
            }/*from www  . j a va  2s.  co  m*/
            map.put(nodeName, list);

        } else {
            map.put(nodeName, processNode(node));
        }
    }
    return map;
}

From source file:org.chiba.xml.xforms.constraints.RelevanceSelector.java

private static void addChildren(Element relevantElement, NodeImpl instanceNode) {
    Document ownerDocument = relevantElement.getOwnerDocument();
    NodeList instanceChildren = instanceNode.getChildNodes();

    for (int index = 0; index < instanceChildren.getLength(); index++) {
        NodeImpl instanceChild = (NodeImpl) instanceChildren.item(index);

        if (isEnabled(instanceChild)) {
            switch (instanceChild.getNodeType()) {
            case Node.TEXT_NODE:
                /* rather not, otherwise we cannot follow specs when
                 * serializing to multipart/form-data for example
                 */*from  ww  w  .ja v  a  2  s  .co  m*/
                // denormalize text for better whitespace handling during serialization
                List list = DOMWhitespace.denormalizeText(instanceChild.getNodeValue());
                for (int item = 0; item < list.size(); item++) {
                    relevantElement.appendChild(ownerDocument.createTextNode(list.get(item).toString()));
                }
                */
                relevantElement.appendChild(ownerDocument.createTextNode(instanceChild.getNodeValue()));
                break;
            case Node.CDATA_SECTION_NODE:
                relevantElement.appendChild(ownerDocument.createCDATASection(instanceChild.getNodeValue()));
                break;
            case Node.ELEMENT_NODE:
                addElement(relevantElement, instanceChild);
                break;
            default:
                // ignore
                break;
            }
        }
    }
}

From source file:org.dhatim.delivery.dom.DOMBuilder.java

public void characters(char[] ch, int start, int length) throws SAXException {
    try {/* www  .j  ava 2s  . co  m*/
        Node currentNode = (Node) nodeStack.peek();

        switch (currentNode.getNodeType()) {
        case Node.ELEMENT_NODE:
            if (inEntity && !rewriteEntities) {
                currentNode.appendChild(ownerDocument.createTextNode("&#" + (int) ch[start] + ";"));
            } else {
                currentNode.appendChild(ownerDocument.createTextNode(new String(ch, start, length)));
            }
            break;
        case Node.CDATA_SECTION_NODE:
            cdataNodeBuilder.append(ch, start, length);
            break;
        default:
            break;
        }
    } catch (DOMException e) {
        logger.error("DOMException appending character data [" + new String(ch, start, length) + "]", e);
        throw e;
    }
}

From source file:org.dhatim.delivery.dom.serialize.Serializer.java

/**
 * Recursively write the DOM tree to the supplied writer.
 * @param element Element to write.//from  ww  w.  j a v a  2  s . com
 * @param writer Writer to use.
  * @param isRoot Is the supplied element the document root element.
  * @throws IOException Exception writing to Writer.
 */
private void recursiveDOMWrite(Element element, Writer writer, boolean isRoot) throws IOException {
    SerializationUnit elementSU;
    NodeList children = element.getChildNodes();

    elementSU = getSerializationUnit(element, isRoot);
    try {
        if (elementSU != null) {
            elementSU.writeElementStart(element, writer, executionContext);
        }

        if (children != null && children.getLength() > 0) {
            int childCount = children.getLength();

            for (int i = 0; i < childCount; i++) {
                Node childNode = children.item(i);

                if (elementSU != null) {
                    switch (childNode.getNodeType()) {
                    case Node.CDATA_SECTION_NODE: {
                        elementSU.writeElementCDATA((CDATASection) childNode, writer, executionContext);
                        break;
                    }
                    case Node.COMMENT_NODE: {
                        elementSU.writeElementComment((Comment) childNode, writer, executionContext);
                        break;
                    }
                    case Node.ELEMENT_NODE: {
                        if (elementSU.writeChildElements()) {
                            recursiveDOMWrite((Element) childNode, writer, false);
                        }
                        break;
                    }
                    case Node.ENTITY_REFERENCE_NODE: {
                        elementSU.writeElementEntityRef((EntityReference) childNode, writer, executionContext);
                        break;
                    }
                    case Node.TEXT_NODE: {
                        elementSU.writeElementText((Text) childNode, writer, executionContext);
                        break;
                    }
                    default: {
                        elementSU.writeElementNode(childNode, writer, executionContext);
                        break;
                    }
                    }
                } else if (childNode.getNodeType() == Node.ELEMENT_NODE) {
                    recursiveDOMWrite((Element) childNode, writer, false);
                }
            }
        }
        if (elementSU != null) {
            elementSU.writeElementEnd(element, writer, executionContext);
        }
    } catch (Throwable thrown) {
        String error = "Failed to apply serialization unit [" + elementSU.getClass().getName() + "] to ["
                + executionContext.getDocumentSource() + ":" + DomUtils.getXPath(element) + "].";

        if (terminateOnVisitorException) {
            if (thrown instanceof SmooksException) {
                throw (SmooksException) thrown;
            } else {
                throw new SmooksException(error, thrown);
            }
        } else {
            logger.debug(error, thrown);
        }
    }
}

From source file:org.dhatim.delivery.dom.serialize.Serializer.java

/**
 * Recursively write the DOM tree to the supplied writer.
 * @param element Element to write.//from  w  ww.j  a v a  2 s . c  o m
 * @param writer Writer to use.
 * @throws IOException Exception writing to Writer.
 */
public static void recursiveDOMWrite(Element element, Writer writer) throws IOException {
    NodeList children = element.getChildNodes();

    try {
        defaultSerializer.writeElementStart(element, writer);

        if (children != null && children.getLength() > 0) {
            int childCount = children.getLength();

            for (int i = 0; i < childCount; i++) {
                Node childNode = children.item(i);

                switch (childNode.getNodeType()) {
                case Node.CDATA_SECTION_NODE: {
                    defaultSerializer.writeElementCDATA((CDATASection) childNode, writer, null);
                    break;
                }
                case Node.COMMENT_NODE: {
                    defaultSerializer.writeElementComment((Comment) childNode, writer, null);
                    break;
                }
                case Node.ELEMENT_NODE: {
                    recursiveDOMWrite((Element) childNode, writer);
                    break;
                }
                case Node.ENTITY_REFERENCE_NODE: {
                    defaultSerializer.writeElementEntityRef((EntityReference) childNode, writer, null);
                    break;
                }
                case Node.TEXT_NODE: {
                    defaultSerializer.writeElementText((Text) childNode, writer, null);
                    break;
                }
                default: {
                    defaultSerializer.writeElementNode(childNode, writer, null);
                    break;
                }
                }
            }
        }
        defaultSerializer.writeElementEnd(element, writer);
    } catch (Throwable thrown) {
        if (thrown instanceof SmooksException) {
            throw (SmooksException) thrown;
        } else {
            throw new SmooksException("Serailization Error.", thrown);
        }
    }
}

From source file:org.dhatim.xml.DomUtils.java

/**
 * Construct the XPath of the supplied DOM Node.
 * <p/>/*ww w  .j  a  v a 2  s .c om*/
 * Supports element, comment and cdata sections DOM Node types.
 * @param node DOM node for XPath generation.
 * @return XPath string representation of the supplied DOM Node.
 */
public static String getXPath(Node node) {
    AssertArgument.isNotNull(node, "node");

    StringBuffer xpath = new StringBuffer();
    Node parent = node.getParentNode();

    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        xpath.append(getXPathToken((Element) node));
        break;
    case Node.COMMENT_NODE:
        int commentNum = DomUtils.countNodesBefore(node, Node.COMMENT_NODE);
        xpath.append("/{COMMENT}[" + commentNum + 1 + "]");
        break;
    case Node.CDATA_SECTION_NODE:
        int cdataNum = DomUtils.countNodesBefore(node, Node.CDATA_SECTION_NODE);
        xpath.append("/{CDATA}[" + cdataNum + 1 + "]");
        break;
    default:
        throw new UnsupportedOperationException(
                "XPath generation for supplied DOM Node type not supported.  Only supports element, comment and cdata section DOM nodes.");
    }

    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE) {
        xpath.insert(0, getXPathToken((Element) parent));
        parent = parent.getParentNode();
    }

    return xpath.toString();
}

From source file:org.dhatim.xml.DomUtils.java

/**
* Get the combined text from all the text, comment and cdata DOM nodes
* contained within the supplied parent element. 
* @param parent The parent DOM element./* ww  w  .ja v  a  2s  . c  om*/
* @param removeEntities Remove all HTML entity and character references from
* the DOM Text child nodes and replace them with their equivalent characters.  Note
* this is not performed on Comment or CDATA section nodes.
* @return The combined (concatenated) contents of all child text, comment
* and cdata DOM nodes.  An empty String no such nodes are present.
*/
public static String getAllText(Element parent, boolean removeEntities) {
    AssertArgument.isNotNull(parent, "parent");

    NodeList children = parent.getChildNodes();
    StringBuffer text = new StringBuffer();
    int childCount = children.getLength();

    for (int i = 0; i < childCount; i++) {
        Node child = children.item(i);

        switch (child.getNodeType()) {
        case Node.TEXT_NODE:
            String data = ((Text) child).getData();
            if (removeEntities) {
                text.append(XmlUtil.removeEntities(data));
            } else {
                text.append(data);
            }
            break;
        case Node.CDATA_SECTION_NODE:
            // CDATA_SECTION_NODE nodes are a subtype of the Text node.
            text.append(((Text) child).getData());
            break;
        case Node.COMMENT_NODE:
            text.append(((Comment) child).getData());
            break;
        default:
            break;
        }
    }

    return text.toString();
}

From source file:org.erdc.cobie.shared.spreadsheetml.transformation.cobietab.COBieSpreadSheet.java

License:asdf

public static void nodeToStream(Node node, PrintWriter out) {
    String workSheetName = "";
    boolean canonical = false;
    // is there anything to do?
    if (node == null) {
        return;//ww  w. j a va  2  s .c o  m
    }

    int type = node.getNodeType();
    switch (type) {
    // print document
    case Node.DOCUMENT_NODE: {
        if (!canonical) {
            out.println("<?xml version=\"1.0\"?>");
        }
        // print(((Document)node).getDocumentElement());

        NodeList children = node.getChildNodes();
        for (int iChild = 0; iChild < children.getLength(); iChild++) {
            nodeToStream(children.item(iChild), out);
        }
        out.flush();
        break;
    }

    // print element with attributes
    case Node.ELEMENT_NODE: {
        out.print('<');
        out.print(node.getNodeName());
        Attr attrs[] = sortAttributes(node.getAttributes());
        for (int i = 0; i < attrs.length; i++) {
            Attr attr = attrs[i];
            if (((node.getNodeName().equalsIgnoreCase("Worksheet")
                    || node.getNodeName().equalsIgnoreCase("ss:Worksheet"))
                    && attr.getName().equalsIgnoreCase("Name")) || attr.getName().equalsIgnoreCase("ss:Name")) {
                workSheetName = normalize(attr.getNodeValue());
            }
            out.print(' ');
            out.print(attr.getNodeName());
            out.print("=\"");
            out.print(normalize(attr.getNodeValue()));
            out.print('"');
        }
        out.print('>');
        out.flush();
        NodeList children = node.getChildNodes();
        if (children != null) {
            int len = children.getLength();
            for (int i = 0; i < len; i++) {
                nodeToStream(children.item(i), out);
            }
        }
        break;
    }

    // handle entity reference nodes
    case Node.ENTITY_REFERENCE_NODE: {
        if (canonical) {
            NodeList children = node.getChildNodes();
            if (children != null) {
                int len = children.getLength();
                for (int i = 0; i < len; i++) {
                    nodeToStream(children.item(i), out);
                }
            }
        } else {
            out.print('&');
            out.print(node.getNodeName());
            out.print(';');
        }
        break;
    }

    // print cdata sections
    case Node.CDATA_SECTION_NODE: {
        if (canonical) {
            out.print(normalize(node.getNodeValue()));
        } else {
            out.print("<![CDATA[");
            out.print(node.getNodeValue());
            out.print("]]>");
        }
        break;
    }

    // print text
    case Node.TEXT_NODE: {
        out.print(normalize(node.getNodeValue()));
        break;
    }

    // print processing instruction
    case Node.PROCESSING_INSTRUCTION_NODE: {
        out.print("<?");
        out.print(node.getNodeName());
        String data = node.getNodeValue();
        if ((data != null) && (data.length() > 0)) {
            out.print(' ');
            out.print(data);
        }
        out.print("?>");
        break;
    }

    // print comment
    case Node.COMMENT_NODE: {
        out.print("<!--");
        String data = node.getNodeValue();
        if (data != null) {
            out.print(data);
        }
        out.print("-->");
        break;
    }
    }

    if (type == Node.ELEMENT_NODE) {
        if ((node.getNodeName().equalsIgnoreCase("Worksheet")
                || node.getNodeName().equalsIgnoreCase("ss:Worksheet")) && (workSheetName.length() > 0)) {
            out.print(printCOBieSheetDataValidation(workSheetName));
        }
        out.print("</");
        out.print(node.getNodeName());
        out.print('>');
    }

    out.flush();

}

From source file:org.exist.dom.ElementImpl.java

private Node appendChild(Txn transaction, NodeId newNodeId, NodeImplRef last, NodePath lastPath, Node child,
        StreamListener listener) throws DOMException {
    if (last == null || last.getNode() == null)
    //TODO : same test as above ? -pb
    {/*from w w w  .j  a  va  2s  .c  o m*/
        throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "invalid node");
    }
    final DocumentImpl owner = (DocumentImpl) getOwnerDocument();
    DBBroker broker = null;
    try {
        broker = ownerDocument.getBrokerPool().get(null);
        switch (child.getNodeType()) {
        case Node.DOCUMENT_FRAGMENT_NODE:
            appendChildren(transaction, newNodeId, null, last, lastPath, child.getChildNodes(), listener);
            return null; // TODO: implement document fragments so
        //we can return all newly appended children
        case Node.ELEMENT_NODE:
            // create new element
            final ElementImpl elem = new ElementImpl(
                    new QName(child.getLocalName() == null ? child.getNodeName() : child.getLocalName(),
                            child.getNamespaceURI(), child.getPrefix()),
                    broker.getBrokerPool().getSymbols());
            elem.setNodeId(newNodeId);
            elem.setOwnerDocument(owner);
            final NodeListImpl ch = new NodeListImpl();
            final NamedNodeMap attribs = child.getAttributes();
            int numActualAttribs = 0;
            for (int i = 0; i < attribs.getLength(); i++) {
                final Attr attr = (Attr) attribs.item(i);
                if (!attr.getNodeName().startsWith("xmlns")) {
                    ch.add(attr);
                    numActualAttribs++;
                } else {
                    final String xmlnsDecl = attr.getNodeName();
                    final String prefix = xmlnsDecl.length() == 5 ? "" : xmlnsDecl.substring(6);
                    elem.addNamespaceMapping(prefix, attr.getNodeValue());
                }
            }
            final NodeList cl = child.getChildNodes();
            for (int i = 0; i < cl.getLength(); i++) {
                final Node n = cl.item(i);
                if (n.getNodeType() != Node.ATTRIBUTE_NODE) {
                    ch.add(n);
                }
            }
            elem.setChildCount(ch.getLength());
            if (numActualAttribs != (short) numActualAttribs) {
                throw new DOMException(DOMException.INVALID_MODIFICATION_ERR, "Too many attributes");
            }
            elem.setAttributes((short) numActualAttribs);
            lastPath.addComponent(elem.getQName());
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), elem);
            broker.indexNode(transaction, elem, lastPath);
            broker.getIndexController().indexNode(transaction, elem, lastPath, listener);
            elem.setChildCount(0);
            last.setNode(elem);
            //process child nodes
            elem.appendChildren(transaction, newNodeId.newChild(), null, last, lastPath, ch, listener);
            broker.endElement(elem, lastPath, null);
            broker.getIndexController().endElement(transaction, elem, lastPath, listener);
            lastPath.removeLastComponent();
            return elem;
        case Node.TEXT_NODE:
            final TextImpl text = new TextImpl(newNodeId, ((Text) child).getData());
            text.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), text);
            broker.indexNode(transaction, text, lastPath);
            broker.getIndexController().indexNode(transaction, text, lastPath, listener);
            last.setNode(text);
            return text;
        case Node.CDATA_SECTION_NODE:
            final CDATASectionImpl cdata = new CDATASectionImpl(newNodeId, ((CDATASection) child).getData());
            cdata.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), cdata);
            broker.indexNode(transaction, cdata, lastPath);
            last.setNode(cdata);
            return cdata;
        case Node.ATTRIBUTE_NODE:
            final Attr attr = (Attr) child;
            final String ns = attr.getNamespaceURI();
            final String prefix = (Namespaces.XML_NS.equals(ns) ? "xml" : attr.getPrefix());
            String name = attr.getLocalName();
            if (name == null) {
                name = attr.getName();
            }
            final QName attrName = new QName(name, ns, prefix);
            final AttrImpl attrib = new AttrImpl(attrName, attr.getValue(),
                    broker.getBrokerPool().getSymbols());
            attrib.setNodeId(newNodeId);
            attrib.setOwnerDocument(owner);
            if (ns != null && attrName.compareTo(Namespaces.XML_ID_QNAME) == Constants.EQUAL) {
                // an xml:id attribute. Normalize the attribute and set its type to ID
                attrib.setValue(StringValue.trimWhitespace(StringValue.collapseWhitespace(attrib.getValue())));
                attrib.setType(AttrImpl.ID);
            } else {
                attrName.setNameType(ElementValue.ATTRIBUTE);
            }
            broker.insertNodeAfter(transaction, last.getNode(), attrib);
            broker.indexNode(transaction, attrib, lastPath);
            broker.getIndexController().indexNode(transaction, attrib, lastPath, listener);
            last.setNode(attrib);
            return attrib;
        case Node.COMMENT_NODE:
            final CommentImpl comment = new CommentImpl(((Comment) child).getData());
            comment.setNodeId(newNodeId);
            comment.setOwnerDocument(owner);
            // insert the node
            broker.insertNodeAfter(transaction, last.getNode(), comment);
            broker.indexNode(transaction, comment, lastPath);
            last.setNode(comment);
            return comment;
        case Node.PROCESSING_INSTRUCTION_NODE:
            final ProcessingInstructionImpl pi = new ProcessingInstructionImpl(newNodeId,
                    ((ProcessingInstruction) child).getTarget(), ((ProcessingInstruction) child).getData());
            pi.setOwnerDocument(owner);
            //insert the node
            broker.insertNodeAfter(transaction, last.getNode(), pi);
            broker.indexNode(transaction, pi, lastPath);
            last.setNode(pi);
            return pi;
        default:
            throw new DOMException(DOMException.INVALID_MODIFICATION_ERR,
                    "Unknown node type: " + child.getNodeType() + " " + child.getNodeName());
        }
    } catch (final EXistException e) {
        LOG.warn("Exception while appending node: " + e.getMessage(), e);
    } finally {
        if (broker != null)
            broker.release();
    }
    return null;
}

From source file:org.exist.http.SOAPServer.java

/**
 * Writes the value of a parameter for an XQuery function call
 * /*from   www.  ja  v  a 2 s. c om*/
 * @param param   This StringBuffer contains the serialization of the value for XQuery
 * @param nParamSeqItem   The parameter value node from the SOAP Message
 * @param prefix   The prefix for the value (casting syntax)
 * @param postfix   The postfix for the value (casting syntax)
 * @param isAtomic   Whether the value of this type should be atomic or not (or even both)
 */
private void processParameterValue(StringBuffer param, Node nParamSeqItem, String prefix, String postfix,
        int isAtomic) throws XPathException {
    boolean justOnce = false;
    final StringBuilder whiteContent = new StringBuilder();

    try {
        final Transformer tr = TransformerFactory.newInstance().newTransformer();
        tr.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        Node n = nParamSeqItem.getFirstChild();
        final StringWriter sw = new StringWriter();
        final StreamResult result = new StreamResult(sw);
        final StringBuffer psw = sw.getBuffer();
        while (n != null) {
            switch (n.getNodeType()) {
            case Node.ELEMENT_NODE:
                if (isAtomic > 0) {
                    throw new Exception(
                            "Content of " + nParamSeqItem.getNodeName() + " must be an atomic value");
                }
                isAtomic = -1;
                if (justOnce) {
                    throw new Exception(nParamSeqItem.getNodeName() + " must have ONLY ONE element child");
                }
                final DOMSource source = new DOMSource(n);
                tr.transform(source, result);
                // Only once!
                justOnce = true;
                break;
            case Node.TEXT_NODE:
            case Node.CDATA_SECTION_NODE:
                final String nodeValue = n.getNodeValue();
                final boolean isNotWhite = !nodeValue.matches("[ \n\r\t]+");
                if (isAtomic >= 0) {
                    if (isNotWhite || isAtomic > 0) {
                        if (isAtomic == 0) {
                            isAtomic = 1;
                        }
                        psw.append(nodeValue);
                    } else if (isAtomic == 0) {
                        whiteContent.append(nodeValue);
                    }
                } else if (isNotWhite) {
                    throw new Exception(nParamSeqItem.getNodeName()
                            + " has mixed content, but it must have only one element child");
                }
                break;
            }
            n = n.getNextSibling();
        }
        if (isAtomic >= 0) {
            param.append(prefix);
        }
        if (isAtomic == 0) {
            param.append(whiteContent);
        } else {
            param.append(psw);
        }
        if (isAtomic >= 0) {
            param.append(postfix);
        }
    } catch (final Exception e) {
        LOG.debug(e.getMessage());
        throw new XPathException(e.getMessage());
    }
}