Example usage for org.dom4j Node setText

List of usage examples for org.dom4j Node setText

Introduction

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

Prototype

void setText(String text);

Source Link

Document

Sets the text data of this node or this method will throw an UnsupportedOperationException if it is read-only.

Usage

From source file:org.craftercms.core.processors.impl.template.TemplateProcessor.java

License:Open Source License

/**
 * Processes the content of certain nodes (found by the {@code NodeScanner} in the item's descriptor as templates,
 * by compiling the node text templates through the {@code templateCompiler} and then processing the compiled
 * template with a model returned by {@code modelFactory}.
 *
 * @throws ItemProcessingException if an error occurred while processing a template
 *///  w  w  w.  j av a2  s. com
public Item process(Context context, CachingOptions cachingOptions, Item item) throws ItemProcessingException {
    String descriptorUrl = item.getDescriptorUrl();
    Document descriptorDom = item.getDescriptorDom();

    if (descriptorDom != null) {
        List<Node> templateNodes = templateNodeScanner.scan(descriptorDom);
        if (CollectionUtils.isNotEmpty(templateNodes)) {
            for (Node templateNode : templateNodes) {
                String templateNodePath = templateNode.getUniquePath();

                if (logger.isDebugEnabled()) {
                    logger.debug("Template found in " + descriptorUrl + " at " + templateNodePath);
                }

                String templateId = templateNodePath + "@" + descriptorUrl;
                String template = templateNode.getText();
                IdentifiableStringTemplateSource templateSource = new IdentifiableStringTemplateSource(
                        templateId, template);

                Object model = modelFactory.getModel(item, templateNode, template);
                StringWriter output = new StringWriter();

                try {
                    CompiledTemplate compiledTemplate = templateCompiler.compile(templateSource);
                    compiledTemplate.process(model, output);
                } catch (TemplateException e) {
                    throw new ItemProcessingException("Unable to process the template " + templateId, e);
                }

                templateNode.setText(output.toString());
            }
        }
    }

    return item;
}

From source file:org.craftercms.cstudio.impl.service.translation.provider.demo.DemoTranslationProvider.java

License:Open Source License

@Override
public InputStream getTranslatedContentForItem(String siteName, String targetLanguage, String path) {
    InputStream retTranslatedContent = null;
    byte[] contentBytes = _content.get(path);

    if (contentBytes != null) {

        if (path.endsWith(".xml") || path.endsWith(".XML")) {
            try {
                InputStream docInputStream = new ByteArrayInputStream(contentBytes);
                SAXReader saxReader = new SAXReader();
                Document document = saxReader.read(docInputStream);

                for (String element : _translateElements) {
                    List<Node> valueEls = document.selectNodes("//" + element);

                    if (valueEls != null && valueEls.size() > 0) {
                        // translate each value
                        String translation = "";
                        Node valueEl = valueEls.get(0);
                        String value = valueEl.getText();

                        translation = value;
                        Pattern contentPattern = Pattern.compile(">(.*?)<");
                        Matcher regexMatcher = contentPattern.matcher(value);
                        while (regexMatcher.find()) {
                            String content = regexMatcher.group(1);
                            if (!".".equals(content.trim())) {
                                translation = translation.replaceAll(content,
                                        new StringBuffer(content).reverse().toString());
                            }//w ww . j a va2  s. co m
                        }

                        // put it back in the xml document (but translated)
                        valueEl.setText(translation);
                    }
                }

                // get the entire translation and return as bytes
                String translatedDocument = document.asXML();
                retTranslatedContent = new ByteArrayInputStream(translatedDocument.getBytes("UTF-8"));
            } catch (Exception err) {
                // log error
                logger.error("issue during translation", err);
            }
        } else {
            retTranslatedContent = new ByteArrayInputStream(contentBytes);
        }
    }

    return retTranslatedContent;
}

From source file:org.craftercms.cstudio.loadtesting.actions.WriteContent.java

License:Open Source License

/**
 * convert InputStream to string// ww w .  ja  v  a 2s.  com
 * @param internalName 
 * 
 * @param is
 * @return string
 */
