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.esri.gpt.server.openls.provider.services.reversegeocode.ReverseGeocodeProvider.java

/**
 * Parses reverse Geocode response./*from   w w w .j a v  a  2s.  c om*/
 * @param sResponse
 * @return
 * @throws Throwable
 */
private GeocodedAddress parseReverseGeocodeResponse(String sResponse) throws Throwable {
    GeocodedAddress addr = new GeocodedAddress();
    try {

        JSONObject jResponse = new JSONObject(sResponse);

        String xResponse = "<?xml version='1.0'?><response>" + org.json.XML.toString(jResponse) + "</response>";
        LOGGER.info("XML from JSON = " + xResponse);

        String addressName = "";

        Address respAddr = null;
        String street = "";
        String intStreet = "";
        String city = "";
        String state = "";
        String zip = "";
        String scoreStr = "";
        String x = "";
        String y = "";
        String country = "US";

        DocumentBuilderFactory xfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = xfactory.newDocumentBuilder();
        InputSource inStream = new InputSource();
        inStream.setCharacterStream(new StringReader(xResponse));
        Document doc = db.parse(inStream);

        doc.getDocumentElement().normalize();
        LOGGER.info("Root element " + doc.getDocumentElement().getNodeName());
        NodeList nodeLst = doc.getChildNodes();
        LOGGER.info("Information of all candidates:");

        for (int s = 0; s < nodeLst.getLength(); s++) {
            Node fstNode = nodeLst.item(s);
            Element fstElmnt = (Element) fstNode;

            street = "";
            intStreet = "";
            city = "";
            state = "";
            zip = "";
            scoreStr = "";

            // LOCATION
            NodeList locationList = fstElmnt.getElementsByTagName("location");
            Element fstNmElmnt = (Element) locationList.item(0);
            NodeList nodeY = fstNmElmnt.getElementsByTagName("y");
            y = nodeY.item(0).getTextContent();
            LOGGER.info("y = " + y);
            NodeList nodeX = fstNmElmnt.getElementsByTagName("x");
            x = nodeX.item(0).getTextContent();
            LOGGER.info("x = " + x);

            // ADDRESS
            NodeList addressList = fstElmnt.getElementsByTagName("address");
            Node addressNode = addressList.item(0);
            addressName = addressList.item(0).getTextContent();
            LOGGER.info("addressName = " + addressName);
            NodeList children = addressNode.getChildNodes();
            for (int i = 0; i < children.getLength(); i++) {
                Node child = children.item(i);
                if (child.getNodeName().equalsIgnoreCase("address")) {
                    street = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("city")) {
                    city = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("zip")) {
                    zip = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("state")) {
                    state = child.getTextContent();
                } else if (child.getNodeName().equalsIgnoreCase("country")) {
                    country = child.getTextContent();
                }
            }

            // SCORE
            NodeList scoreList = fstElmnt.getElementsByTagName("score");
            if (scoreList != null && scoreList.getLength() > 0) {
                scoreStr = scoreList.item(0).getTextContent();
                new Double(scoreStr);
                LOGGER.info("score = " + scoreStr);
            }

            // NOW ADD THIS RESULT TO THE OUTPUT pos
            respAddr = new Address();
            respAddr.setStreet(street);
            respAddr.setMunicipality(city);
            respAddr.setPostalCode(zip);
            respAddr.setCountrySubdivision(state);
            respAddr.setIntersection(intStreet);

            addr.setX(x);
            addr.setY(y);
            addr.setAddress(respAddr);
            addr.setCountry(country);

        }
    } catch (Exception p_e) {
        LOGGER.severe("Caught Exception" + p_e.getMessage());
    }
    return addr;
}

From source file:com.runwaysdk.request.ClientRequestManager.java

/**
 * Parses an XML document to extract connection information, ultimately creating Connection objects.
 * //from  w w w.  j  av a  2  s  .  c  om
 * @param document
 */
