Example usage for org.w3c.dom Node getTextContent

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

Introduction

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

Prototype

public String getTextContent() throws DOMException;

Source Link

Document

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

Usage

From source file:Main.java

/**
 * Remove any whitespace text nodes from the DOM. Calling this before saving
 * a formatted document will fix the formatting indentation of elements
 * loaded from a different document./* w  w w  .  j ava  2  s . c  om*/
 * 
 * @param node
 *            Node to remove whitespace nodes from
 * @param deep
 *            Should this method recurse into the node's children?
 */
public static void removeWhitespace(Node node, boolean deep) {
    NodeList children = node.getChildNodes();
    int length = children.getLength();
    for (int i = 0; i < length; i++) {
        Node child = children.item(i);
        if (child.getNodeType() == Node.TEXT_NODE && length > 1) {
            Node previous = child.getPreviousSibling();
            Node next = child.getNextSibling();
            if ((previous == null || previous.getNodeType() == Node.ELEMENT_NODE
                    || previous.getNodeType() == Node.COMMENT_NODE)
                    && (next == null || next.getNodeType() == Node.ELEMENT_NODE
                            || next.getNodeType() == Node.COMMENT_NODE)) {
                String content = child.getTextContent();
                if (content.matches("\\s*")) //$NON-NLS-1$
                {
                    node.removeChild(child);
                    i--;
                    length--;
                }
            }
        } else if (deep && child.getNodeType() == Node.ELEMENT_NODE) {
            removeWhitespace(child, deep);
        }
    }
}

From source file:Main.java

/**
 * Identify variables in attribute values and CDATA contents and replace
 * with their values as defined in the variableDefs map. Variables without
 * definitions are left alone.//from  www.j a v  a  2 s . c o m
 *
 * @param node the node to do variable replacement in
 * @param variableDefs map from variable names to values.
 */
public static void replaceVariables(final Node node, Map<String, String> variableDefs) {
    switch (node.getNodeType()) {
    case Node.ELEMENT_NODE:
        final Element element = (Element) node;
        final NamedNodeMap atts = element.getAttributes();
        for (int i = 0; i < atts.getLength(); i++) {
            final Attr attr = (Attr) atts.item(i);
            attr.setNodeValue(replaceVariablesInString(attr.getValue(), variableDefs));
        }
        break;

    case Node.CDATA_SECTION_NODE:
        String content = node.getTextContent();
        node.setNodeValue(replaceVariablesInString(content, variableDefs));
        break;

    default:
        break;
    }

    // process children
    final NodeList children = node.getChildNodes();
    for (int childIndex = 0; childIndex < children.getLength(); childIndex++)
        replaceVariables(children.item(childIndex), variableDefs);
}

From source file:org.jboss.as.test.integration.logging.formatters.XmlFormatterTestCase.java

private static void validateDefault(final Document doc, final Collection<String> expectedKeys,
        final String expectedMessage) {
    final Set<String> remainingKeys = new HashSet<>(expectedKeys);

    String loggerClassName = null;
    String loggerName = null;//w  w w . j  a  v  a 2s  .c  o  m
    String level = null;
    String message = null;

    // Check all the expected keys
    final Iterator<String> iterator = remainingKeys.iterator();
    while (iterator.hasNext()) {
        final String key = iterator.next();
        final NodeList children = doc.getElementsByTagName(key);
        Assert.assertTrue(String.format("Key %s was not found in the document: %s", key, doc),
                children.getLength() > 0);
        final Node child = children.item(0);
        if ("loggerClassName".equals(child.getNodeName())) {
            loggerClassName = child.getTextContent();
        } else if ("loggerName".equals(child.getNodeName())) {
            loggerName = child.getTextContent();
        } else if ("level".equals(child.getNodeName())) {
            level = child.getTextContent();
        } else if ("message".equals(child.getNodeName())) {
            message = child.getTextContent();
        }
        iterator.remove();
    }

    // Should have no more remaining keys
    Assert.assertTrue("There are remaining keys that were not validated: " + remainingKeys,
            remainingKeys.isEmpty());

    Assert.assertEquals("org.jboss.logging.Logger", loggerClassName);
    Assert.assertEquals(LoggingServiceActivator.LOGGER.getName(), loggerName);
    Assert.assertTrue("Invalid level found in " + level, isValidLevel(level));
    Assert.assertEquals(expectedMessage, message);
}

