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:com.michael.feng.utils.YahooWeather4a.YahooWeatherUtils.java

private WeatherInfo parseWeatherInfo(Context context, Document doc) {
    WeatherInfo weatherInfo = new WeatherInfo();
    try {//from  w  w  w.  j  a va 2  s  .  co m

        Node titleNode = doc.getElementsByTagName("title").item(0);

        if (titleNode.getTextContent().equals(YAHOO_WEATHER_ERROR)) {
            return null;
        }

        weatherInfo.setTitle(titleNode.getTextContent());
        weatherInfo.setDescription(doc.getElementsByTagName("description").item(0).getTextContent());
        weatherInfo.setLanguage(doc.getElementsByTagName("language").item(0).getTextContent());
        weatherInfo.setLastBuildDate(doc.getElementsByTagName("lastBuildDate").item(0).getTextContent());

        Node locationNode = doc.getElementsByTagName("yweather:location").item(0);
        weatherInfo.setLocationCity(locationNode.getAttributes().getNamedItem("city").getNodeValue());
        weatherInfo.setLocationRegion(locationNode.getAttributes().getNamedItem("region").getNodeValue());
        weatherInfo.setLocationCountry(locationNode.getAttributes().getNamedItem("country").getNodeValue());

        Node windNode = doc.getElementsByTagName("yweather:wind").item(0);
        weatherInfo.setWindChill(windNode.getAttributes().getNamedItem("chill").getNodeValue());
        weatherInfo.setWindDirection(windNode.getAttributes().getNamedItem("direction").getNodeValue());
        weatherInfo.setWindSpeed(windNode.getAttributes().getNamedItem("speed").getNodeValue());

        Node atmosphereNode = doc.getElementsByTagName("yweather:atmosphere").item(0);
        weatherInfo
                .setAtmosphereHumidity(atmosphereNode.getAttributes().getNamedItem("humidity").getNodeValue());
        weatherInfo.setAtmosphereVisibility(
                atmosphereNode.getAttributes().getNamedItem("visibility").getNodeValue());
        weatherInfo
                .setAtmospherePressure(atmosphereNode.getAttributes().getNamedItem("pressure").getNodeValue());
        weatherInfo.setAtmosphereRising(atmosphereNode.getAttributes().getNamedItem("rising").getNodeValue());

        Node astronomyNode = doc.getElementsByTagName("yweather:astronomy").item(0);
        weatherInfo.setAstronomySunrise(astronomyNode.getAttributes().getNamedItem("sunrise").getNodeValue());
        weatherInfo.setAstronomySunset(astronomyNode.getAttributes().getNamedItem("sunset").getNodeValue());

        weatherInfo.setConditionTitle(doc.getElementsByTagName("title").item(2).getTextContent());
        weatherInfo.setConditionLat(doc.getElementsByTagName("geo:lat").item(0).getTextContent());
        weatherInfo.setConditionLon(doc.getElementsByTagName("geo:long").item(0).getTextContent());

        Node currentConditionNode = doc.getElementsByTagName("yweather:condition").item(0);
        weatherInfo.setCurrentCode(
                Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("code").getNodeValue()));
        weatherInfo.setCurrentText(currentConditionNode.getAttributes().getNamedItem("text").getNodeValue());
        weatherInfo.setCurrentTempF(
                Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("temp").getNodeValue()));
        weatherInfo.setCurrentConditionDate(
                currentConditionNode.getAttributes().getNamedItem("date").getNodeValue());

        Node forecast1ConditionNode = doc.getElementsByTagName("yweather:forecast").item(0);
        weatherInfo.setForecast1Code(
                Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("code").getNodeValue()));
        weatherInfo
                .setForecast1Text(forecast1ConditionNode.getAttributes().getNamedItem("text").getNodeValue());
        weatherInfo
                .setForecast1Date(forecast1ConditionNode.getAttributes().getNamedItem("date").getNodeValue());
        weatherInfo.setForecast1Day(forecast1ConditionNode.getAttributes().getNamedItem("day").getNodeValue());
        weatherInfo.setForecast1TempHighF(
                Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("high").getNodeValue()));
        weatherInfo.setForecast1TempLowF(
                Integer.parseInt(forecast1ConditionNode.getAttributes().getNamedItem("low").getNodeValue()));

        Node forecast2ConditionNode = doc.getElementsByTagName("yweather:forecast").item(1);
        weatherInfo.setForecast2Code(
                Integer.parseInt(forecast2ConditionNode.getAttributes().getNamedItem("code").getNodeValue()));
        weatherInfo
                .setForecast2Text(forecast2ConditionNode.getAttributes().getNamedItem("text").getNodeValue());
        weatherInfo
                .setForecast2Date(forecast2ConditionNode.getAttributes().getNamedItem("date").getNodeValue());
        weatherInfo.setForecast2Day(forecast2ConditionNode.getAttributes().getNamedItem("day").getNodeValue());
        weatherInfo.setForecast2TempHighF(
                Integer.parseInt(forecast2ConditionNode.getAttributes().getNamedItem("high").getNodeValue()));
        weatherInfo.setForecast2TempLowF(
                Integer.parseInt(forecast2ConditionNode.getAttributes().getNamedItem("low").getNodeValue()));

    } catch (NullPointerException e) {
        e.printStackTrace();
        Toast.makeText(context, "Parse XML failed - Unrecognized Tag", Toast.LENGTH_SHORT).show();
        weatherInfo = null;
    }

    return weatherInfo;
}

