Example usage for org.w3c.dom Node setTextContent

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

Introduction

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

Prototype

public void setTextContent(String textContent) throws DOMException;

Source Link

Document

This attribute returns the text content of this node and its descendants.

Usage

From source file:org.pentaho.osgi.i18n.webservice.ResourceBundleMessageBodyWriter.java

@Override
public void writeTo(ResourceBundle resourceBundle, Class<?> type, Type genericType, Annotation[] annotations,
        MediaType mediaType, MultivaluedMap<String, Object> httpHeaders, OutputStream entityStream)
        throws IOException, WebApplicationException {
    if (MediaType.APPLICATION_JSON_TYPE.equals(mediaType)) {
        JSONObject resourceBundleJsonObject = new JSONObject();
        for (String key : Collections.list(resourceBundle.getKeys())) {
            resourceBundleJsonObject.put(key, resourceBundle.getString(key));
        }/*from  w w  w .  j a v a  2  s.  c  o m*/
        OutputStreamWriter outputStreamWriter = null;
        try {
            outputStreamWriter = new OutputStreamWriter(entityStream);
            resourceBundleJsonObject.writeJSONString(outputStreamWriter);
        } finally {
            if (outputStreamWriter != null) {
                outputStreamWriter.flush();
            }
        }
    } else if (MediaType.APPLICATION_XML_TYPE.equals(mediaType)) {
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Node propertiesNode = document.createElement("properties");
            document.appendChild(propertiesNode);
            for (String key : Collections.list(resourceBundle.getKeys())) {
                Node propertyNode = document.createElement("property");
                propertiesNode.appendChild(propertyNode);

                Node keyNode = document.createElement("key");
                keyNode.setTextContent(key);
                propertyNode.appendChild(keyNode);

                Node valueNode = document.createElement("value");
                valueNode.setTextContent(resourceBundle.getString(key));
                propertyNode.appendChild(valueNode);
            }
            Result output = new StreamResult(entityStream);
            Source input = new DOMSource(document);
            try {
                Transformer transformer = TransformerFactory.newInstance().newTransformer();
                transformer.setOutputProperty(OutputKeys.INDENT, "yes");
                transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
                transformer.transform(input, output);
            } catch (TransformerException e) {
                throw new IOException(e);
            }
        } catch (ParserConfigurationException e) {
            throw new WebApplicationException(e);
        }
    }
}

From source file:org.rhq.modules.plugins.jbossas7.helper.JBossCliConfiguration.java

private void addChildElement(Node parent, String tagName, String textContent) {
    if (tagName != null && textContent != null && !textContent.isEmpty()) {
        Node element = this.document.createElement(tagName);
        element.setTextContent(textContent);
        parent.appendChild(element);/*  w ww.ja v  a 2s  .  c  o  m*/
    }
}

From source file:org.sakaiproject.james.JamesServlet.java