From source file:com.flexive.shared.media.impl.FxMediaImageMagickEngine.java

/**
 * Identify a file, returning metadata//from  w w w .  java  2s  . co m
 *
 * @param mimeType if not null it will be used to call the correct identify routine
 * @param file     the file to identify
 * @return metadata
 * @throws FxApplicationException on errors
 * @since 3.1
 */
public static FxMetadata identify(String mimeType, File file) throws FxApplicationException {
    if (mimeType == null)
        mimeType = FxMediaNativeEngine.detectMimeType(null, file.getAbsolutePath());
    try {
        String metaData = IMParser.getMetaData(file);

        String format = "unknown";
        String formatDescription = "";
        String compressionAlgorithm = "";
        String colorType = "";
        int width = 0;
        int height = 0;
        double xRes = 0.0;
        double yRes = 0.0;
        int bpp = 0;

        DocumentBuilder builder = javax.xml.parsers.DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new ByteArrayInputStream(metaData.getBytes()));
        XPath xPath = javax.xml.xpath.XPathFactory.newInstance().newXPath();

        Node nFormat = (Node) xPath.evaluate("/Image/Format", document, javax.xml.xpath.XPathConstants.NODE);
        if (nFormat != null && nFormat.getTextContent() != null) {
            format = nFormat.getTextContent();
            if (format.indexOf(' ') > 0) {
                formatDescription = format.substring(format.indexOf(' ') + 1);
                if (formatDescription.indexOf('(') >= 0 && formatDescription.indexOf(')') > 0) {
                    formatDescription = formatDescription.substring(formatDescription.indexOf('(') + 1,
                            formatDescription.indexOf(')'));
                }
                format = format.substring(0, format.indexOf(' '));
            }
        }

        Node nCompression = (org.w3c.dom.Node) xPath.evaluate("/Image/Compression", document,
                javax.xml.xpath.XPathConstants.NODE);
        if (nCompression != null && nCompression.getTextContent() != null) {
            compressionAlgorithm = nCompression.getTextContent();
        }

        Node nColorType = (Node) xPath.evaluate("/Image/Colorspace", document,
                javax.xml.xpath.XPathConstants.NODE);
        if (nColorType != null && nColorType.getTextContent() != null) {
            colorType = nColorType.getTextContent();
        }

        Node nGeometry = (Node) xPath.evaluate("/Image/Geometry", document,
                javax.xml.xpath.XPathConstants.NODE);
        if (nGeometry != null && nGeometry.getTextContent() != null) {
            String geo = nGeometry.getTextContent();
            if (geo.indexOf('+') > 0)
                geo = geo.substring(0, geo.indexOf('+'));
            if (geo.indexOf('x') > 0) {
                try {
                    width = Integer.parseInt(geo.substring(0, geo.indexOf('x')));
                    height = Integer.parseInt(geo.substring(geo.indexOf('x') + 1));
                } catch (NumberFormatException ex) {
                    //failed, ignore
                }

            }
        }

        Node nResolution = (Node) xPath.evaluate("/Image/Resolution", document,
                javax.xml.xpath.XPathConstants.NODE);
        if (nResolution != null && nResolution.getTextContent() != null) {
            String res = nResolution.getTextContent();
            if (res.indexOf('+') > 0)
                res = res.substring(0, res.indexOf('+'));
            if (res.indexOf('x') > 0) {
                try {
                    xRes = Double.parseDouble(res.substring(0, res.indexOf('x')));
                    yRes = Double.parseDouble(res.substring(res.indexOf('x') + 1));
                } catch (NumberFormatException ex) {
                    //failed, ignore
                }

            }
        }

        Node nDepth = (Node) xPath.evaluate("/Image/Depth", document, javax.xml.xpath.XPathConstants.NODE);
        if (nDepth != null && nDepth.getTextContent() != null) {
            String dep = nDepth.getTextContent();
            if (dep.indexOf('-') > 0)
                dep = dep.substring(0, dep.indexOf('-'));
            try {
                bpp = Integer.parseInt(dep);
            } catch (NumberFormatException ex) {
                //failed, ignore
            }
        }

        List<FxMetadata.FxMetadataItem> items = new ArrayList<FxMetadata.FxMetadataItem>(50);
        NodeList nodes = (NodeList) xPath.evaluate("/Image/*", document,
                javax.xml.xpath.XPathConstants.NODESET);
        Node currNode;
        for (int i = 0; i < nodes.getLength(); i++) {
            currNode = nodes.item(i);
            if (currNode.hasChildNodes() && currNode.getChildNodes().getLength() > 1) {
                for (int j = 0; j < currNode.getChildNodes().getLength(); j++)
                    items.add(new FxMetadata.FxMetadataItem(
                            currNode.getNodeName() + "/" + currNode.getChildNodes().item(j).getNodeName(),
                            currNode.getChildNodes().item(j).getTextContent()));
            } else
                items.add(new FxMetadata.FxMetadataItem(currNode.getNodeName(), currNode.getTextContent()));
        }
        return new FxImageMetadataImpl(mimeType, file.getName(), items, width, height, format,
                formatDescription, compressionAlgorithm, xRes, yRes, colorType, false, bpp, false, false, null);
    } catch (Exception e) {
        throw new FxApplicationException(e, "ex.media.identify.error", file.getName(), mimeType,
                e.getMessage());
    }

}