From source file:com.tomdignan.android.opencnam.library.teststub.test.OpenCNAMRequestTestCase.java

public void testXMLRequest() {
    mOpenCNAMRequest.setSerializationFormat(OpenCNAMRequest.FORMAT_XML);
    // TEXT is default.
    String response = null;//from   www  . j  a  v  a2  s.  c  o m

    try {
        response = (String) mOpenCNAMRequest.execute();
    } catch (ClientProtocolException e) {
        Log.e(TAG, "ClientProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "ClientProtocolException: " + e.getMessage());
    }

    assertNotNull(response);
    ByteArrayInputStream inputStream = new ByteArrayInputStream(response.getBytes());
    Document document = null;

    try {
        document = mDocumentBuilder.parse(inputStream);
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    assertNotNull(document);

    Element root = document.getDocumentElement();

    String rootName = root.getNodeName();
    assertNotNull(rootName);
    assertEquals(rootName, "object");

    NodeList children = root.getChildNodes();
    assertNotNull(children);

    int size = children.getLength();
    assertEquals(size, 2);

    Node cnamNode = children.item(0);
    assertNotNull(cnamNode);

    String cnamValue = cnamNode.getTextContent().trim();
    assertEquals(cnamValue, CNAM);

    String cnamNodeName = cnamNode.getNodeName();
    assertEquals(cnamNodeName, "cnam");

    Node numberNode = children.item(1);
    assertNotNull(numberNode);

    String numberName = numberNode.getNodeName().trim();

    assertNotNull(numberName);
    assertEquals(numberName, "number");

    String numberValue = numberNode.getTextContent().trim();

    assertNotNull(numberValue);
    assertEquals(numberValue, NUMBER);
}

From source file:de.rub.nds.burp.utilities.attacks.signatureFaking.SignatureFakingOracle.java

/**
 * Crawls all the collected KeyInfo elements and extracts certificates
 *///  ww w.j a  va  2s  .  c  om
private void crawlKeyInfoElements() {
    for (Node ki : keyInfoElements) {
        List<Element> l = DomUtilities.findChildren(ki, "X509Certificate", NamespaceConstants.URI_NS_DS, true);
        if (l.size() > 0) {
            Node x509cert = l.get(0);
            if (x509cert != null && x509cert.getLocalName().equals("X509Certificate")) {
                certificates.add(x509cert.getTextContent());
            }
        }
    }
}

From source file:eu.guardiansystems.livesapp.android.ui.GMapDirections.java

public int getDistanceValue(Document doc) {
    try {/*from  w ww .j av a 2 s. com*/
        NodeList nl1 = doc.getElementsByTagName("distance");
        Node node1 = null;
        node1 = nl1.item(nl1.getLength() - 1);
        NodeList nl2 = node1.getChildNodes();
        Node node2 = nl2.item(getNodeIndex(nl2, "value"));

        return Integer.parseInt(node2.getTextContent());
    } catch (Exception e) {
        return -1;
    }
    /*
     * NodeList nl1 = doc.getElementsByTagName("distance"); Node node1 =
     * null; if (nl1.getLength() > 0) node1 = nl1.item(nl1.getLength() - 1);
     * if (node1 != null) { NodeList nl2 = node1.getChildNodes(); Node node2
     * = nl2.item(getNodeIndex(nl2, "value")); Log.i("DistanceValue",
     * node2.getTextContent()); return
     * Integer.parseInt(node2.getTextContent()); } else return 0;
     */
}

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

@Test
public void validateUrlsInServiceDescription() throws IOException, XPathException {
    //Get all referenced oslc_cm:url elements in the Description Document
    NodeList urlElements = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_cm:url", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < urlElements.getLength(); i++) {
        Node urlElement = urlElements.item(i);
        String url = urlElement.getTextContent();

        //Perform HTTP GET request on the URL and verify it exists in some form
        HttpResponse urlResponse = OSLCUtils.getResponseFromUrl(baseUrl, url, basicCreds, "*/*");
        EntityUtils.consume(urlResponse.getEntity());
        assertFalse(urlResponse.getStatusLine().getStatusCode() == 404);
    }//from   ww w . jav  a2s.  co  m
}

From source file:Importers.ImportReportCompiler.java

private Vector getHosts(Node node) {
    Vector hosts = new Vector();
    NodeList children = node.getChildNodes();
    for (int i = 0; i < children.getLength(); i++) {
        Node n = children.item(i);
        if (n.getNodeType() == Node.ELEMENT_NODE) {
            String name = n.getNodeName();
            String value = n.getTextContent();
            if (name.equalsIgnoreCase("host")) {
                Host host = getHost(n);//from   ww w.  ja  v  a 2 s.c  om
                hosts.addElement(host);
            }
        }
    }
    return hosts;
}

From source file:com.android.ePerion.gallery.mapEperion.GoogleMapEperion.java

/**
 * Get a list of GeoPoint in order to draw the driving direction between two geoPoint.
 * @param lat1 Latitude of the source geoPoint.
 * @param lon1 Longitude of the source geoPoint.
 * @param lat2 Latitude of the destination.
 * @param lon2 Longitude of the destination.
 * @return A list of geoPoints.//  w w  w . ja  v  a 2s  .com
 */
public ArrayList<GeoPoint> getDirections(double lat1, double lon1, double lat2, double lon2) {
    //URL to send to the Google Map API in order to get the route between two points.
    String url = "http://maps.googleapis.com/maps/api/directions/xml?origin=" + lat1 + "," + lon1
            + "&destination=" + lat2 + "," + lon2 + "&sensor=false&units=metric";
    String tag[] = { "lat", "lng" };
    ArrayList<GeoPoint> list_of_geopoints = new ArrayList<GeoPoint>();
    HttpResponse response = null;
    //Send the HTTP request to the servers.
    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpPost httpPost = new HttpPost(url);
        response = httpClient.execute(httpPost, localContext);
        InputStream in = response.getEntity().getContent();
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(in);
        //Parse the XML document, returned by the Google API, to store the geoPoints extracted.
        if (doc != null) {
            NodeList nl1, nl2;
            nl1 = doc.getElementsByTagName(tag[0]);
            nl2 = doc.getElementsByTagName(tag[1]);
            if (nl1.getLength() > 0) {
                list_of_geopoints = new ArrayList<GeoPoint>();
                for (int i = 0; i < nl1.getLength(); i++) {
                    Node node1 = nl1.item(i);
                    Node node2 = nl2.item(i);
                    double lat = Double.parseDouble(node1.getTextContent());
                    double lng = Double.parseDouble(node2.getTextContent());
                    list_of_geopoints.add(new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6)));
                }
            } else {
                // No points found
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return list_of_geopoints;
}

From source file:com.googlecode.ehcache.annotations.config.EhCacheConfigBeanDefinitionParser.java

/**
 * @param evictExpiredElement//from  ww  w  .  j  av  a  2s . c o  m
 * @return The list of {@link CacheNameMatcher}s to use for finding caches to evict
 */
protected List<CacheNameMatcher> parseEvictExpiredElement(final Element evictExpiredElement) {
    List<CacheNameMatcher> cacheNameMatchers = new ArrayList<CacheNameMatcher>();
    final NodeList childNodes = evictExpiredElement.getChildNodes();
    final int childNodesLength = childNodes.getLength();
    boolean configContainsExcludes = false;
    boolean configContainsIncludes = false;
    if (0 != childNodesLength) {
        for (int index = 0; index < childNodesLength; index++) {
            final Node childNode = childNodes.item(index);
            if (Node.ELEMENT_NODE == childNode.getNodeType()) {
                final String childName = childNode.getLocalName();
                NamedNodeMap childAttributes = childNode.getAttributes();
                Node nameAttr = childAttributes.getNamedItem(XSD_ATTRIBUTE__NAME);
                CacheNameMatcher matcher = null;
                if (null != nameAttr) {
                    String matcherValue = nameAttr.getTextContent();
                    matcher = new ExactCacheNameMatcherImpl(matcherValue);
                } else {
                    Node patternAttr = childAttributes.getNamedItem(XSD_ATTRIBUTE__PATTERN);
                    if (null != patternAttr) {
                        String matcherValue = patternAttr.getTextContent();
                        matcher = new PatternCacheNameMatcherImpl(matcherValue);
                    }
                }

                if (null != matcher) {
                    if (XSD_ELEMENT__INCLUDE.equals(childName)) {
                        cacheNameMatchers.add(matcher);
                        configContainsIncludes = true;
                    } else if (XSD_ELEMENT__EXCLUDE.equals(childName)) {
                        cacheNameMatchers.add(new NotCacheNameMatcherImpl(matcher));
                        configContainsExcludes = true;
                    }
                }
            }
        }
    }

    if (0 == cacheNameMatchers.size()) {
        // no include/exclude elements found
        cacheNameMatchers = Collections.singletonList(INCLUDE_ALL_CACHE_NAME_MATCHER);
    } else if (!configContainsIncludes && configContainsExcludes) {
        //config contains excludes only
        // create a new list with a Include all matcher at the front
        List<CacheNameMatcher> newList = new ArrayList<CacheNameMatcher>();
        newList.add(INCLUDE_ALL_CACHE_NAME_MATCHER);
        newList.addAll(cacheNameMatchers);
        cacheNameMatchers = newList;
    }

    return Collections.unmodifiableList(cacheNameMatchers);
}

From source file:de.undercouch.citeproc.zotero.ZoteroConnector.java

@Override
protected Map<String, Object> parseResponse(Response response) throws IOException {
    String contentType = response.getHeader("Content-Type");
    InputStream is = response.getInputStream();
    Reader r = new BufferedReader(new InputStreamReader(is));
    if (contentType != null && contentType.equals("application/atom+xml")) {
        //response is an Atom. parse it...
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        Document doc;/*  w  w  w.  j  av a 2s .  c  o m*/
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            InputSource source = new InputSource(r);
            doc = builder.parse(source);
        } catch (SAXException e) {
            throw new IOException("Could not parse server response", e);
        } catch (ParserConfigurationException e) {
            throw new IOException("Could not create XML parser", e);
        }

        Map<String, Object> result = new HashMap<String, Object>();

        //extract content in 'csljson' format
        Element feed = doc.getDocumentElement();
        NodeList entries = feed.getElementsByTagName("entry");
        for (int i = 0; i < entries.getLength(); ++i) {
            String key = null;
            String csljson = null;

            Node entry = entries.item(i);
            if (entry instanceof Element) {
                Element entryElem = (Element) entry;
                NodeList keys = entryElem.getElementsByTagNameNS("http://zotero.org/ns/api", "key");
                if (keys.getLength() > 0) {
                    key = keys.item(0).getTextContent().trim();
                    NodeList contents = entryElem.getElementsByTagName("content");
                    if (contents.getLength() > 0) {
                        Node content = contents.item(0);
                        Node type = content.getAttributes().getNamedItemNS("http://zotero.org/ns/api", "type");
                        if (type != null && type.getTextContent().equals(CSLJSON)) {
                            csljson = content.getTextContent().trim();
                        }
                    }
                }
            }

            if (csljson == null || csljson.isEmpty()) {
                throw new IOException("Could not extract CSL json content from entry");
            }

            Map<String, Object> item = new JsonParser(new JsonLexer(new StringReader(csljson))).parseObject();
            result.put(key, item);
        }

        return result;
    } else {
        return super.parseResponse(response);
    }
}