protected void customizeConfig(String host, String dns1, String dns2, String smtpPort, String logDir,
        String postmasterAddress) throws JamesConfigurationException {
    String configPath = m_phoenixHome + "/apps/james/SAR-INF/config.xml";
    String environmentPath = m_phoenixHome + "/apps/james/SAR-INF/environment.xml";

    XPath xpath = XPathFactory.newInstance().newXPath();
    Document doc;//w  w w .ja  va 2 s  .  c  o m

    try {
        // process config.xml first
        doc = Xml.readDocument(configPath);
        if (doc == null) {
            M_log.error("init(): James config file " + configPath + "could not be found.");
            throw new JamesConfigurationException();
        }

        if (postmasterAddress == null) {
            postmasterAddress = "postmaster@" + host;
        }

        // build a hashmap of node paths and values to set
        HashMap<String, String> nodeValues = new HashMap<String, String>();

        // WARNING!! in XPath, node-set indexes begin with 1, and NOT 0
        nodeValues.put("/config/James/servernames/servername[1]", host);
        nodeValues.put("/config/dnsserver/servers/server[2]", dns1);
        nodeValues.put("/config/dnsserver/servers/server[3]", dns2);
        nodeValues.put("/config/James/postmaster", postmasterAddress);
        nodeValues.put("/config/smtpserver/port", smtpPort);

        // loop through the hashmap, setting each value, or failing if one can't be found
        for (String nodePath : nodeValues.keySet()) {
            if (!(Boolean) xpath.evaluate(nodePath, doc, XPathConstants.BOOLEAN)) {
                if (nodePath.startsWith("/config/dnsserver/servers/server")) {
                    // add node (only if we're dealing with DNS server entries)
                    Element element = doc.createElement("server");
                    element.appendChild(doc.createTextNode(nodeValues.get(nodePath)));
                    Node parentNode = (Node) xpath.evaluate("/config/dnsserver/servers", doc,
                            XPathConstants.NODE);
                    parentNode.appendChild(element);

                } else {
                    // else, throw an exception
                    throw new JamesConfigurationException();
                }

            } else {
                // change existing node (if value != null else remove it)
                Node node = (Node) xpath.evaluate(nodePath, doc, XPathConstants.NODE);
                if (nodeValues.get(nodePath) != null) {
                    node.setTextContent(nodeValues.get(nodePath));
                } else {
                    node.getParentNode().removeChild(node);
                }
            }
        }

        M_log.debug("init(): writing James configuration to " + configPath);
        Xml.writeDocument(doc, configPath);

        // now handle environment.xml
        doc = Xml.readDocument(environmentPath);
        if (doc == null) {
            M_log.error("init(): James config file " + environmentPath + "could not be found.");
            throw new JamesConfigurationException();
        }

        String nodePath = "/server/logs/targets/file/filename";
        String nodeValue = logDir + "james";

        if (!(Boolean) xpath.evaluate(nodePath, doc, XPathConstants.BOOLEAN)) {
            M_log.error("init(): Could not find XPath '" + nodePath + "' in " + environmentPath + ".");
            throw new JamesConfigurationException();
        }
        ((Node) xpath.evaluate(nodePath, doc, XPathConstants.NODE)).setTextContent(nodeValue);

        M_log.debug("init(): writing James configuration to " + environmentPath);
        Xml.writeDocument(doc, environmentPath);
    } catch (JamesConfigurationException e) {
        throw e;
    } catch (Exception e) {
        M_log.warn("init(): An unhandled exception was encountered while configuring James: " + e.getMessage());
    }
}

From source file:org.sakaiproject.kernel.component.core.PersistenceUnitClassLoader.java

/**
 * Insert nodes before a given reference node in a
 * {@link org.w3c.dom.NodeList}.//  w w  w.ja v  a 2s.  co  m
 *
 * @param mappings
 * @param parentNode
 * @param refChild
 */
private void insertBefore(final Set<String> texts, final Document doc, final Node parentNode,
        final Node refChild, final EntityType type) {
    for (String text : texts) {
        Node n = doc.createElement(type.getType());
        n.setTextContent(text);
        parentNode.insertBefore(n, refChild);
    }
}

From source file:org.silverpeas.util.xml.transform.XPathTransformer.java

/**
 * Transform the DOM tree using the configuration.
 *
 * @param configuration the transformation configuration.
 * @param doc the DOM tree to be updated.
 *///from ww w. ja v a  2s.co m
protected void applyTransformation(XmlConfiguration configuration, Document doc) {
    List<Parameter> parameters = configuration.getParameters();
    for (Parameter parameter : parameters) {
        console.printMessage('\t' + parameter.getKey() + " (mode:" + parameter.getMode() + ')');
        Node rootXpathNode = getMatchingNode(parameter.getKey(), doc);
        if (rootXpathNode != null) {
            for (Value value : parameter.getValues()) {
                switch (value.getMode()) {
                case XmlTreeHandler.MODE_INSERT: {
                    createNewNode(doc, rootXpathNode, value);
                }
                    break;
                case XmlTreeHandler.MODE_DELETE: {
                    Node deletedNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    rootXpathNode.removeChild(deletedNode);
                }
                    break;
                case XmlTreeHandler.MODE_UPDATE: {
                    Node oldNode = getMatchingNode(value.getLocation(), rootXpathNode);
                    if (oldNode == null) {
                        createNewNode(doc, rootXpathNode, value);
                    } else {
                        if (rootXpathNode.equals(oldNode)) {
                            rootXpathNode = rootXpathNode.getParentNode();
                        }
                        Node newNode = oldNode.cloneNode(true);
                        if (oldNode instanceof Element) {
                            newNode.setTextContent(value.getValue());
                            rootXpathNode.replaceChild(newNode, oldNode);
                        } else {
                            ((Attr) newNode).setValue(value.getValue());
                            rootXpathNode.getAttributes().setNamedItem(newNode);
                        }

                    }
                    break;
                }
                }
            }
        }
    }
}

