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:com.twinsoft.convertigo.beans.core.Step.java

protected String getNodeValue(Node node) {
    if (node != null) {
        int len;/*from  ww  w  . j a v a  2s. c  o  m*/
        int nodeType = node.getNodeType();
        switch (nodeType) {
        case Node.ELEMENT_NODE:
            if (sequence.getProject().isStrictMode()) {
                return XMLUtils.prettyPrintElement((Element) node, true, false);
            } else {
                len = node.getChildNodes().getLength();
                Node firstChild = node.getFirstChild();
                if (firstChild != null) {
                    int firstChildType = firstChild.getNodeType();
                    switch (firstChildType) {
                    case Node.CDATA_SECTION_NODE:
                    case Node.TEXT_NODE:
                        return ((len < 2) ? firstChild.getNodeValue() : XMLUtils.getNormalizedText(node));
                    case Node.ELEMENT_NODE:
                        return XMLUtils.prettyPrintElement((Element) node, true, false);
                    default:
                        return null;
                    }
                } else {
                    if (Engine.logBeans.isInfoEnabled())
                        Engine.logBeans.warn("Applied XPath on step '" + this
                                + "' returned node with null value ('" + node.getNodeName() + "')");
                    return null;
                }
            }
        case Node.CDATA_SECTION_NODE:
        case Node.TEXT_NODE:
            len = node.getChildNodes().getLength();
            return ((len < 2) ? node.getNodeValue() : XMLUtils.getNormalizedText(node));
        case Node.ATTRIBUTE_NODE:
            return node.getNodeValue();
        default:
            if (Engine.logBeans.isInfoEnabled())
                Engine.logBeans.warn("Applied XPath on step '" + this + "' is not supported");
            return null;
        }
    }
    return null;
}

From source file:com.enonic.vertical.engine.handlers.MenuHandler.java

private void buildDocumentTypeXML(Element menuitemElem, Element documentElem) {

    if (documentElem != null) {
        if (verticalProperties.isStoreXHTMLOn()) {
            Node n = documentElem.getFirstChild();
            if (n != null && n.getNodeType() == Node.CDATA_SECTION_NODE) {
                int menuItemKey = Integer.parseInt(menuitemElem.getAttribute("key"));
                String menuItemName = XMLTool.getElementText(XMLTool.getElement(menuitemElem, "name"));
                Document doc = menuitemElem.getOwnerDocument();
                String docString = XMLTool.getElementText(documentElem);
                documentElem.removeChild(n);
                XMLTool.createXHTMLNodes(doc, documentElem, docString, true);
                String menuKey = menuitemElem.getAttribute("menukey");
                VerticalAdminLogger.error(this.getClass(), 0,
                        "Received invalid XML from database, menukey=" + menuKey + ", menuitem key="
                                + menuItemKey + ", name=" + menuItemName + ". Running Tidy..",
                        null);//from   www  .j a  v  a 2  s. c  o m
            }
            documentElem.setAttribute("mode", "xhtml");
        } else {
            Node n = documentElem.getFirstChild();
            if (n == null) {
                Document doc = menuitemElem.getOwnerDocument();
                XMLTool.createCDATASection(doc, menuitemElem, "Scratch document.");
            } else if (n.getNodeType() != Node.CDATA_SECTION_NODE) {
                Document doc = menuitemElem.getOwnerDocument();
                String docString = XMLTool.serialize(documentElem);
                XMLTool.createCDATASection(doc, documentElem, docString);
                VerticalEngineLogger.debug(this.getClass(), 0, "Expected CDATA, found XML. Serialized it.",
                        null);
            }
        }
    }
}

From source file:com.impetus.kundera.loader.PersistenceXMLLoader.java

/**
 * Get the content of the given element.
 * /*from w  w  w .ja  va2 s .  com*/
 * @param element
 *            The element to get the content for.
 * @param defaultStr
 *            The default to return when there is no content.
 * @return The content of the element or the default.
 * @throws Exception
 *             the exception
 */