From source file:de.wikilab.android.friendica01.Notification.java

public static Notification fromXmlNode(Node d) {
    Notification n = new Notification();

    n.href = d.getAttributes().getNamedItem("href").getNodeValue();
    n.name = d.getAttributes().getNamedItem("name").getNodeValue();
    n.url = d.getAttributes().getNamedItem("url").getNodeValue();
    n.photo = d.getAttributes().getNamedItem("photo").getNodeValue();
    n.date = d.getAttributes().getNamedItem("date").getNodeValue();
    n.seen = d.getAttributes().getNamedItem("seen").getNodeValue();

    n.content = d.getTextContent();

    if (n.content.startsWith("&rarr;")) {
        n.isUnread = true;//from w  w  w  .ja va2  s. c o m
        n.content = n.content.substring(6);
    }

    return n;
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateEclipseCsMetaXmlFileRules(String pkg, Set<Class<?>> pkgModules, Set<Node> rules)
        throws Exception {
    for (Node rule : rules) {
        final NamedNodeMap attributes = rule.getAttributes();
        final Node internalNameNode = attributes.getNamedItem("internal-name");

        Assert.assertNotNull(pkg + " checkstyle-metadata.xml must contain an internal name", internalNameNode);

        final String internalName = internalNameNode.getTextContent();
        final String classpath = "com.github.sevntu.checkstyle.checks." + pkg + "." + internalName;

        final Class<?> module = findModule(pkgModules, classpath);
        pkgModules.remove(module);/* w  ww .  j a va 2  s . c  om*/

        Assert.assertNotNull("Unknown class found in " + pkg + " checkstyle-metadata.xml: " + internalName,
                module);

        final Node nameAttribute = attributes.getNamedItem("name");

        Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires a name for " + internalName,
                nameAttribute);
        Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid name for " + internalName,
                "%" + internalName + ".name", nameAttribute.getTextContent());

        final Node parentAttribute = attributes.getNamedItem("parent");

        Assert.assertNotNull(pkg + " checkstyle-metadata.xml requires a parent for " + internalName,
                parentAttribute);
        Assert.assertEquals(pkg + " checkstyle-metadata.xml requires a valid parent for " + internalName,
                "TreeWalker", parentAttribute.getTextContent());

        final Set<Node> children = XmlUtil.getChildrenElements(rule);

        validateEclipseCsMetaXmlFileRule(pkg, module, children);
    }
}