From source file:org.slc.sli.scaffold.ResourceDocumentation.java

private void addTag(final Node node, final String key, final String value) {
    if (value != null) {
        final Node toAdd = this.doc.createElement(key);
        toAdd.setTextContent(value);
        node.appendChild(toAdd);//from   w  w  w  .j a  va2 s  .  c  om
    }
}

From source file:org.talend.dataquality.libraries.devops.ReleaseVersionBumper.java

private void bumpPomVersion() throws Exception {

    final String resourcePath = ReleaseVersionBumper.class.getResource(".").getFile();
    final String projectRoot = new File(resourcePath).getParentFile().getParentFile().getParentFile()
            .getParentFile().getParentFile().getParentFile().getParentFile().getPath() + File.separator;

    String parentPomPath = "./pom.xml";
    File inputFile = new File(projectRoot + parentPomPath);
    if (inputFile.exists()) {
        System.out.println("Updating: " + inputFile.getAbsolutePath());
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputFile);

        // replace version value of this project
        Node parentVersion = (Node) xPath.evaluate("/project/version", doc, XPathConstants.NODE);
        parentVersion.setTextContent(targetVersion);

        // replace property value of this project
        NodeList propertyNodes = ((Node) xPath.evaluate("/project/properties", doc, XPathConstants.NODE))
                .getChildNodes();/*from   w  ww .j  a  va 2 s.  c  o  m*/
        for (int idx = 0; idx < propertyNodes.getLength(); idx++) {
            Node node = propertyNodes.item(idx);
            String propertyName = node.getNodeName();
            String propertyValue = node.getTextContent();
            if (propertyName.startsWith(DATAQUALITY_PREFIX)) {
                if (targetVersion.endsWith(SNAPSHOT_VERSION_SUFFIX) && propertyName.contains(SNAPSHOT_STRING)) {
                    node.setTextContent(propertyValue.substring(0, 4) + microVersion);
                } else if (!targetVersion.endsWith(SNAPSHOT_VERSION_SUFFIX)
                        && propertyName.contains(RELEASED_STRING)) {
                    node.setTextContent(propertyValue.substring(0, 4) + microVersion);
                }
            }
        }
        // re-write pom.xml file
        xTransformer.transform(new DOMSource(doc), new StreamResult(inputFile));

        // update manifest of this project
        Path manifestPath = Paths.get(inputFile.getParentFile().getAbsolutePath(), "META-INF", "MANIFEST.MF");
        updateManifestVersion(manifestPath);

        // update modules
        NodeList moduleNodes = (NodeList) xPath.evaluate("/project/modules/module", doc,
                XPathConstants.NODESET);
        for (int idx = 0; idx < moduleNodes.getLength(); idx++) {
            String modulePath = moduleNodes.item(idx).getTextContent();
            updateChildModules(new File(projectRoot + modulePath + "/pom.xml"));
        }
    }
}

From source file:org.talend.dataquality.libraries.devops.ReleaseVersionBumper.java

