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:hudson.plugins.plot.XMLSeries.java

/**
 * Load the series from a properties file.
 *///w ww  . j  a  v  a  2 s.c  o  m
@Override
public List<PlotPoint> loadSeries(FilePath workspaceRootDir, int buildNumber, PrintStream logger) {
    InputStream in = null;
    InputSource inputSource = null;

    try {
        List<PlotPoint> ret = new ArrayList<PlotPoint>();
        FilePath[] seriesFiles = null;

        try {
            seriesFiles = workspaceRootDir.list(getFile());
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception trying to retrieve series files", e);
            return null;
        }

        if (ArrayUtils.isEmpty(seriesFiles)) {
            LOGGER.info("No plot data file found: " + getFile());
            return null;
        }

        try {
            if (LOGGER.isLoggable(defaultLogLevel))
                LOGGER.log(defaultLogLevel, "Loading plot series data from: " + getFile());

            in = seriesFiles[0].read();
            // load existing plot file
            inputSource = new InputSource(in);
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "Exception reading plot series data from " + seriesFiles[0], e);
            return null;
        }

        if (LOGGER.isLoggable(defaultLogLevel))
            LOGGER.log(defaultLogLevel, "NodeType " + nodeTypeString + " : " + nodeType);

        if (LOGGER.isLoggable(defaultLogLevel))
            LOGGER.log(defaultLogLevel, "Loaded XML Plot file: " + getFile());

        XPath xpath = XPathFactory.newInstance().newXPath();
        Object xmlObject = xpath.evaluate(xpathString, inputSource, nodeType);

        /*
         * If we have a nodeset, we need multiples, otherwise we just need
         * one value, and can do a toString() to set it.
         */
        if (nodeType.equals(XPathConstants.NODESET)) {
            NodeList nl = (NodeList) xmlObject;
            if (LOGGER.isLoggable(defaultLogLevel))
                LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength());

            for (int i = 0; i < nl.getLength(); i++) {
                Node node = nl.item(i);
                if (!new Scanner(node.getTextContent().trim()).hasNextDouble()) {
                    return coalesceTextnodesAsLabelsStrategy(nl, buildNumber);
                }
            }
            return mapNodeNameAsLabelTextContentAsValueStrategy(nl, buildNumber);
        } else if (nodeType.equals(XPathConstants.NODE)) {
            addNodeToList(ret, (Node) xmlObject, buildNumber);
        } else {
            // otherwise we have a single type and can do a toString on it.
            if (xmlObject instanceof NodeList) {
                NodeList nl = (NodeList) xmlObject;

                if (LOGGER.isLoggable(defaultLogLevel))
                    LOGGER.log(defaultLogLevel, "Number of nodes: " + nl.getLength());

                for (int i = 0; i < nl.getLength(); i++) {
                    Node n = nl.item(i);

                    if (n != null && n.getLocalName() != null && n.getTextContent() != null) {
                        addValueToList(ret, label, xmlObject, buildNumber);
                    }
                }

            } else {
                addValueToList(ret, label, xmlObject, buildNumber);
            }
        }
        return ret;

    } catch (XPathExpressionException e) {
        LOGGER.log(Level.SEVERE, "XPathExpressionException for XPath '" + getXpath() + "'", e);
    } finally {
        IOUtils.closeQuietly(in);
    }

    return null;
}

From source file:org.eclipse.lyo.testsuite.oslcv2.FetchResourceTests.java