private void parseDocument(Document document) {
    NodeList connectionsList = document.getElementsByTagName(CONNECTION_ELEMENT);

    // go through each connection
    for (int i = 0; i < connectionsList.getLength(); i++) {
        Node connection = connectionsList.item(i);
        NodeList connectionData = connection.getChildNodes();

        // get the data for each connection
        String label = null;
        ConnectionLabel.Type type = null;
        String address = null;

        // we have to loop through all child nodes since whitespace
        // counts as a text node
        for (int j = 0; j < connectionData.getLength(); j++) {
            Node data = connectionData.item(j);

            // ignore all \n\t text nodes
            if (data.getNodeType() == Node.TEXT_NODE) {
                continue;
            }

            if (data.getNodeName().equals(LABEL_ELEMENT)) {
                label = data.getTextContent();
            } else if (data.getNodeName().equals(TYPE_ELEMENT)) {
                String typeValue = data.getTextContent();
                type = ConnectionLabel.Type.dereference(typeValue);
            } else if (data.getNodeName().equals(ADDRESS_ELEMENT)) {
                address = data.getTextContent();
            }
        }

        connections.put(label, new ConnectionLabel(label, type, address));
    }
}

From source file:edu.ur.ir.ir_import.service.DefaultCollectionImportService.java

/**
 * Add the pictures to the collection.//from  w  ww .  j a v a  2  s . c om
 * 
 * @param picturesNode
 * @param c
 * @param repository
 * @param zip
 */
private void addPictures(Node picturesNode, InstitutionalCollection c, Repository repository, ZipFile zip) {
    NodeList children = picturesNode.getChildNodes();
    for (int index = 0; index < children.getLength(); index++) {
        Node picture = children.item(index);
        if (picture != null) {
            addPicture(picture.getTextContent(), c, repository, zip);
        }
    }
}

From source file:com.twinsoft.convertigo.eclipse.wizards.setup.SetupWizard.java

public void register(final String username, final String password, final String firstname,
        final String lastname, final String email, final String country, final String company,
        final String companyHeadcount, final RegisterCallback callback) {
    Thread th = new Thread(new Runnable() {

        public void run() {
            synchronized (SetupWizard.this) {
                boolean success = false;
                String message;/* w ww.  j a v  a  2  s  . co m*/

                try {
                    String[] url = { registrationServiceUrl };
                    HttpClient client = prepareHttpClient(url);
                    PostMethod method = new PostMethod(url[0]);
                    HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
                    // set parameters for POST method
                    method.setParameter("__sequence", "checkEmail");
                    method.setParameter("username", username);
                    method.setParameter("password", password);
                    method.setParameter("firstname", firstname);
                    method.setParameter("lastname", lastname);
                    method.setParameter("email", email);
                    method.setParameter("country", country);
                    method.setParameter("company", company);
                    method.setParameter("companyHeadcount", companyHeadcount);

                    // execute HTTP post with parameters
                    int statusCode = client.executeMethod(method);
                    if (statusCode == HttpStatus.SC_OK) {
                        Document document = XMLUtils.parseDOM(method.getResponseBodyAsStream());
                        NodeList nd = document.getElementsByTagName("errorCode");

                        if (nd.getLength() > 0) {
                            Node node = nd.item(0);
                            String errorCode = node.getTextContent();

                            if ("0".equals(errorCode)) {
                                success = true;
                                message = "Registration submited, please check your email.";
                            } else {
                                method = new PostMethod(registrationServiceUrl);

                                // set parameters for POST method to get the
                                // details of error messages
                                method.setParameter("__sequence", "getErrorMessages");
                                client.executeMethod(method);
                                document = XMLUtils.parseDOM(method.getResponseBodyAsStream());
                                nd = document.getElementsByTagName("label");
                                Node nodeDetails = nd.item(Integer.parseInt(errorCode));

                                ConvertigoPlugin.logError(nodeDetails.getTextContent());
                                message = "Failed to register: " + nodeDetails.getTextContent();
                            }
                        } else {
                            success = true;
                            message = "debug";
                        }
                    } else {
                        message = "Unexpected HTTP status: " + statusCode;
                    }
                } catch (Exception e) {
                    message = "Generic failure: " + e.getClass().getSimpleName() + ", " + e.getMessage();
                    ConvertigoPlugin.logException(e, "Error while trying to send registration");
                }
                callback.onRegister(success, message);
            }
        }

    });
    th.setDaemon(true);
    th.setName("SetupWizard.register");
    th.start();
}