private static String getElementContent(Element element, String defaultStr) {
    if (element == null) {
        return defaultStr;
    }

    NodeList children = element.getChildNodes();
    StringBuilder result = new StringBuilder("");
    for (int i = 0; i < children.getLength(); i++) {
        if (children.item(i).getNodeType() == Node.TEXT_NODE
                || children.item(i).getNodeType() == Node.CDATA_SECTION_NODE) {
            result.append(children.item(i).getNodeValue());
        }
    }
    return result.toString().trim();
}

From source file:com.mediaworx.xmlutils.XmlHelper.java

/**
 * Removes text nodes that are empty or contain whitespace only if the parent node has at least one child of any
 * of the following types: ELEMENT, CDATA, COMMENT. This is used to improve the XML format when using a transformer
 * to do the formatting (whitespace nodes are interfering with indentation and line breaks).
 * This method was modeled after a method by "user2401669" found on
 * <a href="http://stackoverflow.com/questions/16641835/strange-xml-indentation">StackOverflow</a>.
 *///from  w ww .  j a va2 s . c  o  m
public static void cleanEmptyTextNodes(Node parentNode) {
    boolean removeEmptyTextNodes = false;

    Node childNode = parentNode.getFirstChild();
    while (childNode != null) {
        short nodeType = childNode.getNodeType();

        if (nodeType == Node.ELEMENT_NODE || nodeType == Node.CDATA_SECTION_NODE
                || nodeType == Node.COMMENT_NODE) {
            removeEmptyTextNodes = true;
            if (nodeType == Node.ELEMENT_NODE) {
                cleanEmptyTextNodes(childNode); // recurse into subtree
            }
        }
        childNode = childNode.getNextSibling();
    }

    if (removeEmptyTextNodes) {
        removeEmptyTextNodes(parentNode);
    }
}

From source file:com.itelis.worker.dev.template.service.JRXmlDataSource.java

/**
 * Return the text that a node contains. This routine:
 * <ul>/* w  w  w .  j  av a2  s  .  c  o m*/
 * <li>Ignores comments and processing instructions.
 * <li>Concatenates TEXT nodes, CDATA nodes, and the results of recursively processing EntityRef nodes.
 * <li>Ignores any element nodes in the sublist. (Other possible options are to recurse into element sublists or throw an exception.)
 * </ul>
 * @param node a DOM node
 * @return a String representing node contents or null
 */
public String getText(Node node) {
    if (!node.hasChildNodes())
        return node.getNodeValue();

    StringBuffer result = new StringBuffer();

    NodeList list = node.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
        Node subnode = list.item(i);
        if (subnode.getNodeType() == Node.TEXT_NODE) {
            String value = subnode.getNodeValue();
            if (value != null)
                result.append(value);
        } else if (subnode.getNodeType() == Node.CDATA_SECTION_NODE) {
            String value = subnode.getNodeValue();
            if (value != null)
                result.append(value);
        } else if (subnode.getNodeType() == Node.ENTITY_REFERENCE_NODE) {
            // Recurse into the subtree for text
            // (and ignore comments)
            String value = getText(subnode);
            if (value != null)
                result.append(value);
        }
    }

    return result.toString();
}

From source file:com.esri.geoevent.solutions.adapter.cot.CoTAdapter.java