@Test
public void getValidResourceUsingCOMPACT()
        throws IOException, ParserConfigurationException, SAXException, XPathExpressionException {
    String body = getValidResourceUsingContentType(OSLCConstants.CT_COMPACT);

    Document doc = OSLCUtils.createXMLDocFromResponseBody(body);

    Node compactNode = (Node) OSLCUtils.getXPath().evaluate("/*/oslc_v2:Compact", doc, XPathConstants.NODE);
    assertNotNull(compactNode);/*  w  ww.  j  a  v  a  2  s .  com*/

    // Everything is optional in the oslc:Compact representation.

    NodeList nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./dc:title", compactNode,
            XPathConstants.NODESET);
    int numNodes = nodeList.getLength();
    assertTrue("Expected number of dcterms:titles to be <=1 but was: " + numNodes, numNodes <= 1);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:shortTitle", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:shortTitles to be <=1 but was: " + numNodes, numNodes <= 1);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:icon", compactNode, XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:icon to be <=1 but was: " + numNodes, numNodes <= 1);

    String iconUrl = null;
    if (numNodes == 1) {
        Node rdfAbout = nodeList.item(0).getAttributes().getNamedItemNS(OSLCConstants.RDF, "resource");
        assertNotNull("oslc:icon in oslc:Compact missing rdf:about attribute", rdfAbout);
        iconUrl = rdfAbout.getTextContent();

        HttpResponse response = OSLCUtils.getResponseFromUrl(iconUrl, iconUrl, creds, "*/*", headers);
        int statusCode = response.getStatusLine().getStatusCode();
        EntityUtils.consume(response.getEntity());
        assertTrue(
                "Fetching icon from " + iconUrl + " did not respond with expected code, received " + statusCode,
                200 <= statusCode && statusCode < 400);
    }

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:smallPreview", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:smallPreview is 0 or 1 but was: " + numNodes, numNodes <= 1);
    if (numNodes == 1)
        validateCompactPreview(nodeList);

    nodeList = (NodeList) OSLCUtils.getXPath().evaluate("./oslc_v2:largePreview", compactNode,
            XPathConstants.NODESET);
    numNodes = nodeList.getLength();
    assertTrue("Expected number of oslc:largePreview is 0 or 1 but was: " + numNodes, numNodes <= 1);
    if (numNodes == 1)
        validateCompactPreview(nodeList);
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void serviceDescriptionHasTitle() throws XPathException {
    //Verify that the ServiceDescription has a dc:title child element
    Node title = (Node) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:title", doc,
            XPathConstants.NODE);
    assertNotNull(title);/*from   w ww. j  a  va  2s. c o m*/
    assertFalse(title.getTextContent().isEmpty());

    //Verify that the dc:title child element has no children
    NodeList children = (NodeList) OSLCUtils.getXPath().evaluate("/oslc_cm:ServiceDescriptor/dc:title/*", doc,
            XPathConstants.NODESET);
    assertTrue(children.getLength() == 0);
}

From source file:de.ingrid.iplug.opensearch.converter.IngridRSSConverter.java

/**
 * Extract the score value from a given node and return it as a float value.
 * In case no score node could be found 0.0f is returned. This score will
 * not be put into an IngridHit then.//from   w ww. j av a  2  s .com
 * 
 * @param item
 *            is the node to look for the score entry
 * @return the score but 0.0f if no ranking is supported
 * @throws XPathExpressionException
 */
private float getScore(Node item) throws XPathExpressionException {
    XPath xpath = XPathFactory.newInstance().newXPath();
    Node node = (Node) xpath.evaluate("score", item, XPathConstants.NODE);
    if (node != null) {
        return Float.valueOf(node.getTextContent());
    }
    return 0.0f;
}

From source file:com.adaptris.core.services.jdbc.JdbcIteratingDataCaptureServiceImpl.java

private StatementParameterList createActualParams(XPath xpath, Node n) throws XPathExpressionException {
    StatementParameterList result = new StatementParameterList();
    StatementParameterList original = getStatementParameters();
    for (int args = 1; args <= original.size(); args++) {
        JdbcStatementParameter param = original.get(args - 1);
        // Due to iteratesXpath, we don't use getqueryValue from
        // statementParameter.
        if (isXpathParam(param)) {
            StatementParameterImpl actualParam = (StatementParameterImpl) param.makeCopy();
            Node xpathNode = xpath.selectSingleNode(n, actualParam.getQueryString());
            // queryResult = xpath.selectSingleTextItem(n, actualParam.getQueryString());
            actualParam.setQueryString(xpathNode != null ? xpathNode.getTextContent() : null);
            actualParam.setQueryType(QueryType.constant);
            result.add(actualParam);/*w  ww. j  av  a 2 s  .  c o  m*/
        } else {
            result.add(param.makeCopy());
        }
    }
    return result;
}

From source file:com.msopentech.odatajclient.engine.data.impl.v3.AtomDeserializer.java