private void updateChildModules(File inputFile) throws Exception {
    if (inputFile.exists()) {
        System.out.println("Updating: " + inputFile.getAbsolutePath());
        Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputFile);

        // replace parent version value
        Node parentVersion = (Node) xPath.evaluate("/project/parent/version", doc, XPathConstants.NODE);
        parentVersion.setTextContent(targetVersion);

        // replace project version value
        Node projectVersion = (Node) xPath.evaluate("/project/version", doc, XPathConstants.NODE);
        String projectVersionValue = projectVersion.getTextContent();
        if (targetVersion.endsWith(SNAPSHOT_VERSION_SUFFIX)) {
            projectVersion.setTextContent(projectVersionValue.replace(RELEASED_STRING, SNAPSHOT_STRING));
        } else {/*w  w w.j a v  a2s .c o m*/
            projectVersion.setTextContent(projectVersionValue.replace(SNAPSHOT_STRING, RELEASED_STRING));
        }

        // replace dependency version value
        NodeList nodes = (NodeList) xPath.evaluate("/project/dependencies/dependency/version", doc,
                XPathConstants.NODESET);
        for (int idx = 0; idx < nodes.getLength(); idx++) {
            Node node = nodes.item(idx);
            String depVersionvalue = node.getTextContent();
            if (depVersionvalue.startsWith("${dataquality.")) {
                if (targetVersion.endsWith(SNAPSHOT_VERSION_SUFFIX)) {
                    node.setTextContent(depVersionvalue.replace(RELEASED_STRING, SNAPSHOT_STRING));
                } else {
                    node.setTextContent(depVersionvalue.replace(SNAPSHOT_STRING, RELEASED_STRING));
                }
            }
        }

        // re-write pom.xml file
        xTransformer.transform(new DOMSource(doc), new StreamResult(inputFile));

        // update manifest file of child project
        Path manifestPath = Paths.get(inputFile.getParentFile().getAbsolutePath(), "META-INF", "MANIFEST.MF");
        updateManifestVersion(manifestPath);
    }
}

From source file:org.talend.mdm.webapp.browserecords.server.util.CommonUtil.java

public static void migrationMultiLingualFieldValue(ItemBean itemBean, TypeModel typeModel, Node node,
        String path, boolean isMultiOccurence, ItemNodeModel nodeModel) {
    String value = node.getTextContent();
    if (typeModel != null && typeModel.getType().equals(DataTypeConstants.MLS)
            && BrowseRecordsConfiguration.dataMigrationMultiLingualFieldAuto()) {
        if (value != null && value.trim().length() > 0) {
            if (!MultilanguageMessageParser.isExistMultiLanguageFormat(value)) {
                String defaultLanguage = com.amalto.core.util.Util.getDefaultSystemLocale();
                String newValue = MultilanguageMessageParser.getFormatValueByDefaultLanguage(value,
                        defaultLanguage != null ? defaultLanguage : "en");//$NON-NLS-1$
                if (nodeModel == null) {
                    if (isMultiOccurence) {
                        node.setTextContent(newValue);
                    } else {
                        itemBean.set(path, newValue);
                    }// www. j a v a  2s.c o m
                } else {
                    nodeModel.setObjectValue(newValue);
                }
            } else if (nodeModel != null) {
                nodeModel.setObjectValue(FormatUtil.multiLanguageEncode(value));
            }
        }
    }
}

From source file:org.vivoweb.harvester.fetch.WOSFetch.java

/**
 * @param previousQuery a WOS soap query xml message
 * @return the string with the altered first node in the 
 * @throws IOException thrown if there is an issue parsing the previousQuery string
 *//* w w  w  .  j  a v a  2 s .c  om*/
private String getnextQuery(String previousQuery) throws IOException {
    String nextQuery = "";
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true); // never forget this!
        Document searchDoc = factory.newDocumentBuilder()
                .parse(new ByteArrayInputStream(previousQuery.getBytes()));
        //log.debug("searchDoc:");
        //log.debug(documentToString(searchDoc));

        NodeList firstrecordNodes = searchDoc.getElementsByTagName("firstRecord");
        Node firstnode = firstrecordNodes.item(0);
        int firstrecord = Integer.parseInt(firstnode.getTextContent());
        log.debug("firstrecord = " + firstrecord);

        NodeList countNodes = searchDoc.getElementsByTagName("count");
        int count = Integer.parseInt(countNodes.item(0).getTextContent());
        log.debug("count= " + count);
        int newFirst = firstrecord + count;
        firstnode.setTextContent(Integer.toString(newFirst));
        log.debug("new First Record= " + newFirst);
        //      }

        nextQuery = nodeToString(searchDoc);
        //log.debug("newsearchDoc:\n"+nextQuery);
    } catch (SAXException e) {
        e.printStackTrace();
        throw new IOException(e);
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
        throw new IOException(e);
    }
    return nextQuery;

}