From source file:org.apromore.plugin.deployment.yawl.YAWLDeploymentPluginUnitTest.java

@Test
public void testConnectionIssues() throws IOException, JAXBException, SAXException, PluginException {
    YAWLEngineClientFactory mockClientFactory = EasyMock.createMock(YAWLEngineClientFactory.class);
    YAWLEngineClient mockClient = EasyMock.createMock(YAWLEngineClient.class);

    EasyMock.expect(mockClientFactory.newInstance(EasyMock.anyObject(String.class),
            EasyMock.anyObject(String.class), EasyMock.anyObject(String.class))).andReturn(mockClient);
    Node response = EasyMock.createMock(Node.class);
    EasyMock.expect(response.getNodeName()).andReturn("failure");
    EasyMock.expect(response.getTextContent()).andReturn("Could not connect");
    EasyMock.expect(mockClient.connectToYAWL()).andReturn(response);

    EasyMock.replay(mockClientFactory);/*from www  . j  ava2 s  .co m*/
    EasyMock.replay(mockClient);
    EasyMock.replay(response);

    deploymentPlugin.setEngineClientFactory(mockClientFactory);

    try (BufferedInputStream cpfInputStream = new BufferedInputStream(
            new FileInputStream("src/test/resources/SimpleMakeTripProcess.yawl.cpf"))) {
        CanonicalProcessType cpf = CPFSchema.unmarshalCanonicalFormat(cpfInputStream, true).getValue();
        PluginRequestImpl request = new PluginRequestImpl();
        request.addRequestProperty(new RequestParameterType<String>("yawlEngineUrl",
                "http://localhost:" + server.getServiceAddress().getPort() + "/yawl/ia"));
        request.addRequestProperty(new RequestParameterType<String>("yawlEngineUsername", "admin"));
        request.addRequestProperty(new RequestParameterType<String>("yawlEnginePassword", "YAWL"));

        try {
            deploymentPlugin.deployProcess(cpf, request);
            fail("Should have thrown DeploymentException!");
        } catch (DeploymentException e) {
        }

    }

    EasyMock.verify(mockClientFactory);
    EasyMock.verify(mockClient);
    EasyMock.verify(response);
}