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.rbmhtechnology.apidocserver.service.RepositoryService.java

public List<String> getAvailableVersions(String groupId, String artifactId) throws RepositoryException {
    LOG.info("getAvailableVersions('{}','{}')", groupId, artifactId);

    File mavenMetadataXmlFile = downloadMavenMetadataXml(groupId, artifactId);

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();

    // Using factory get an instance of document builder
    DocumentBuilder db;//from   w  w  w  .  ja  v a 2s  .c  o m

    List<String> versions = Lists.newArrayList();
    try {
        db = dbf.newDocumentBuilder();

        // parse using builder to get DOM representation of the XML file
        Document dom = db.parse(mavenMetadataXmlFile);

        // get the root element
        Element rootElement = dom.getDocumentElement();
        NodeList versionNodeList = rootElement.getElementsByTagName("version");

        for (int i = 0; i < versionNodeList.getLength(); i++) {
            Node item = versionNodeList.item(i);
            if (!versions.contains(item.getTextContent()))
                versions.add(item.getTextContent());
        }

    } catch (SAXException | IOException | ParserConfigurationException e) {
        throw new RepositoryException("Could not parse maven-metadata.xml for groupId: '" + groupId
                + "' and artifactId: '" + artifactId + "'", e);
    }

    // sort list descending, i.e. latest version first
    Collections.sort(versions, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o2.compareTo(o1);
        }
    });

    return versions;
}

From source file:org.ambraproject.article.service.FetchArticleServiceImpl.java

/**
 * Returns abbreviated journal name//from  www .j av a 2s. c o  m
 * @param doc article xml
 * @return abbreviated journal name
 */
public String getJournalAbbreviation(Document doc) {
    String journalAbbrev = "";

    if (doc == null) {
        return journalAbbrev;
    }

    try {
        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();

        XPathExpression expr = xpath.compile("//journal-meta/journal-id[@journal-id-type='nlm-ta']");
        Object resultObj = expr.evaluate(doc, XPathConstants.NODE);
        Node resultNode = (Node) resultObj;
        if (resultNode != null) {
            journalAbbrev = resultNode.getTextContent();
        }
    } catch (Exception e) {
        log.error("Error occurred while getting abbreviated journal name.", e);
    }

    return journalAbbrev;
}

From source file:zh.wang.android.yweathergetter.YahooWeather.java

private WeatherInfo parseWeatherInfo(Context context, Document doc) {
    WeatherInfo weatherInfo = new WeatherInfo();
    try {/*from www .  j av a 2s  . c  o  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.setCurrentTemp(
                Integer.parseInt(currentConditionNode.getAttributes().getNamedItem("temp").getNodeValue()));
        weatherInfo.setCurrentConditionDate(
                currentConditionNode.getAttributes().getNamedItem("date").getNodeValue());

        if (mNeedDownloadIcons) {
            weatherInfo.setCurrentConditionIcon(
                    ImageUtils.getBitmapFromWeb(weatherInfo.getCurrentConditionIconURL()));
        }

        for (int i = 0; i < FORECAST_INFO_MAX_SIZE; i++) {
            WeatherInfo.ForecastInfo forecastInfo = weatherInfo.getForecastInfoList().get(i);
            this.parseForecastInfo(forecastInfo, doc, i);
        }

    } catch (NullPointerException e) {
        YahooWeatherLog.printStack(e);
        if (mExceptionListener != null)
            mExceptionListener.onFailParsing(e);
        weatherInfo = null;
    }

    return weatherInfo;
}

From source file:edu.sabanciuniv.sentilab.sare.controllers.opinion.OpinionDocumentFactory.java

private OpinionDocument create(OpinionDocument document, OpinionCorpus corpus, Node node)
        throws XPathException {

    try {//  www .  j av a2 s .  c  o m
        Validate.notNull(node, CannedMessages.NULL_ARGUMENT, "node");
    } catch (NullPointerException e) {
        throw new IllegalFactoryOptionsException(e);
    }

    XPathFactory factory = XPathFactory.newInstance();
    XPath xpath = factory.newXPath();
    Double polarity = (Double) xpath.compile("./@polarity").evaluate(node, XPathConstants.NUMBER);

    return this.create(document, corpus, node.getTextContent().trim(), polarity);
}

From source file:com.vmware.o11n.plugin.powershell.model.RemotePsType.java

public Object read(Node node) {
    Object res = "";
    RemotePsType type = getType(node);/*from   w  w  w . ja v a2 s. c  om*/
    if (type == RemotePsType.PrimitiveType) {
        res = convertPrimitiveType(node.getNodeName(), node.getTextContent());
    } else if (type == RemotePsType.List) {
        res = readList(node);
    } else if (type == RemotePsType.Dictionary) {
        res = readDictionary(node);
    } else if (type == RemotePsType.Object) {
        res = readObject(node);
    } else if (type == RemotePsType.Ref) {
        String refId = node.getAttributes().getNamedItem(ATTR_REF_ID).getNodeValue();
        return getObjByRefId(refId);
    } else {
        throw new RuntimeException("Unsupported type.");
    }

    return res;
}

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

@Test
public void serviceProvidersHaveValidTitles() throws XPathException {
    //Get all entries, parse out which have embedded ServiceProviders and check the titles
    NodeList entries = (NodeList) OSLCUtils.getXPath().evaluate("//oslc_disc:entry/*", doc,
            XPathConstants.NODESET);
    for (int i = 0; i < entries.getLength(); i++) {
        Node provider = (Node) OSLCUtils.getXPath().evaluate(
                "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider", doc, XPathConstants.NODE);
        //This entry has a catalog, check that it has a title
        if (provider != null) {
            Node pTitle = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/dc:title", doc,
                    XPathConstants.NODE);
            assertNotNull(pTitle);/* w  w w.ja va 2s. com*/
            //Make sure the title isn't empty
            assertFalse(pTitle.getTextContent().isEmpty());
            Node child = (Node) OSLCUtils.getXPath().evaluate(
                    "//oslc_disc:entry[" + (i + 1) + "]/oslc_disc:ServiceProvider/dc:title/*", doc,
                    XPathConstants.NODE);
            //Make sure the title has no child elements
            assertTrue(child == null);
        }
    }
}

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