public static String elementToString(Node n) {

    String name = n.getNodeName();
    short type = n.getNodeType();

    if (Node.CDATA_SECTION_NODE == type) {
        return "<![CDATA[" + n.getNodeValue() + "]]&gt;";
    }//w  w w.  jav  a2 s .  co  m

    if (name.startsWith("#")) {
        return "";
    }

    StringBuffer sb = new StringBuffer();
    sb.append('<').append(name);

    NamedNodeMap attrs = n.getAttributes();
    if (attrs != null) {
        for (int i = 0; i < attrs.getLength(); i++) {
            Node attr = attrs.item(i);
            sb.append(' ').append(attr.getNodeName()).append("=\"").append(attr.getNodeValue()).append("\"");
        }
    }

    String textContent = null;
    NodeList children = n.getChildNodes();

    if (children.getLength() == 0) {
        if ((textContent = n.getTextContent()) != null && !"".equals(textContent)) {
            sb.append(textContent).append("</").append(name).append('>');
        } else {
            sb.append("/>").append('\n');
        }
    } else {
        sb.append('>').append('\n');
        boolean hasValidChildren = false;
        for (int i = 0; i < children.getLength(); i++) {
            String childToString = elementToString(children.item(i));
            if (!"".equals(childToString)) {
                sb.append(childToString);
                hasValidChildren = true;
            }
        }

        if (!hasValidChildren && ((textContent = n.getTextContent()) != null)) {
            sb.append(textContent);
        }

        sb.append("</").append(name).append('>');
    }

    return sb.toString();
}

From source file:com.twinsoft.convertigo.engine.util.XMLUtils.java

public static Object readObjectFromXml(Element node) throws Exception {
    String nodeName = node.getNodeName();
    String nodeValue = ((Element) node).getAttribute("value");

    if (nodeName.equals("java.lang.Boolean")) {
        return new Boolean(nodeValue);
    } else if (nodeName.equals("java.lang.Byte")) {
        return new Byte(nodeValue);
    } else if (nodeName.equals("java.lang.Character")) {
        return new Character(nodeValue.charAt(0));
    } else if (nodeName.equals("java.lang.Integer")) {
        return new Integer(nodeValue);
    } else if (nodeName.equals("java.lang.Double")) {
        return new Double(nodeValue);
    } else if (nodeName.equals("java.lang.Float")) {
        return new Float(nodeValue);
    } else if (nodeName.equals("java.lang.Long")) {
        return new Long(nodeValue);
    } else if (nodeName.equals("java.lang.Short")) {
        return new Short(nodeValue);
    } else if (nodeName.equals("java.lang.String")) {
        return nodeValue;
    } else if (nodeName.equals("array")) {
        String className = node.getAttribute("classname");
        String length = node.getAttribute("length");
        int len = (new Integer(length)).intValue();

        Object array;//from  w  w w  . ja  v a 2  s. c o  m
        if (className.equals("byte")) {
            array = new byte[len];
        } else if (className.equals("boolean")) {
            array = new boolean[len];
        } else if (className.equals("char")) {
            array = new char[len];
        } else if (className.equals("double")) {
            array = new double[len];
        } else if (className.equals("float")) {
            array = new float[len];
        } else if (className.equals("int")) {
            array = new int[len];
        } else if (className.equals("long")) {
            array = new long[len];
        } else if (className.equals("short")) {
            array = new short[len];
        } else {
            array = Array.newInstance(Class.forName(className), len);
        }

        Node xmlNode = null;
        NodeList nl = node.getChildNodes();
        int len_nl = nl.getLength();
        int i = 0;
        for (int j = 0; j < len_nl; j++) {
            xmlNode = nl.item(j);
            if (xmlNode.getNodeType() == Node.ELEMENT_NODE) {
                Object o = XMLUtils.readObjectFromXml((Element) xmlNode);
                Array.set(array, i, o);
                i++;
            }
        }

        return array;
    }
    // XMLization
    else if (nodeName.equals("xmlizable")) {
        String className = node.getAttribute("classname");

        Node xmlNode = findChildNode(node, Node.ELEMENT_NODE);
        Object xmlizable = Class.forName(className).newInstance();
        ((XMLizable) xmlizable).readXml(xmlNode);

        return xmlizable;
    }
    // Serialization
    else if (nodeName.equals("serializable")) {
        Node cdata = findChildNode(node, Node.CDATA_SECTION_NODE);
        String objectSerializationData = cdata.getNodeValue();
        Engine.logEngine.debug("Object serialization data:\n" + objectSerializationData);
        byte[] objectBytes = org.apache.commons.codec.binary.Base64.decodeBase64(objectSerializationData);

        // We read the object to a bytes array
        ByteArrayInputStream inputStream = new ByteArrayInputStream(objectBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        Object object = objectInputStream.readObject();
        inputStream.close();

        return object;
    }

    return null;
}

From source file:mondrian.test.DiffRepository.java

private static void writeNode(Node node, XMLOutput out) {
    final NodeList childNodes;
    switch (node.getNodeType()) {
    case Node.DOCUMENT_NODE:
        out.print("<?xml version=\"1.0\" ?>" + Util.nl);
        childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node child = childNodes.item(i);
            writeNode(child, out);/*from ww  w.  j  a va2s .c  o  m*/
        }
        //            writeNode(((Document) node).getDocumentElement(), out);
        break;

    case Node.ELEMENT_NODE:
        Element element = (Element) node;
        final String tagName = element.getTagName();
        out.beginBeginTag(tagName);
        // Attributes.
        final NamedNodeMap attributeMap = element.getAttributes();
        for (int i = 0; i < attributeMap.getLength(); i++) {
            final Node att = attributeMap.item(i);
            out.attribute(att.getNodeName(), att.getNodeValue());
        }
        out.endBeginTag(tagName);
        // Write child nodes, ignoring attributes but including text.
        childNodes = node.getChildNodes();
        for (int i = 0; i < childNodes.getLength(); i++) {
            Node child = childNodes.item(i);
            if (child.getNodeType() == Node.ATTRIBUTE_NODE) {
                continue;
            }
            writeNode(child, out);
        }
        out.endTag(tagName);
        break;

    case Node.ATTRIBUTE_NODE:
        out.attribute(node.getNodeName(), node.getNodeValue());
        break;

    case Node.CDATA_SECTION_NODE:
        CDATASection cdata = (CDATASection) node;
        out.cdata(cdata.getNodeValue(), true);
        break;

    case Node.TEXT_NODE:
        Text text = (Text) node;
        final String wholeText = text.getNodeValue();
        if (!isWhitespace(wholeText)) {
            out.cdata(wholeText, false);
        }
        break;

    case Node.COMMENT_NODE:
        Comment comment = (Comment) node;
        out.print("<!--" + comment.getNodeValue() + "-->" + Util.nl);
        break;

    default:
        throw new RuntimeException("unexpected node type: " + node.getNodeType() + " (" + node + ")");
    }
}

