Example usage for org.dom4j Node TEXT_NODE

List of usage examples for org.dom4j Node TEXT_NODE

Introduction

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

Prototype

short TEXT_NODE

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

Click Source Link

Document

Matches elements nodes

Usage

From source file:net.unicon.warlock.fac.AbstractWarlockFactory.java

License:Open Source License

private static ILayoutElement parseLayoutElement(Node n, IWarlockFactory owner) throws WarlockException {

    // Assertions.
    if (n == null) {
        String msg = "Argument 'n [Node]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }/*from  w  w  w .j ava2  s. c  o m*/
    if (owner == null) {
        String msg = "Argument 'owner' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    ILayoutElement rslt = null;

    // Choose which type to create.
    switch (n.getNodeType()) {

    case Node.TEXT_NODE:
        rslt = IgnoredLayoutText.parse(n);
        break;
    case Node.ELEMENT_NODE:
        Element e = (Element) n;
        String tagName = e.getName();
        if (tagName.equals("value-of")) {
            rslt = XpathValue.parse(e);
        } else if (tagName.equals("copy-of")) {
            rslt = CopyOf.parse(e);
        } else if (tagName.equals("call-template")) {
            rslt = TemplateCall.parse(e);
        } else {
            rslt = IgnoredLayoutElement.parse(e, owner);
        }
        break;
    default:
        rslt = EmptyLayoutElement.INSTANCE;
        break;
    }

    return rslt;

}

From source file:nl.tue.gale.ae.processor.xmlmodule.CreoleTextHandler.java

License:Open Source License

@SuppressWarnings("unchecked")
private void traverse(Element textElement) {
    boolean flat = ("true".equals(textElement.attributeValue("flat")));
    List<Element> elements = ImmutableList.copyOf((List<Element>) textElement.elements());
    for (Element element : elements) {
        textElement.content().add(textElement.content().indexOf(element),
                DocumentFactory.getInstance().createText("(% " + GaleUtil.serializeXML(element) + " %)"));
        textElement.remove(element);/*from   www  . ja v a  2s.c  o  m*/
    }
    textElement.normalize();
    List<Node> content = ImmutableList.copyOf((List<Node>) textElement.content());
    for (Node node : content)
        if (node.getNodeType() == Node.TEXT_NODE) {
            textElement.content().addAll(textElement.content().indexOf(node), parse(node.getText(), flat));
            textElement.content().remove(node);
        }
}

From source file:nl.tue.gale.ae.processor.xmlmodule.RepositoryModule.java

License:Open Source License

private void removeTextNodes(Element element) {
    @SuppressWarnings("unchecked")
    List<Node> content = (List<Node>) element.content();
    for (Node node : ImmutableList.copyOf(content))
        if (node.getNodeType() == Node.TEXT_NODE)
            content.remove(node);/*w w  w.  j a v  a 2  s. com*/
}

From source file:org.apache.maven.archetype.common.DefaultPomManager.java

License:Apache License

public void addModule(File pom, String artifactId)
        throws IOException, XmlPullParserException, DocumentException, InvalidPackaging {
    boolean found = false;

    StringWriter writer = new StringWriter();
    Reader fileReader = null;/*from   w w w .  ja  va  2 s.  c  o m*/

    try {
        fileReader = ReaderFactory.newXmlReader(pom);

        SAXReader reader = new SAXReader();
        Document document = reader.read(fileReader);
        Element project = document.getRootElement();

        String packaging = null;
        Element packagingElement = project.element("packaging");
        if (packagingElement != null) {
            packaging = packagingElement.getStringValue();
        }
        if (!"pom".equals(packaging)) {
            throw new InvalidPackaging(
                    "Unable to add module to the current project as it is not of packaging type 'pom'");
        }

        Element modules = project.element("modules");
        if (modules == null) {
            modules = project.addText("  ").addElement("modules");
            modules.setText("\n  ");
            project.addText("\n");
        }
        // TODO: change to while loop
        for (@SuppressWarnings("unchecked")
        Iterator<Element> i = modules.elementIterator("module"); i.hasNext() && !found;) {
            Element module = i.next();
            if (module.getText().equals(artifactId)) {
                found = true;
            }
        }
        if (!found) {
            Node lastTextNode = null;
            for (@SuppressWarnings("unchecked")
            Iterator<Node> i = modules.nodeIterator(); i.hasNext();) {
                Node node = i.next();
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    lastTextNode = null;
                } else if (node.getNodeType() == Node.TEXT_NODE) {
                    lastTextNode = node;
                }
            }

            if (lastTextNode != null) {
                modules.remove(lastTextNode);
            }

            modules.addText("\n    ");
            modules.addElement("module").setText(artifactId);
            modules.addText("\n  ");

            XMLWriter xmlWriter = new XMLWriter(writer);
            xmlWriter.write(document);

            FileUtils.fileWrite(pom.getAbsolutePath(), writer.toString());
        } // end if
    } finally {
        IOUtil.close(fileReader);
    }
}

From source file:org.apache.maven.archetype.old.DefaultOldArchetype.java

License:Apache License

static boolean addModuleToParentPom(String artifactId, Reader fileReader, Writer fileWriter)
        throws DocumentException, IOException, ArchetypeTemplateProcessingException {
    SAXReader reader = new SAXReader();
    Document document = reader.read(fileReader);
    Element project = document.getRootElement();

    String packaging = null;/*w w  w.  j a va  2s .  co  m*/
    Element packagingElement = project.element("packaging");
    if (packagingElement != null) {
        packaging = packagingElement.getStringValue();
    }
    if (!"pom".equals(packaging)) {
        throw new ArchetypeTemplateProcessingException(
                "Unable to add module to the current project as it is not of packaging type 'pom'");
    }

    Element modules = project.element("modules");
    if (modules == null) {
        modules = project.addText("  ").addElement("modules");
        modules.setText("\n  ");
        project.addText("\n");
    }
    boolean found = false;
    for (Iterator<?> i = modules.elementIterator("module"); i.hasNext() && !found;) {
        Element module = (Element) i.next();
        if (module.getText().equals(artifactId)) {
            found = true;
        }
    }
    if (!found) {
        Node lastTextNode = null;
        for (Iterator<?> i = modules.nodeIterator(); i.hasNext();) {
            Node node = (Node) i.next();
            if (node.getNodeType() == Node.ELEMENT_NODE) {
                lastTextNode = null;
            } else if (node.getNodeType() == Node.TEXT_NODE) {
                lastTextNode = node;
            }
        }

        if (lastTextNode != null) {
            modules.remove(lastTextNode);
        }

        modules.addText("\n    ");
        modules.addElement("module").setText(artifactId);
        modules.addText("\n  ");

        XMLWriter writer = new XMLWriter(fileWriter);
        writer.write(document);
    }
    return !found;
}

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;// w w w .j  a va  2s  . com
            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 .  j ava 2  s .c  o 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);//from  w ww .  j ava2s .co 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 ww.  j av  a2s.co 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.jasig.portal.tenants.TemplateDataTenantOperationsListener.java

