Example usage for org.dom4j Node CDATA_SECTION_NODE

List of usage examples for org.dom4j Node CDATA_SECTION_NODE

Introduction

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

Prototype

short CDATA_SECTION_NODE

To view the source code for org.dom4j Node CDATA_SECTION_NODE.

Click Source Link

Document

Matches elements nodes

Usage

From source file:org.apereo.portal.io.xml.SpELDataTemplatingStrategy.java

License:Apache License

@Override
public Source processTemplates(Document data, String filename) {

    log.trace("Processing templates for document XML={}", data.asXML());
    for (String xpath : XPATH_EXPRESSIONS) {
        @SuppressWarnings("unchecked")
        List<Node> nodes = data.selectNodes(xpath);
        for (Node n : nodes) {
            String inpt, otpt;//from   w  ww.ja va2s . c o m
            switch (n.getNodeType()) {
            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                Attribute a = (Attribute) n;
                inpt = a.getValue();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    a.setValue(otpt);
                }
                break;
            case org.w3c.dom.Node.TEXT_NODE:
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
                inpt = n.getText();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    n.setText(otpt);
                }
                break;
            default:
                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                throw new RuntimeException(msg);
            }
        }
    }

    final SAXSource rslt = new DocumentSource(data);
    rslt.setSystemId(filename); // must be set, else import chokes
    return rslt;
}

From source file:org.codehaus.modello.plugin.utils.Dom4jUtils.java

License:Apache License

/**
 * Asserts that the specified {@link Node} is not a {@link Node#TEXT_NODE}
 * or {@link Node#CDATA_SECTION_NODE}.//from   ww  w.ja  va  2  s.  co m
 * 
 * @param message Assertion message to print.
 * @param node Node to interrogate for {@link Node#TEXT_NODE} or
 *            {@link Node#CDATA_SECTION_NODE} property.
 * @param recursive <code>true</code> if the node is to be recursively
 *            searched, else <code>false</code>.
 * @return <code>true</code> if the specified {@link Node} is not of type
 *         {@link Node#TEXT_NODE} or {@link Node#CDATA_SECTION_NODE}
 */
public static boolean assertNoTextNode(String message, Node node, boolean recursive) {
    if (node.getNodeType() == Node.TEXT_NODE || node.getNodeType() == Node.CDATA_SECTION_NODE) {
        // Double check that it isn't just whitespace.
        String text = StringUtils.trim(node.getText());

        if (StringUtils.isNotEmpty(text)) {
            throw new AssertionFailedError(message + " found <" + text + ">");
        }
    }

    if (recursive) {
        if (node instanceof Branch) {
            Iterator it = ((Branch) node).nodeIterator();
            while (it.hasNext()) {
                Node child = (Node) it.next();
                assertNoTextNode(message, child, recursive);
            }
        }
    }

    return false;
}

From source file:org.hudsonci.xpath.impl.Dom2Dom.java

License:Open Source License

private org.w3c.dom.Node createChild(Node child, org.w3c.dom.Node wparent) {
    int type = child.getNodeType();

    // Collapse multiple consecutive text nodes to a single text node
    // with trimmed value.
    if (type != Node.TEXT_NODE)
        endText(wparent);/* w w  w  .  jav  a2s .c o m*/

    Name name;
    org.w3c.dom.Node node = null;

    switch (type) {
    case Node.ATTRIBUTE_NODE:
        break;
    case Node.CDATA_SECTION_NODE:
        CDATA cd = (CDATA) child;
        wparent.appendChild(node = wdoc.createCDATASection(cd.getText()));
        break;
    case Node.COMMENT_NODE:
        Comment co = (Comment) child;
        wparent.appendChild(node = wdoc.createComment(co.getText()));
        break;
    case Node.DOCUMENT_TYPE_NODE:
        DocumentType dt = (DocumentType) child;
        wparent.appendChild(new XDocumentType(dt, wparent));
        break;
    case Node.ELEMENT_NODE:
        Element el = (Element) child;
        name = new Name(el);
        org.w3c.dom.Element e = name.namespaceURI == null ? wdoc.createElement(name.qualifiedName)
                : wdoc.createElementNS(name.namespaceURI, name.qualifiedName);
        wparent.appendChild(e);
        node = currentElement = e;

        for (int i = 0, n = el.attributeCount(); i < n; i++) {
            Attribute at = el.attribute(i);
            name = new Name(at);
            if (name.namespaceURI == null)
                e.setAttribute(name.qualifiedName, at.getValue());
            else
                e.setAttributeNS(name.namespaceURI, name.qualifiedName, at.getValue());
        }
        return e;
    case Node.ENTITY_REFERENCE_NODE:
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        ProcessingInstruction p = (ProcessingInstruction) child;
        wparent.appendChild(node = wdoc.createProcessingInstruction(p.getTarget(), p.getText()));
        break;
    case Node.TEXT_NODE:
        textBuilder.append(child.getText());
        lastText = (Text) child;
        break;
    case Node.NAMESPACE_NODE:
        Namespace ns = (Namespace) child;
        name = new Name(ns);
        currentElement.setAttribute(name.qualifiedName, ns.getURI());
        break;
    default:
        throw new IllegalStateException("Unknown node type");
    }
    if (node != null)
        reverseMap.put(node, child);
    return null;
}