public AtomEntry entry(final Element input) {
    if (!ODataConstants.ATOM_ELEM_ENTRY.equals(input.getNodeName())) {
        return null;
    }/*from  w  w  w.  java 2s  . c o  m*/

    final AtomEntry entry = new AtomEntry();

    common(input, entry);

    final String etag = input.getAttribute(ODataConstants.ATOM_ATTR_ETAG);
    if (StringUtils.isNotBlank(etag)) {
        entry.setETag(etag);
    }

    final List<Element> categories = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_CATEGORY);
    if (!categories.isEmpty()) {
        entry.setType(categories.get(0).getAttribute(ODataConstants.ATOM_ATTR_TERM));
    }

    final List<Element> links = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_LINK);
    for (Element linkElem : links) {
        final AtomLink link = new AtomLink();
        link.setRel(linkElem.getAttribute(ODataConstants.ATTR_REL));
        link.setTitle(linkElem.getAttribute(ODataConstants.ATTR_TITLE));
        link.setHref(linkElem.getAttribute(ODataConstants.ATTR_HREF));

        if (ODataConstants.SELF_LINK_REL.equals(link.getRel())) {
            entry.setSelfLink(link);
        } else if (ODataConstants.EDIT_LINK_REL.equals(link.getRel())) {
            entry.setEditLink(link);
        } else if (link.getRel().startsWith(
                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.NAVIGATION_LINK_REL))) {

            link.setType(linkElem.getAttribute(ODataConstants.ATTR_TYPE));
            entry.addNavigationLink(link);

            final List<Element> inlines = XMLUtils.getChildElements(linkElem, ODataConstants.ATOM_ELEM_INLINE);
            if (!inlines.isEmpty()) {
                final List<Element> entries = XMLUtils.getChildElements(inlines.get(0),
                        ODataConstants.ATOM_ELEM_ENTRY);
                if (!entries.isEmpty()) {
                    link.setInlineEntry(entry(entries.get(0)));
                }

                final List<Element> feeds = XMLUtils.getChildElements(inlines.get(0),
                        ODataConstants.ATOM_ELEM_FEED);
                if (!feeds.isEmpty()) {
                    link.setInlineFeed(feed(feeds.get(0)));
                }
            }
        } else if (link.getRel().startsWith(
                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.ASSOCIATION_LINK_REL))) {

            entry.addAssociationLink(link);
        } else if (link.getRel().startsWith(
                client.getWorkingVersion().getNamespaceMap().get(ODataVersion.MEDIA_EDIT_LINK_REL))) {

            entry.addMediaEditLink(link);
        }
    }

    final List<Element> authors = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_AUTHOR);
    if (!authors.isEmpty()) {
        final AtomEntry.Author author = new AtomEntry.Author();
        for (Node child : XMLUtils.getChildNodes(input, Node.ELEMENT_NODE)) {
            if (ODataConstants.ATOM_ELEM_AUTHOR_NAME.equals(XMLUtils.getSimpleName(child))) {
                author.setName(child.getTextContent());
            } else if (ODataConstants.ATOM_ELEM_AUTHOR_URI.equals(XMLUtils.getSimpleName(child))) {
                author.setUri(child.getTextContent());
            } else if (ODataConstants.ATOM_ELEM_AUTHOR_EMAIL.equals(XMLUtils.getSimpleName(child))) {
                author.setEmail(child.getTextContent());
            }
        }
        if (!author.isEmpty()) {
            entry.setAuthor(author);
        }
    }

    final List<Element> actions = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_ACTION);
    for (Element action : actions) {
        final ODataOperation operation = new ODataOperation();
        operation.setMetadataAnchor(action.getAttribute(ODataConstants.ATTR_METADATA));
        operation.setTitle(action.getAttribute(ODataConstants.ATTR_TITLE));
        operation.setTarget(URI.create(action.getAttribute(ODataConstants.ATTR_TARGET)));

        entry.addOperation(operation);
    }

    final List<Element> contents = XMLUtils.getChildElements(input, ODataConstants.ATOM_ELEM_CONTENT);
    if (!contents.isEmpty()) {
        final Element content = contents.get(0);

        List<Element> props = XMLUtils.getChildElements(content, ODataConstants.ELEM_PROPERTIES);
        if (props.isEmpty()) {
            entry.setMediaContentSource(content.getAttribute(ODataConstants.ATOM_ATTR_SRC));
            entry.setMediaContentType(content.getAttribute(ODataConstants.ATTR_TYPE));

            props = XMLUtils.getChildElements(input, ODataConstants.ELEM_PROPERTIES);
            if (!props.isEmpty()) {
                entry.setMediaEntryProperties(props.get(0));
            }
        } else {
            entry.setContent(props.get(0));
        }
    }

    return entry;
}

From source file:org.eclipse.lyo.testsuite.server.oslcv1tests.ServiceDescriptionTests.java

@Test
public void homeElementHasTitleAndUrlChildElements() throws XPathException {
    //Make sure each home element has a title and url
    NodeList hElements = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm:home", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < hElements.getLength(); i++) {
        Node hUrl = (Node) OSLCUtils.getXPath().evaluate("./oslc_cm:url", hElements.item(i),
                XPathConstants.NODE);
        assertNotNull(hUrl);/*from w  w w . ja v  a2  s.  c om*/
        Node hTitle = (Node) OSLCUtils.getXPath().evaluate("./dc:title", hElements.item(i),
                XPathConstants.NODE);
        assertNotNull(hTitle);
        assertFalse(hTitle.getTextContent().isEmpty());
    }
}

From source file:org.apache.camel.component.social.providers.twitter.AbstractTwitterPath.java