License:Apache License

@Override
public void onCreate(final ITenant tenant) {

    final StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.setRootObject(new RootObjectImpl(tenant));

    /*/*ww w  .ja va  2  s .  c om*/
     * First load dom4j Documents and sort the entity files into the proper order 
     */
    final Map<PortalDataKey, Set<Document>> importQueue = new HashMap<PortalDataKey, Set<Document>>();
    Resource rsc = null;
    try {
        for (Resource r : templateResources) {
            rsc = r;
            if (log.isDebugEnabled()) {
                log.debug("Loading template resource file for tenant " + "'" + tenant.getFname() + "':  "
                        + rsc.getFilename());
            }
            final Document doc = reader.read(rsc.getInputStream());
            final QName qname = doc.getRootElement().getQName();
            PortalDataKey atLeastOneMatchingDataKey = null;
            for (PortalDataKey pdk : dataKeyImportOrder) {
                // Matching is tougher because it's dom4j <> w3c...
                boolean matches = qname.getName().equals(pdk.getName().getLocalPart())
                        && qname.getNamespaceURI().equals(pdk.getName().getNamespaceURI());
                if (matches) {
                    // Found the right bucket...
                    atLeastOneMatchingDataKey = pdk;
                    Set<Document> bucket = importQueue.get(atLeastOneMatchingDataKey);
                    if (bucket == null) {
                        // First of these we've seen;  create the bucket;
                        bucket = new HashSet<Document>();
                        importQueue.put(atLeastOneMatchingDataKey, bucket);
                    }
                    bucket.add(doc);
                    /*
                     * At this point, we would normally add a break;
                     * statement, but group_membership.xml files need to
                     * match more than one PortalDataKey.
                     */
                }
            }
            if (atLeastOneMatchingDataKey == null) {
                // We can't proceed
                throw new RuntimeException(
                        "No PortalDataKey found for QName:  " + doc.getRootElement().getQName());
            }
        }
    } catch (Exception e) {
        throw new RuntimeException(
                "Failed to process the specified template:  " + (rsc != null ? rsc.getFilename() : ""), e);
    }

    log.trace("Ready to import data entity templates for new tenant '{}';  importQueue={}", tenant.getName(),
            importQueue);

    /*
     * Now import the identified entities each bucket in turn 
     */
    Document doc = null;
    org.w3c.dom.Document w3c = null;
    try {
        for (PortalDataKey pdk : dataKeyImportOrder) {
            Set<Document> bucket = importQueue.get(pdk);
            if (bucket != null) {
                log.debug("Importing the specified PortalDataKey tenant '{}':  {}", tenant.getName(),
                        pdk.getName());
                for (Document d : bucket) {
                    doc = d;
                    log.trace("Importing document XML={}", doc.asXML());
                    for (String xpath : XPATH_EXPRESSIONS) {
                        @SuppressWarnings("unchecked")
                        List<Node> nodes = doc.selectNodes(xpath);
                        for (Node n : nodes) {
                            String inpt, otpt;
                            switch (n.getNodeType()) {
                            case org.w3c.dom.Node.ATTRIBUTE_NODE:
                                Attribute a = (Attribute) n;
                                inpt = a.getValue();
                                otpt = processText(inpt, ctx);
                                if (!otpt.equals(inpt)) {
                                    a.setValue(otpt);
                                }
                                break;
                            case org.w3c.dom.Node.TEXT_NODE:
                                Text t = (Text) n;
                                inpt = t.getText();
                                otpt = processText(inpt, ctx);
                                if (!otpt.equals(inpt)) {
                                    t.setText(otpt);
                                }
                                break;
                            default:
                                String msg = "Unsupported node type:  " + n.getNodeTypeName();
                                throw new RuntimeException(msg);
                            }
                        }
                    }
                    w3c = writer.write(doc, domImpl);
                    Source source = new DOMSource(w3c);
                    source.setSystemId(rsc.getFilename()); // must be set, else import chokes
                    dataHandlerService.importData(source, pdk);
                }
            }
        }

    } catch (Exception e) {
        log.warn("w3c DOM=" + this.nodeToString(w3c));
        throw new RuntimeException(
                "Failed to process the specified template document:  " + (doc != null ? doc.asXML() : ""), e);
    }

}