From source file:org.jasig.portal.io.xml.SpELDataTemplatingStrategy.java

License:Apache License

@Override
public Source processTemplates(Document data, String filename) {

    log.trace("Processing templates for document XML={}", data.asXML());
    for (String xpath : XPATH_EXPRESSIONS) {
        @SuppressWarnings("unchecked")
        List<Node> nodes = data.selectNodes(xpath);
        for (Node n : nodes) {
            String inpt, otpt;// w  w w. j  a v a2  s.c o m
            switch (n.getNodeType()) {
            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                Attribute a = (Attribute) n;
                inpt = a.getValue();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    a.setValue(otpt);
                }
                break;
            case org.w3c.dom.Node.TEXT_NODE:
            case org.w3c.dom.Node.CDATA_SECTION_NODE:
                inpt = n.getText();
                otpt = processText(inpt);
                if (otpt == null) {
                    throw new RuntimeException("Invalid expression '" + inpt + "' in file " + filename);
                }
                if (!otpt.equals(inpt)) {
                    n.setText(otpt);
                }
                break;
            default:
                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                throw new RuntimeException(msg);
            }
        }
    }

    final SAXSource rslt = new DocumentSource(data);
    rslt.setSystemId(filename); // must be set, else import chokes
    return rslt;

}

From source file:org.olat.ims.qti.qpool.QTIExportProcessor.java

License:Apache License

/**
 * Collect the file and rewrite the /*  ww w .  j a va 2s .co m*/
 * @param el
 * @param container
 * @param materials
 * @param paths
 */
private void collectResourcesInMatText(Element el, VFSContainer container, ItemsAndMaterials materials) {
    //mattext
    @SuppressWarnings("unchecked")
    List<Element> mattextList = el.selectNodes(".//mattext");
    for (Element mat : mattextList) {
        Attribute texttypeAttr = mat.attribute("texttype");
        String texttype = texttypeAttr.getValue();
        if ("text/html".equals(texttype)) {
            @SuppressWarnings("unchecked")
            List<Node> childElList = new ArrayList<Node>(mat.content());
            for (Node childEl : childElList) {
                mat.remove(childEl);
            }

            for (Node childEl : childElList) {
                if (Node.CDATA_SECTION_NODE == childEl.getNodeType()) {
                    CDATA data = (CDATA) childEl;
                    boolean changed = false;
                    String text = data.getText();
                    List<String> materialPaths = findMaterialInMatText(text);
                    for (String materialPath : materialPaths) {
                        VFSItem matVfsItem = container.resolve(materialPath);
                        if (matVfsItem instanceof VFSLeaf) {
                            String exportUri = generateExportPath(materials.getPaths(), matVfsItem);
                            materials.addMaterial(new ItemMaterial((VFSLeaf) matVfsItem, exportUri));
                            text = text.replaceAll(materialPath, exportUri);
                            changed = true;
                        }
                    }
                    if (changed) {
                        mat.addCDATA(text);
                    } else {
                        mat.add(childEl);
                    }
                } else {
                    mat.add(childEl);
                }
            }
        }
    }
}

From source file:org.openadaptor.auxil.convertor.map.Dom4JDocumentMapFacade.java

License:Open Source License

/** 
 * Extract value from a single node//from  www. j  a va2s  . c o  m
 * <br>
 * <UL>
 *  <LI>If an Element return the element reference.
 *  <LI>If an Attribute return the attribute value
 *  <LI>If text (or CDATA) return it.
 *  <LI>If null return null.
 * @param node Node from which to extract a value
 * @return Reference to Element, or String representation of value.
 */