From source file:com.example.apis.ifashion.YahooWeather.java

private WeatherInfo parseWeatherInfo(Context context, Document doc) {
    WeatherInfo weatherInfo = new WeatherInfo();
    try {/*from   w  w w.ja  v a 2  s .  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.setCurrentTempF(
                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++) {
            this.parseForecastInfo(weatherInfo.getForecastInfoList().get(i), doc, i);
        }

    } 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.twitter.hraven.hadoopJobMonitor.policy.DefaultPolicy.java

/**
 * Check the status of an attempt of a task. This method is invoked only if
 * {@link checkTask} returns false./* www.ja  v  a2 s. c  o m*/
 * 
 * @param taskType
 * @param taskReport
 * @param appConf
 * @param taskAttemptId
 * @param taskAttemptXml The task attempt detail in xml format
 * @return true if task attempt is well-behaved
 */
@Override
public String checkTaskAttempt(ApplicationReport appReport, TaskType taskType, TaskReport taskReport,
        AppConfiguraiton appConf, TaskAttemptID taskAttemptId, Document taskAttemptXml, long currTime) {
    long maxRunTimeMs = appConf.getMaxTaskLenMin(taskType) * MINtoMS;
    // Iterating through the nodes and extracting the data.
    NodeList nodeList = taskAttemptXml.getDocumentElement().getChildNodes();
    int checkedNodes = 0, maxRequiredNodes = 2;//elapsedtime and progress
    for (int i = 0; i < nodeList.getLength(); i++) {
        Node node = nodeList.item(i);
        if (node instanceof Element) {
            String name = node.getNodeName();
            //check duration
            if (name.equals("elapsedTime")) {
                checkedNodes++;
                String timeStr = node.getTextContent();
                long timeMs = Long.parseLong(timeStr);
                LOG.debug(name + " = " + timeMs + " ? " + maxRunTimeMs);
                boolean badTask = (timeMs > maxRunTimeMs);
                if (badTask) {
                    String msg = Notifier.tooLongTaskAttempt(appConf, appReport, taskReport, taskType,
                            taskAttemptId, timeMs, maxRunTimeMs);
                    if (taskType == TaskType.MAP
                            && appConf.isEnforced(HadoopJobMonitorConfiguration.MAP_MAX_RUNTIME_MIN))
                        return msg;
                    if (taskType == TaskType.REDUCE
                            && appConf.isEnforced(HadoopJobMonitorConfiguration.REDUCE_MAX_RUNTIME_MIN))
                        return msg;
                }
                if (checkedNodes >= maxRequiredNodes)
                    break;
                continue;
            }
            //check progress
            if (name.equals("progress")) {
                checkedNodes++;
                String progressStr = node.getTextContent();
                float progress = Float.parseFloat(progressStr);
                boolean badTask = !checkProgress(progress, appConf.getProgressThreshold(), maxRunTimeMs,
                        taskAttemptId, currTime);
                if (badTask) {
                    String msg = Notifier.tooLittleProgress(appConf, appReport, taskReport, taskType,
                            taskAttemptId, progress, appConf.getProgressThreshold(), maxRunTimeMs);
                    if (taskType == TaskType.MAP
                            && appConf.isEnforced(HadoopJobMonitorConfiguration.MAP_MAX_RUNTIME_MIN))
                        return msg;
                    if (taskType == TaskType.REDUCE
                            && appConf.isEnforced(HadoopJobMonitorConfiguration.REDUCE_MAX_RUNTIME_MIN))
                        return msg;
                }
                if (checkedNodes >= maxRequiredNodes)
                    break;
                continue;
            }
        }
    }
    return null;
}

From source file:eu.transkribus.languageresources.extractor.pagexml.PAGEXMLExtractor.java

private <A extends PAGEXMLAnnotation> List<A> extractValuesFromLine(List<A> list, Node unicodeNode,
        PAGEXMLValueBuilder builder, int pageIndex, int lineIndex) {
    String textContent = unicodeNode.getTextContent();
    String customTagValue = getCustomTagValue(unicodeNode);
    return extractValueFromLine(list, textContent, customTagValue, builder, pageIndex, lineIndex);
}

From source file:com.oracle.tutorial.jdbc.RSSFeedsTable.java

public void addRSSFeed(String fileName) throws ParserConfigurationException, SAXException, IOException,
        XPathExpressionException, TransformerConfigurationException, TransformerException, SQLException {
    // Parse the document and retrieve the name of the RSS feed

    String titleString = null;//from  w  ww . j  a  va  2 s  .co  m

    javax.xml.parsers.DocumentBuilderFactory factory = javax.xml.parsers.DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);
    DocumentBuilder builder = factory.newDocumentBuilder();
    Document doc = builder.parse(fileName);

    XPathFactory xPathfactory = XPathFactory.newInstance();

    XPath xPath = xPathfactory.newXPath();

    Node titleElement = (Node) xPath.evaluate("/rss/channel/title[1]", doc, XPathConstants.NODE);

    if (titleElement == null) {
        System.out.println("Unable to retrieve title element");
        return;
    } else {
        titleString = titleElement.getTextContent().trim().toLowerCase().replaceAll("\\s+", "_");
        System.out.println("title element: [" + titleString + "]");
    }

    System.out.println(JDBCTutorialUtilities.convertDocumentToString(doc));

    PreparedStatement insertRow = null;
    SQLXML rssData = null;

    System.out.println("Current DBMS: " + this.dbms);

    try {
        if (this.dbms.equals("mysql")) {
            // For databases that support the SQLXML data type, this creates a
            // SQLXML object from org.w3c.dom.Document.

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values" + " (?, ?)";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);

            System.out.println("Creating SQLXML object with MySQL");
            rssData = con.createSQLXML();
            System.out.println("Creating DOMResult object");
            DOMResult dom = (DOMResult) rssData.setResult(DOMResult.class);
            dom.setNode(doc);

            insertRow.setSQLXML(2, rssData);
            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

        else if (this.dbms.equals("derby")) {

            System.out.println("Adding XML file " + fileName);
            String insertRowQuery = "insert into RSS_FEEDS (RSS_NAME, RSS_FEED_XML) values"
                    + " (?, xmlparse(document cast (? as clob) preserve whitespace))";
            insertRow = con.prepareStatement(insertRowQuery);
            insertRow.setString(1, titleString);
            String convertedDoc = JDBCTutorialUtilities.convertDocumentToString(doc);
            insertRow.setClob(2, new StringReader(convertedDoc));

            System.out.println("Running executeUpdate()");
            insertRow.executeUpdate();

        }

    } catch (SQLException e) {
        JDBCTutorialUtilities.printSQLException(e);
    } catch (Exception ex) {
        System.out.println("Another exception caught:");
        ex.printStackTrace();
    }

    finally {
        if (insertRow != null) {
            insertRow.close();
        }
    }
}

From source file:com.jaeksoft.searchlib.crawler.rest.RestCrawlItem.java

public RestCrawlItem(RestCrawlMaster crawlMaster, XPathParser xpp, Node item) throws XPathExpressionException {
    this(crawlMaster);
    setName(XPathParser.getAttributeString(item, REST_CRAWL_ATTR_NAME));
    setUrl(XPathParser.getAttributeString(item, REST_CRAWL_ATTR_URL));
    setMethod(HttpDownloader.Method.find(DomUtils.getAttributeText(item, REST_CRAWL_ATTR_METHOD),
            HttpDownloader.Method.GET));
    setLang(LanguageEnum.findByCode(XPathParser.getAttributeString(item, REST_CRAWL_ATTR_LANG)));
    setBufferSize(XPathParser.getAttributeValue(item, REST_CRAWL_ATTR_BUFFER_SIZE));
    Node mapNode = xpp.getNode(item, REST_CRAWL_NODE_NAME_MAP);
    if (mapNode != null)
        getFieldMap().load(mapNode);//  w w w. j ava2  s.  c om
    Node pathNode = xpp.getNode(item, REST_CRAWL_NODE_DOC_PATH);
    if (pathNode != null)
        setPathDocument(StringEscapeUtils.unescapeXml(pathNode.getTextContent()));
    Node credNode = xpp.getNode(item, REST_CRAWL_NODE_CREDENTIAL);
    if (credNode != null)
        credential = CredentialItem.fromXml(credNode);
    Node callBackNode = DomUtils.getFirstNode(item, REST_CRAWL_NODE_CALLBACK);
    if (callBackNode != null) {
        setCallbackMethod(HttpDownloader.Method.find(
                DomUtils.getAttributeText(callBackNode, REST_CRAWL_CALLBACK_ATTR_METHOD),
                HttpDownloader.Method.GET));
        setCallbackUrl(DomUtils.getAttributeText(callBackNode, REST_CRAWL_CALLBACK_ATTR_URL));
        setCallbackMode(
                CallbackMode.find(DomUtils.getAttributeText(callBackNode, REST_CRAWL_CALLBACK_ATTR_MODE)));
        setCallbackQueryParameter(
                DomUtils.getAttributeText(callBackNode, REST_CRAWL_CALLBACK_ATTR_QUERY_PARAM));
        setCallbackPayload(callBackNode.getTextContent());
    }

}

From source file:eu.planets_project.tb.impl.properties.ManuallyMeasuredPropertyHandlerImpl.java

private List<ManuallyMeasuredProperty> parseManualPropertiesXML(Element root, boolean bUserCreated) {
    List<ManuallyMeasuredProperty> ret = new ArrayList<ManuallyMeasuredProperty>();
    NodeList nProperties = root.getChildNodes();
    for (int i = 0; i < nProperties.getLength(); i++) {
        Node nProperty = nProperties.item(i);
        if (nProperty.getNodeName().equals("property")) {

            //now iterate over its children to extract name and description
            NodeList nPropChilds = nProperty.getChildNodes();
            String name = null, description = null, tburi = null;
            for (int j = 0; j < nPropChilds.getLength(); j++) {
                Node nPropChild = nPropChilds.item(j);
                if (nPropChild.getNodeName().equals("name")) {
                    name = nPropChild.getTextContent();
                }/*  www. j a v  a  2s . c  o  m*/
                if (nPropChild.getNodeName().equals("description")) {
                    description = nPropChild.getTextContent();

                }
            }
            NamedNodeMap attributes = nProperty.getAttributes();
            if (attributes.getNamedItem("tburi") != null) {
                tburi = attributes.getNamedItem("tburi").getNodeValue();
            }

            //check if name and description were properly extracted
            if ((name != null) && (description != null) && (tburi != null)) {
                //now create the ManuallyMeasuredProperty
                ret.add(new ManuallyMeasuredPropertyImpl(name, description, tburi, bUserCreated));
                log.debug("added propery: " + name + " " + tburi);
            } else {
                log.debug("error creating ManuallyMeasuredProperty for property item nr: " + i);
            }
        }
    }
    return ret;
}