From source file:com.puppycrawl.tools.checkstyle.XDocsPagesTest.java

private static void validateUsageExample(String fileName, String sectionName, Node subSection) {
    final String text = subSection.getTextContent().replace("Checkstyle Style", "").replace("Google Style", "")
            .replace("Sun Style", "").trim();

    Assert.assertTrue(/*from   w ww .  j  av a2 s .com*/
            fileName + " section '" + sectionName + "' has unknown text in 'Example of Usage': " + text,
            text.isEmpty());

    for (Node node : findChildElementsByTag(subSection, "a")) {
        final String url = node.getAttributes().getNamedItem("href").getTextContent();
        final String linkText = node.getTextContent().trim();
        String expectedUrl = null;

        if ("Checkstyle Style".equals(linkText)) {
            expectedUrl = "https://github.com/search?q=" + "path%3Aconfig+filename%3Acheckstyle_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        } else if ("Google Style".equals(linkText)) {
            expectedUrl = "https://github.com/search?q="
                    + "path%3Asrc%2Fmain%2Fresources+filename%3Agoogle_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        } else if ("Sun Style".equals(linkText)) {
            expectedUrl = "https://github.com/search?q="
                    + "path%3Asrc%2Fmain%2Fresources+filename%3Asun_checks.xml+"
                    + "repo%3Acheckstyle%2Fcheckstyle+" + sectionName;
        }

        Assert.assertEquals(fileName + " section '" + sectionName + "' should have matching url", expectedUrl,
                url);
    }
}

From source file:com.github.sevntu.checkstyle.internal.ChecksTest.java

private static void validateSonarFile(Document document, Set<Class<?>> modules) {
    final NodeList rules = document.getElementsByTagName("rule");

    for (int position = 0; position < rules.getLength(); position++) {
        final Node rule = rules.item(position);
        final Set<Node> children = XmlUtil.getChildrenElements(rule);

        final String key = SevntuXmlUtil.findElementByTag(children, "key").getTextContent();

        final Class<?> module = findModule(modules, key);
        modules.remove(module);//  ww  w. j  a  va2s.  c o  m

        Assert.assertNotNull("Unknown class found in sonar: " + key, module);

        final String moduleName = module.getName();
        final Node name = SevntuXmlUtil.findElementByTag(children, "name");

        Assert.assertNotNull(moduleName + " requires a name in sonar", name);
        Assert.assertFalse(moduleName + " requires a name in sonar", name.getTextContent().isEmpty());

        final Node categoryNode = SevntuXmlUtil.findElementByTag(children, "category");

        String expectedCategory = module.getCanonicalName();
        final int lastIndex = expectedCategory.lastIndexOf('.');
        expectedCategory = expectedCategory.substring(expectedCategory.lastIndexOf('.', lastIndex - 1) + 1,
                lastIndex);

        Assert.assertNotNull(moduleName + " requires a category in sonar", categoryNode);

        final Node categoryAttribute = categoryNode.getAttributes().getNamedItem("name");

        Assert.assertNotNull(moduleName + " requires a category name in sonar", categoryAttribute);
        Assert.assertEquals(moduleName + " requires a valid category in sonar", expectedCategory,
                categoryAttribute.getTextContent());

        final Node description = SevntuXmlUtil.findElementByTag(children, "description");

        Assert.assertNotNull(moduleName + " requires a description in sonar", description);

        final Node configKey = SevntuXmlUtil.findElementByTag(children, "configKey");
        final String expectedConfigKey = "Checker/TreeWalker/" + key;

        Assert.assertNotNull(moduleName + " requires a configKey in sonar", configKey);
        Assert.assertEquals(moduleName + " requires a valid configKey in sonar", expectedConfigKey,
                configKey.getTextContent());

        validateSonarProperties(module, SevntuXmlUtil.findElementsByTag(children, "param"));
    }

    for (Class<?> module : modules) {
        Assert.fail("Module not found in sonar: " + module.getCanonicalName());
    }
}