private Object getSingleValuedResult(Node node) {
    Object result = null;
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        result = (Element) node;
        break;
    case Node.ATTRIBUTE_NODE:
        result = ((Attribute) node).getValue();
        break;
    case Node.TEXT_NODE:
    case Node.CDATA_SECTION_NODE: //Not sure about this one!
        result = node.getText();
        break;
    }
    return result;
}

From source file:org.opencms.importexport.CmsXmlPageConverter.java

License:Open Source License

/**
 * Converts the contents of a page into an xml page.<p>
 * //from ww  w .j a  v  a 2  s  .co m
 * @param cms the cms object
 * @param content the content used with xml templates
 * @param locale the locale of the body element(s)
 * @param encoding the encoding to the xml page
 * @return the xml page content or null if conversion failed
 * @throws CmsImportExportException if the body content or the XMLTEMPLATE element were not found
 * @throws CmsXmlException if there is an error reading xml contents from the byte array into a document
 */
public static CmsXmlPage convertToXmlPage(CmsObject cms, byte[] content, Locale locale, String encoding)
        throws CmsImportExportException, CmsXmlException {

    CmsXmlPage xmlPage = null;

    Document page = CmsXmlUtils.unmarshalHelper(content, null);

    Element xmltemplate = page.getRootElement();
    if ((xmltemplate == null) || !"XMLTEMPLATE".equals(xmltemplate.getName())) {
        throw new CmsImportExportException(Messages.get().container(Messages.ERR_NOT_FOUND_ELEM_XMLTEMPLATE_0));
    }

    // get all edittemplate nodes
    Iterator i = xmltemplate.elementIterator("edittemplate");
    boolean useEditTemplates = true;
    if (!i.hasNext()) {
        // no edittemplate nodes found, get the template nodes
        i = xmltemplate.elementIterator("TEMPLATE");
        useEditTemplates = false;
    }

    // now create the XML page
    xmlPage = new CmsXmlPage(locale, encoding);

    while (i.hasNext()) {
        Element currentTemplate = (Element) i.next();
        String bodyName = currentTemplate.attributeValue("name");
        if (CmsStringUtil.isEmpty(bodyName)) {
            // no template name found, use the parameter body name
            bodyName = "body";
        }
        String bodyContent = null;

        if (useEditTemplates) {
            // no content manipulation needed for edittemplates
            bodyContent = currentTemplate.getText();
        } else {
            // parse content for TEMPLATEs
            StringBuffer contentBuffer = new StringBuffer();
            for (Iterator k = currentTemplate.nodeIterator(); k.hasNext();) {
                Node n = (Node) k.next();
                if (n.getNodeType() == Node.CDATA_SECTION_NODE) {
                    contentBuffer.append(n.getText());
                    continue;
                } else if (n.getNodeType() == Node.ELEMENT_NODE) {
                    if ("LINK".equals(n.getName())) {
                        contentBuffer.append(OpenCms.getSystemInfo().getOpenCmsContext());
                        contentBuffer.append(n.getText());
                        continue;
                    }
                }
            }
            bodyContent = contentBuffer.toString();
        }

        if (bodyContent == null) {
            throw new CmsImportExportException(Messages.get().container(Messages.ERR_BODY_CONTENT_NOT_FOUND_0));
        }

        bodyContent = CmsStringUtil.substitute(bodyContent, CmsStringUtil.MACRO_OPENCMS_CONTEXT,
                OpenCms.getSystemInfo().getOpenCmsContext());

        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(bodyContent)) {
            xmlPage.addValue(bodyName, locale);
            xmlPage.setStringValue(cms, bodyName, locale, bodyContent);
        }
    }

    return xmlPage;

}