protected void validateNonEmptyResponse(String query)
        throws XPathExpressionException, IOException, ParserConfigurationException, SAXException {
    String queryUrl = OSLCUtils.addQueryStringToURL(currentUrl, query);
    HttpResponse response = OSLCUtils.getResponseFromUrl(setupBaseUrl, queryUrl, basicCreds,
            OSLCConstants.CT_XML, headers);
    int statusCode = response.getStatusLine().getStatusCode();
    if (HttpStatus.SC_OK != statusCode) {
        EntityUtils.consume(response.getEntity());
        throw new IOException("Response code: " + statusCode + " for " + queryUrl);
    }//from   w w w .j a va  2  s. c  o  m

    String responseBody = EntityUtils.toString(response.getEntity());

    Document doc = OSLCUtils.createXMLDocFromResponseBody(responseBody);
    Node results = (Node) OSLCUtils.getXPath().evaluate("//oslc:ResponseInfo/@rdf:about", doc,
            XPathConstants.NODE);

    // Only test oslc:ResponseInfo if found
    if (results != null) {
        assertEquals("Expended ResponseInfo/@rdf:about to equal request URL", queryUrl, results.getNodeValue());
        results = (Node) OSLCUtils.getXPath().evaluate("//oslc:totalCount", doc, XPathConstants.NODE);
        if (results != null) {
            int totalCount = Integer.parseInt(results.getTextContent());
            assertTrue("Expected oslc:totalCount > 0", totalCount > 0);
        }

        NodeList resultList = (NodeList) OSLCUtils.getXPath().evaluate("//rdf:Description/rdfs:member", doc,
                XPathConstants.NODESET);
        assertNotNull("Expected rdfs:member(s)", resultList);
        assertNotNull("Expected > 1 rdfs:member(s)", resultList.getLength() > 0);
    }
}

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