From source file:DOMProcessor.java

/** Searches for a given element in the given node and updates list
  * of text within matched elements. Recursively searches for sub-nodes
  * of the given one./*from  w  w  w.  j  a  v  a 2  s  .  c o m*/
  * @param element Element to search for. If null, all elements searched.
  * @param node Node to start search from.
  */
private void searchText(String element, Node node) {
    // Only consider document or element nodes.
    if ((node.getNodeType() != Node.DOCUMENT_NODE) && (node.getNodeType() != Node.ELEMENT_NODE)) {
        return;
    }

    if ((element == null) || (node.getNodeName().equalsIgnoreCase(element))) {
        // Match found so look for text in children.
        NodeList children = node.getChildNodes();

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

            if ((child.getNodeType() == Node.CDATA_SECTION_NODE) || (child.getNodeType() == Node.TEXT_NODE)) {
                if (child.getNodeValue().trim().length() > 0) {
                    //matches.add(child.getNodeValue());
                    matches.add(child);
                }
            }
        }
    }

    if ((node.getNodeType() == Node.DOCUMENT_NODE) || (node.getNodeType() == Node.ELEMENT_NODE)) {
        // Search child nodes.
        NodeList children = node.getChildNodes();

        for (int i = 0; i < children.getLength(); i++) {
            searchText(element, children.item(i));
        }
    }
}