public String getFileContent(String baseFileName, String fileName, String internalName) throws Exception {
    InputStream is = null;
    InputStreamReader isReader = null;
    StringWriter sw = null;
    XMLWriter writer = null;
    try {
        is = this.getClass().getResourceAsStream("/" + baseFileName);
        isReader = new InputStreamReader(is, "UTF-8");
        SAXReader saxReader = new SAXReader();
        Document document = saxReader.read(isReader);
        Element root = document.getRootElement();
        Node node = root.selectSingleNode("file-name");
        node.setText(fileName);
        Node node2 = root.selectSingleNode("internal-name");
        node2.setText(internalName);
        sw = new StringWriter();
        writer = new XMLWriter(sw);
        writer.write(document);
        writer.flush();
        return sw.toString();
    } finally {
        if (is != null) {
            is.close();
        }
        if (isReader != null) {
            isReader.close();
        }
        if (sw != null) {
            sw.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:org.danann.cernunnos.xml.NodeProcessor.java

License:Apache License

public static void evaluatePhrases(Node n, Grammar g, TaskRequest req, TaskResponse res) {

    // Assertions...
    if (n == null) {
        String msg = "Argument 'n [Node]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }/*from  ww  w  . ja v a  2s.  com*/
    if (g == null) {
        String msg = "Argument 'g [Grammar]' cannot be null.";
        throw new IllegalArgumentException(msg);
    }

    if (n instanceof Branch) {
        ((Branch) n).normalize();
    }

    final XPath xpath = XPATH_LOCAL.get();
    for (Iterator<?> it = xpath.selectNodes(n).iterator(); it.hasNext();) {
        Node d = (Node) it.next();
        if (d.getText().trim().length() != 0) {
            Phrase p = g.newPhrase(d);
            Object o = p.evaluate(req, res);
            String value = o != null ? o.toString() : "null";
            d.setText(value);
        }
    }

}

From source file:org.hibernate.ogm.type.AbstractGenericBasicType.java

License:Open Source License

@SuppressWarnings({ "unchecked" })
public final void setToXMLNode(Node node, Object value, SessionFactoryImplementor factory) {
    node.setText(toString((T) value));
}

From source file:org.hibernate.type.ByteArrayBlobType.java

License:Open Source License

public void setToXMLNode(Node node, Object value, SessionFactoryImplementor factory) throws HibernateException {
    node.setText(toString(value));
}

From source file:org.jage.platform.config.xml.loaders.PlaceholderResolver.java

License:Open Source License

@SuppressWarnings("unchecked")
private void fillPlaceholders(final Properties properties, final Document document)
        throws ConfigurationException {
    for (final Node node : (List<Node>) ATTRIBUTE_PLACEHOLDERS.selectNodes(document)) {
        final String text = node.getText();
        final String placeholderName = text.substring(PREFIX.length(), text.length() - SUFFIX.length());
        final String placeholderValue = properties.getProperty(placeholderName);
        if (placeholderValue == null) {
            throw new ConfigurationException(
                    format("No property value found for placeholder '%s'", placeholderName));
        }// w  w  w . ja v  a 2  s  . co  m
        node.setText(placeholderValue);
    }
}

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;//from ww  w  . j  a v  a2 s . c  om
            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.jivesoftware.openfire.clearspace.WSUtils.java

License:Open Source License

/**
 * Modifies the text of the elmement with name 'name'.
 *
 * @param node     the element to search
 * @param name     the name to search/*w w  w.  ja va  2  s  .c  o  m*/
 * @param newValue the new value of the text
 */
protected static void modifyElementText(Node node, String name, String newValue) {
    Node n = node.selectSingleNode(name);
    n.setText(newValue);
}

From source file:org.openadaptor.thirdparty.dom4j.Dom4jSimpleRecordAccessor.java

License:Open Source License

/**
 * Store the suppplied object in the underlying Dom4j Document at the
 * location defined by the supplied key.
 * <p>//  w  w w. j a v a 2  s  .  c o m
 * Note - if the path does not exist, it will attempt to create it.
 * <p>
 * Currently the value stored simply uses the Object's toString() method.
 * //ToDo: allow it to set the type attribute also.
 * @param key an XPath like expression with the path.
 * @param value Object to be stored.
 * @return The Object which has just been stored.
 * @throws RecordException if the operation cannot be completed.
 */
public Object put(Object key, Object value) throws RecordException {
    if (key == null) {
        log.warn("<null> key value is not permitted");
        throw new RecordException("<null> key value is not permitted");
    }

    String path = key.toString().trim();
    Node node = getNode(document, path);
    //node.setText(value == null ? null : value.toString());
    node.setText(Dom4jUtils.valueAsNonNullString(value));
    return value;
}