@Test
public void testKeyOverrides() throws Exception {
    final Map<String, String> keyOverrides = new HashMap<>();
    keyOverrides.put("timestamp", "dateTime");
    keyOverrides.put("sequence", "seq");
    final Map<String, String> metaData = new LinkedHashMap<>();
    metaData.put("test-key-1", "test-value-1");
    metaData.put("key-no-value", null);
    // Configure the subsystem
    configure(keyOverrides, metaData, true);

    final String msg = "Logging test: XmlFormatterTestCase.defaultLoggingTest";
    final Map<String, String> params = new LinkedHashMap<>();
    // Indicate we need an exception logged
    params.put(LoggingServiceActivator.LOG_EXCEPTION_KEY, "true");
    // Add an NDC value
    params.put(LoggingServiceActivator.NDC_KEY, "test.ndc.value");
    // Add some map entries for MDC values
    params.put("mdcKey1", "mdcValue1");
    params.put("mdcKey2", "mdcValue2");

    final List<String> expectedKeys = createDefaultKeys();
    expectedKeys.remove("timestamp");
    expectedKeys.remove("sequence");
    expectedKeys.addAll(keyOverrides.values());
    expectedKeys.add("metaData");
    expectedKeys.add("exception");
    expectedKeys.add("stackTrace");
    expectedKeys.add("sourceFileName");
    expectedKeys.add("sourceMethodName");
    expectedKeys.add("sourceClassName");
    expectedKeys.add("sourceLineNumber");
    expectedKeys.add("sourceModuleVersion");
    expectedKeys.add("sourceModuleName");

    final int statusCode = getResponse(msg, params);
    Assert.assertEquals("Invalid response statusCode: " + statusCode, statusCode, HttpStatus.SC_OK);

    final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    final DocumentBuilder builder = factory.newDocumentBuilder();

    // Validate each line
    for (String s : readLogLines()) {
        final Document doc = builder.parse(new InputSource(new StringReader(s)));

        validateDefault(doc, expectedKeys, msg);

        // Timestamp should have been renamed to dateTime
        Assert.assertEquals("Found timestamp entry in " + s, 0,
                doc.getElementsByTagName("timestamp").getLength());

        // Sequence should have been renamed to seq
        Assert.assertEquals("Found sequence entry in " + s, 0,
                doc.getElementsByTagName("sequence").getLength());

        // Validate MDC
        final NodeList mdcNodes = doc.getElementsByTagName("mdc");
        Assert.assertEquals(1, mdcNodes.getLength());
        final Node mdcItem = mdcNodes.item(0);
        final NodeList mdcChildren = mdcItem.getChildNodes();
        Assert.assertEquals(2, mdcChildren.getLength());
        final Node mdc1 = mdcChildren.item(0);
        Assert.assertEquals("mdcKey1", mdc1.getNodeName());
        Assert.assertEquals("mdcValue1", mdc1.getTextContent());
        final Node mdc2 = mdcChildren.item(1);
        Assert.assertEquals("mdcKey2", mdc2.getNodeName());
        Assert.assertEquals("mdcValue2", mdc2.getTextContent());

        // Validate the meta-data
        final NodeList metaDataNodes = doc.getElementsByTagName("metaData");
        Assert.assertEquals(2, metaDataNodes.getLength());
        Assert.assertEquals("test-key-1",
                metaDataNodes.item(0).getAttributes().getNamedItem("key").getTextContent());
        Assert.assertEquals("test-value-1", metaDataNodes.item(0).getTextContent());
        Assert.assertEquals("key-no-value",
                metaDataNodes.item(1).getAttributes().getNamedItem("key").getTextContent());
        Assert.assertEquals("", metaDataNodes.item(1).getTextContent());

        validateStackTrace(doc, true, true);
    }//from w  w w  .ja va 2s.  co  m
}

From source file:au.com.ors.rest.dao.JobAppDAO.java

/**
 * Update an existing job application<br/>
 * //from  ww w .  jav  a  2  s.  c  o m
 * @param application
 *            job application to be updated
 * @throws JobApplicationNotFoundException
 * @throws TransformerException
 */
public JobApplication update(JobApplication application)
        throws JobApplicationNotFoundException, TransformerException {
    int jobIndex = -1;
    for (int i = 0; i < jobAppList.size(); ++i) {
        if (jobAppList.get(i).get_appId().equals(application.get_appId())) {
            // found
            jobIndex = i;
            break;
        }
    }

    if (jobIndex < 0) {
        throw new JobApplicationNotFoundException("Application with _appId=" + application.get_appId()
                + " not found in database while updating.");
    }

    jobAppList.set(jobIndex, application);

    // update section to XML
    Element root = dom.getDocumentElement();
    NodeList nodeList = root.getChildNodes();

    for (int i = 0; i < nodeList.getLength(); ++i) {
        Node node = nodeList.item(i);
        if (!node.getNodeName().equals("JobApplication")) {
            continue;
        }

        NodeList appInfoList = node.getChildNodes();
        for (int j = 0; j < appInfoList.getLength(); ++j) {
            Node current = appInfoList.item(j);

            // _appId, _jobId cannot be updated after the application
            // created already
            if (current.getNodeType() == Node.ELEMENT_NODE) {
                if (current.getNodeName().equals("_appId")) {
                    if (!current.getTextContent().equals(application.get_appId())) {
                        break; // not the right application ID
                    }
                } else if (current.getNodeName().equals("_jobId")) {
                    continue;
                } else if (current.getNodeName().equals("driverLicenseNumber")) {
                    current.setTextContent(application.getDriverLicenseNumber());
                } else if (current.getNodeName().equals("fullName")) {
                    current.setTextContent(application.getFullName());
                } else if (current.getNodeName().equals("postCode")) {
                    current.setTextContent(application.getPostCode());
                } else if (current.getNodeName().equals("textCoverLetter")) {
                    current.setTextContent(application.getTextCoverLetter());
                } else if (current.getNodeName().equals("textBriefResume")) {
                    current.setTextContent(application.getTextBriefResume());
                } else if (current.getNodeName().equals("status")) {
                    current.setTextContent(application.getStatus());
                }
            }
        }
    }

    // write dom
    DOMSource source = new DOMSource(dom);
    TransformerFactory transformerFactory = TransformerFactory.newInstance();
    Transformer transformer = transformerFactory.newTransformer();
    StreamResult result = new StreamResult(dataUrl);
    transformer.transform(source, result);
    return application;
}