From source file:com.enonic.vertical.engine.handlers.PageTemplateHandler.java

private Document createPageTemplatesDocument(Collection<PageTemplateEntity> pageTemplates) {
    Document doc = XMLTool.createDocument("pagetemplates");
    if (pageTemplates == null) {
        return doc;
    }//from  w  w  w  .  j  av a  2 s  .  co m

    for (PageTemplateEntity pageTemplate : pageTemplates) {
        Element root = doc.getDocumentElement();
        Document ptdDoc = null;

        org.jdom.Document pageTemplateXmlDataAsJdomDoc = pageTemplate.getXmlData();
        if (pageTemplateXmlDataAsJdomDoc != null) {
            ptdDoc = XMLDocumentFactory.create(pageTemplateXmlDataAsJdomDoc).getAsDOMDocument();
            Element docElem = XMLTool.getElement(ptdDoc.getDocumentElement(), "document");
            if (docElem != null) {
                Node firstChild = docElem.getFirstChild();
                if (firstChild == null || firstChild.getNodeType() != Node.CDATA_SECTION_NODE) {
                    docElem.setAttribute("mode", "xhtml");
                }
            }
        }

        Element elem = XMLTool.createElement(doc, root, "pagetemplate");
        elem.setAttribute("key", String.valueOf(pageTemplate.getKey()));
        elem.setAttribute("menukey", String.valueOf(pageTemplate.getSite().getKey()));

        // sub-elements
        XMLTool.createElement(doc, elem, "name", pageTemplate.getName());
        XMLTool.createElement(doc, elem, "description", pageTemplate.getDescription());
        Element tmp = XMLTool.createElement(doc, elem, "stylesheet");
        tmp.setAttribute("stylesheetkey", pageTemplate.getStyleKey().toString());
        tmp.setAttribute("exists",
                resourceDao.getResourceFile(pageTemplate.getStyleKey()) != null ? "true" : "false");

        // element conobjects for pagetemplate
        Document contentobj = getPageTemplateCO(pageTemplate);
        elem.appendChild(doc.importNode(contentobj.getDocumentElement(), true));

        // get page template parameters
        Document ptpDoc = getPageTemplParams(pageTemplate);
        Node ptpNode = doc.importNode(ptpDoc.getDocumentElement(), true);
        elem.appendChild(ptpNode);

        // element timestamp
        XMLTool.createElement(doc, elem, "timestamp",
                CalendarUtil.formatTimestamp(pageTemplate.getTimestamp(), true));

        // element: pagetemplatedata
        if (ptdDoc != null) {
            elem.appendChild(doc.importNode(ptdDoc.getDocumentElement(), true));
        }

        // element: css
        ResourceKey cssKey = pageTemplate.getCssKey();
        if (cssKey != null) {
            tmp = XMLTool.createElement(doc, elem, "css");
            tmp.setAttribute("stylesheetkey", cssKey.toString());
            tmp.setAttribute("exists", resourceDao.getResourceFile(cssKey) != null ? "true" : "false");
        }

        // attribute: runAs & defaultRunAsUser
        elem.setAttribute("runAs", pageTemplate.getRunAs().toString());
        UserEntity defaultRunAsUser = pageTemplate.getSite().resolveDefaultRunAsUser();
        String defaultRunAsUserName = "NA";
        if (defaultRunAsUser != null) {
            defaultRunAsUserName = defaultRunAsUser.getDisplayName();
        }
        elem.setAttribute("defaultRunAsUser", defaultRunAsUserName);

        // attribute: type
        elem.setAttribute("type", pageTemplate.getType().getName());

        // contenttypes
        int[] contentTypes = getContentTypesByPageTemplate(pageTemplate);
        Document contentTypesDoc = getContentHandler().getContentTypesDocument(contentTypes);
        XMLTool.mergeDocuments(elem, contentTypesDoc, true);
    }

    return doc;
}