From source file:de.ingrid.portal.global.UtilsMapServiceManager.java

private static void evaluateKmlNode(HashMap data, Node node) {

    if (node.getNamespaceURI().equals(IDFNamespaceContext.NAMESPACE_URI_KML)) {
        Node documentNode = XPathUtils.getNode(node, "./kml:Document");
        if (documentNode != null) {
            Node titleNode = XPathUtils.getNode(documentNode, "./kml:name");
            String title = "";
            // Titel
            if (titleNode != null) {
                title = titleNode.getTextContent().trim();
                data.put("coord_class", title);
            }//from ww  w.ja  v a  2 s.  c o m

            //Placemark
            NodeList placemarkNodeList = XPathUtils.getNodeList(documentNode, "./kml:Placemark");
            if (placemarkNodeList != null) {
                ArrayList<HashMap<String, String>> placemarks = new ArrayList<HashMap<String, String>>();
                for (int i = 0; i < placemarkNodeList.getLength(); i++) {
                    Node pmNode = placemarkNodeList.item(i);
                    HashMap<String, String> placemark = new HashMap<String, String>();
                    placemark.put("coord_class", title);

                    // Name
                    Node pmNameNode = XPathUtils.getNode(pmNode, "./kml:name");
                    if (pmNameNode != null) {
                        String name = pmNameNode.getTextContent().trim();
                        if (name != null) {
                            placemark.put("coord_title", name);
                        }
                    }

                    // Description
                    Node pmDescrNode = XPathUtils.getNode(pmNode, "./kml:description");
                    if (pmDescrNode != null) {
                        String description = pmDescrNode.getTextContent().trim();
                        if (description != null) {
                            placemark.put("coord_descr", description);
                        }
                    }

                    // Point
                    Node pmPointNode = XPathUtils.getNode(pmNode, "./kml:Point");
                    if (pmPointNode != null) {
                        if (pmPointNode.hasChildNodes()) {
                            Node coordinatesNode = XPathUtils.getNode(pmPointNode, "./kml:coordinates");
                            if (coordinatesNode != null) {
                                String coordinates = coordinatesNode.getTextContent().trim();
                                if (coordinates != null) {
                                    String[] coords = coordinates.split(",");
                                    placemark.put("coord_x", coords[0]);
                                    placemark.put("coord_y", coords[1]);
                                }
                            }
                        }
                    }
                    placemarks.add(placemark);
                }
                data.put("placemarks", placemarks);
            }
        }
    }
}

From source file:com.linkedin.drelephant.util.Utils.java

/**
 * Given a configuration element, extract the params map.
 *
 * @param confElem the configuration element
 * @return the params map or an empty map if one can't be found
 *//*from w w w  . j  a v  a2 s .co  m*/
public static Map<String, String> getConfigurationParameters(Element confElem) {
    Map<String, String> paramsMap = new HashMap<String, String>();
    Node paramsNode = confElem.getElementsByTagName("params").item(0);
    if (paramsNode != null) {
        NodeList paramsList = paramsNode.getChildNodes();
        for (int j = 0; j < paramsList.getLength(); j++) {
            Node paramNode = paramsList.item(j);
            if (paramNode != null && !paramsMap.containsKey(paramNode.getNodeName())) {
                paramsMap.put(paramNode.getNodeName(), paramNode.getTextContent());
            }
        }
    }
    return paramsMap;
}