From source file:org.zenonpagetemplates.onePhaseImpl.PageTemplateImpl.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
private void defaultContent(Element element, ContentHandler contentHandler, LexicalHandler lexicalHandler,
        EvaluationHelper evaluationHelper, Stack<Map<String, Slot>> slotStack)
        throws SAXException, PageTemplateException, IOException, EvaluationException {
    // Use default template content
    for (Iterator<Node> i = element.nodeIterator(); i.hasNext();) {
        Node node = i.next();/*w  w  w.j  av  a  2s.c  o  m*/
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            processElement((Element) node, contentHandler, lexicalHandler, evaluationHelper, slotStack);
            break;

        case Node.TEXT_NODE:
            char[] text = node.getText().toCharArray();
            contentHandler.characters(text, 0, text.length);
            break;

        case Node.COMMENT_NODE:
            char[] comment = node.getText().toCharArray();
            lexicalHandler.comment(comment, 0, comment.length);
            break;

        case Node.CDATA_SECTION_NODE:
            lexicalHandler.startCDATA();
            char[] cdata = node.getText().toCharArray();
            contentHandler.characters(cdata, 0, cdata.length);
            lexicalHandler.endCDATA();
            break;

        case Node.NAMESPACE_NODE:
            Namespace declared = (Namespace) node;
            //System.err.println( "Declared namespace: " + declared.getPrefix() + ":" + declared.getURI() );
            this.namespaces.put(declared.getPrefix(), declared.getURI());
            //if ( declared.getURI().equals( TAL_NAMESPACE_URI ) ) {
            //    this.talNamespacePrefix = declared.getPrefix();
            //} 
            //else if (declared.getURI().equals( METAL_NAMESPACE_URI ) ) {
            //    this.metalNamespacePrefix = declared.getPrefix();
            //}
            break;

        case Node.ATTRIBUTE_NODE:
            // Already handled
            break;

        case Node.DOCUMENT_TYPE_NODE:
        case Node.ENTITY_REFERENCE_NODE:
        case Node.PROCESSING_INSTRUCTION_NODE:
        default:
            //System.err.println( "WARNING: Node type not supported: " + node.getNodeTypeName() );       
        }
    }
}

From source file:org.zenonpagetemplates.twoPhasesImpl.ZPTDocumentFactory.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
static private void mapContent(Element element, ZPTElement zptElement, ZPTDocument zptDocument,
        Stack<Map<String, Slot>> slotStack) throws SAXException, PageTemplateException, IOException {

    // Use default template content
    for (Iterator<Node> i = element.nodeIterator(); i.hasNext();) {
        Node node = i.next();/*from  w  ww . ja v a  2  s . c o m*/
        switch (node.getNodeType()) {
        case Node.ELEMENT_NODE:
            zptElement.addContent(getNewZPTElement((Element) node, zptDocument, slotStack));
            break;

        case Node.TEXT_NODE:
            zptElement.addContent(new TextNode(node.getText()));
            break;

        case Node.CDATA_SECTION_NODE:
            zptElement.addContent(new CDATANode(node.getText()));
            break;

        case Node.NAMESPACE_NODE: // Already handled
            /*
             Namespace declared = (Namespace)node;
             if (zptDocument.isNamespaceToDeclare(declared)){
                zptDocument.addNamespace(declared);
             } else {
                zptElement.addNamespaceStaticAttribute(declared);
             }
             break;*/

        case Node.ATTRIBUTE_NODE: // Already handled
        case Node.COMMENT_NODE: // Remove all comments
        case Node.DOCUMENT_TYPE_NODE:
        case Node.ENTITY_REFERENCE_NODE:
        case Node.PROCESSING_INSTRUCTION_NODE:
        default:
            // Nothing to do
        }
    }
}

From source file:ru.apertum.qsystem.client.forms.FBoardParams.java

License:Open Source License

/**
 *     XML// ww w .  j a  v a2s  .c  o  m
 */
private void saveXML() {
    if (params != null) {
        if (Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_FRACTAL).size() > 0) {
            Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_FRACTAL).get(0)
                    .addAttribute(Uses.TAG_BOARD_VALUE, tfFRactal.getText());
        }
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_RUNNING_TEXT).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, textFieldRunning.getText());
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_FON_IMG).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, textFieldPict.getText());
        //    CDATA
        for (int i = 0; i < params.nodeCount(); i++) {
            final Node node = params.node(i);
            if (node.getNodeType() == Node.CDATA_SECTION_NODE) {
                params.remove(node);
            }
        }
        final String str = textAreaHtml.getText();
        if (!"".equals(str)) {
            params.addCDATA(str);
        }
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_VIDEO_FILE).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, textFieldVideo.getText());
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_FONT_SIZE).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, String.valueOf((Integer) spinnerFontSize.getValue()));
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_SPEED_TEXT).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, String.valueOf((Integer) spinnerSpeed.getValue()));
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_FONT_COLOR).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, textFieldFontColor.getText());
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_SIMPLE_DATE).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, checkBoxDate.isSelected() ? "1" : "0");
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_GRID_NEXT).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, checkBoxGridNext.isSelected() ? "1" : "0");
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_GRID_NEXT_COLS).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, String.valueOf((Integer) spinnerGridNextCols.getValue()));
        Uses.elementsByAttr(params, Uses.TAG_BOARD_NAME, Uses.TAG_BOARD_GRID_NEXT_ROWS).get(0)
                .addAttribute(Uses.TAG_BOARD_VALUE, String.valueOf((Integer) spinnerGridNextRows.getValue()));

    }
}