protected DefaultSocialData parseStatus(Node aNode) throws TransformerException {
    StreamResult streamResult = new StreamResult(new StringWriter());
    DOMSource domSource = new DOMSource(aNode);
    getTransformer().transform(domSource, streamResult);

    String xmlString = streamResult.getWriter().toString();
    String id = null;/*  w  w w.j  a  va2  s.  c  o m*/
    NodeList childs = aNode.getChildNodes();
    for (int j = 0; j < childs.getLength(); j++) {
        Node child = childs.item(j);
        if (child.getNodeName().equals("id")) {
            id = child.getTextContent();
            break;
        }
    }

    DefaultSocialData socialData = new DefaultSocialData(id, xmlString);
    return socialData;
}

From source file:at.ait.dme.yuma.server.enrichment.SemanticEnrichmentServiceImpl.java

private Collection<SemanticTagGroup> parseUniVieResponse(String text) throws Exception {

    Collection<SemanticTagGroup> resources = new ArrayList<SemanticTagGroup>();

    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(text.getBytes("UTF-8")));

    NodeList childNodes = doc.getChildNodes();
    for (int a = 0; a < childNodes.getLength(); a++) {
        if (childNodes.item(a).getNodeName().equals("entities")) {
            NodeList entities = childNodes.item(a).getChildNodes();
            for (int i = 0; i < entities.getLength(); i++) {
                Node entity = entities.item(i);
                NodeList entityContent = entity.getChildNodes();
                SemanticTagGroup e = new SemanticTagGroup();
                resources.add(e);/*from  ww  w  .  ja v  a2s. c  om*/

                for (int j = 0; j < entityContent.getLength(); j++) {
                    Node n = entityContent.item(j);
                    String nName = n.getNodeName();
                    if (nName.equals(ENTITY_NAME)) {
                        e.setTitle(n.getTextContent());
                    } else if (nName.equals(ENTITY_TYPE)) {
                        e.setType(n.getTextContent());
                    } else if (nName.equals(REFERENCE)) {
                        NodeList referenceContent = n.getChildNodes();
                        String url = "", label = "", description = "";
                        for (int k = 0; k < referenceContent.getLength(); k++) {
                            Node r = referenceContent.item(k);

                            String nodeName = r.getNodeName();
                            if (nodeName.equals(LINK)) {
                                url = r.getTextContent();
                            } else if (nodeName.equals(LINK_LABEL)) {
                                label = r.getTextContent();
                            } else if (nodeName.equals(LINK_ABSTRACT)) {
                                description = r.getTextContent();
                            }
                        }
                        e.addTag(new SemanticTag(e.getTitle(), e.getType(), label, description, url));
                    }
                }
            }
        }
    }
    return resources;
}

From source file:at.ait.dme.yuma.suite.apps.map.server.geo.GeocoderServiceImpl.java

private SemanticTag[] parseGeonamesResponse(CharSequence xml) throws Exception {
    DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
    Document doc = builder.parse(new ByteArrayInputStream(xml.toString().getBytes("UTF-8")));

    ArrayList<SemanticTag> tags = new ArrayList<SemanticTag>();
    NodeList nodes = doc.getElementsByTagName("geoname");

    NodeList children;//from   ww  w  . j a  va2  s  . co  m
    ArrayList<String> countries = new ArrayList<String>();
    for (int i = 0; i < nodes.getLength(); i++) {
        String toponymName = null;
        String geonameId = null;
        String country = null;
        String lat = null;
        String lon = null;
        children = nodes.item(i).getChildNodes();
        for (int j = 0; j < children.getLength(); j++) {
            Node child = children.item(j);
            if (child.getNodeName().equals("toponymName")) {
                toponymName = child.getTextContent();
            } else if (child.getNodeName().equals("geonameId")) {
                geonameId = child.getTextContent();
            } else if (child.getNodeName().equals("countryName")) {
                // Store country --> we'll retrieve their geonameIds later, too!
                country = child.getTextContent();
                if (!countries.contains(country))
                    countries.add(country);
            } else if (child.getNodeName().equals("lat")) {
                lat = child.getTextContent();
            } else if (child.getNodeName().equals("lng")) {
                lon = child.getTextContent();
            }
        }
        if (toponymName != null && country != null && geonameId != null && lat != null && lon != null)
            tags.add(new SemanticTag(toponymName, getAlternativePlacenames(toponymName), "Place", "en",
                    toponymName + ", " + country + " (city) \nLatitude: " + lat + " \nLongitude: " + lon,
                    GEONAMES_URI_TEMPLATE.replace("@id@", geonameId)));
    }

    for (SemanticTag countryTag : getCountries(countries)) {
        tags.add(0, countryTag);
    }

    return tags.toArray(new SemanticTag[tags.size()]);
}