Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * @param service//from w  w w . j  a va 2s. co  m
 *          Service-ID
 * @return Data of specific service
 */
private TreeMap<String, String> getServiceDataBouquets(String service) {
    if (!mConfig.hasValidAddress()) {
        return null;
    }
    try {
        InputStream stream = openStreamForLocalUrl("/web/getservices?bRef=" + service);
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxHandler handler = new DreamboxHandler();
        saxParser.parse(stream, handler);
        return handler.getData();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * @param service/*from w w  w. ja  v  a  2 s . c  o  m*/
 *          Service-ID
 * @return Data of specific service
 */
private TreeMap<String, String> getServiceData(String service) {
    if (!mConfig.hasValidAddress()) {
        return null;
    }
    try {
        InputStream stream = openStreamForLocalUrl("/web/getservices?sRef=" + service);
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxHandler handler = new DreamboxHandler();
        saxParser.parse(stream, handler);
        return handler.getData();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:edu.psu.citeseerx.updates.external.metadata.DBLPMetadataUpdater.java

public void updateDBLP() {
    try {//from   w  ww .  j a  v  a 2  s. c  o m
        // Get the SAX factory.
        SAXParserFactory factory = SAXParserFactory.newInstance();

        // Neither we want validation nor namespaces.
        factory.setNamespaceAware(false);
        factory.setValidating(true);

        SAXParser parser = factory.newSAXParser();
        parser.getXMLReader().setEntityResolver(new DBLPEntityResolver(DBLPDTDFile));

        /*xmlReader.setFeature(
            "http://apache.org/xml/features/nonvalidating/load-external-dtd", 
            false);*/

        parser.parse(DBLPDataFile, dblpHandler);
    } catch (ParserConfigurationException e) {
        logger.error("The underlaying parser doesn't support the " + "requested feature", e);
    } catch (SAXException e) {
        logger.error("Error", e);
    } catch (IOException e) {
        logger.error("A parsing error has occurred: " + DBLPDataFile, e);
    }

}

From source file:com.wlcg.aroundme.cc.weather.YahooWeatherProvider.java

@Override
public WeatherInfo getWeatherInfo(String id, String localizedCityName, boolean metricUnits) {
    mCityId = id;/* w  ww  .j ava2 s  .c o m*/
    mLocalizedCityName = localizedCityName;
    mMetricUnits = metricUnits;

    String url = String.format(URL_WEATHER, id, metricUnits ? "c" : "f");
    Log.d(TAG, "URL is => " + url);
    String response = HttpRetriever.retrieve(url);

    if (response == null) {
        //mWeatherInfo = null;
        return null;
    }

    WeatherInfo info = null;

    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        SAXParser parser = factory.newSAXParser();
        StringReader reader = new StringReader(response);
        WeatherHandler handler = new WeatherHandler();
        parser.parse(new InputSource(reader), handler);

        if (handler.isComplete()) {
            // There are cases where the current condition is unknown, but the forecast
            // is not - using the (inaccurate) forecast is probably better than showing
            // the question mark
            if (handler.conditionCode.equals(3200)) {
                handler.condition = handler.forecasts.get(0).getCondition();
                handler.conditionCode = handler.forecasts.get(0).getConditionCode();
            }
            ArrayList<DayForecast> forecasts = new ArrayList<WeatherInfo.DayForecast>();

            String time = new SimpleDateFormat("yyyy/MM/dd HH:mm").format(new java.util.Date());
            for (DayForecast forecast : handler.forecasts) {
                if (forecast.getDate().equals(handler.date)) {
                    forecast.setCondition(handler.condition);
                    forecast.setConditionCode(handler.conditionCode);
                    forecast.setHumidity(handler.humidity);
                    forecast.setSunRaise(handler.sunrise);
                    forecast.setSunSet(handler.sunset);
                    forecast.setTemperature(handler.temperature);
                    forecast.setTempUnit(handler.temperatureUnit);
                    forecast.setWindSpeed(handler.windSpeed);
                    forecast.setWindDirection(handler.windDirection);
                    forecast.setWindSpeedUnit(handler.speedUnit);
                }
                if (localizedCityName != null) {
                    forecast.setCity(localizedCityName);
                }
                forecast.setSynctimestamp(time);
                forecasts.add(forecast);

                //Log.d(TAG, "Weather forecast is => " + forecast);
            }
            //mWeatherInfo = new WeatherInfo(forecasts);
            info = new WeatherInfo(forecasts);
            Log.d(TAG, "Weather updated: " + info);
        } else {
            Log.w(TAG, "Received incomplete weather XML (id=" + id + ")");
            //mWeatherInfo = null;
            info = null;
        }
    } catch (ParserConfigurationException e) {
        Log.e(TAG, "Could not create XML parser", e);
        //mWeatherInfo = null;
        info = null;
    } catch (SAXException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
        //mWeatherInfo = null;
        info = null;
    } catch (IOException e) {
        Log.e(TAG, "Could not parse weather XML (id=" + id + ")", e);
        //mWeatherInfo = null;
        info = null;
    }
    if (mWeatherDataChangedListener != null)
        mWeatherDataChangedListener.onDataChanged();
    return info;
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * @return List of Timers//ww w .j a va  2  s  . com
 */
private ArrayList<HashMap<String, String>> getTimers() {
    if (!mConfig.hasValidAddress()) {
        return null;
    }
    try {
        InputStream stream = openStreamForLocalUrl("/web/timerlist");
        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxTimerHandler handler = new DreamboxTimerHandler();
        saxParser.parse(stream, handler);

        return handler.getTimers();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.aionengine.gameserver.dataholders.loadingutils.XmlMerger.java

/**
 * Check for modifications of included files.
 *
 * @return <code>true</code> if at least one of included files has modifications.
 * @throws IOException                  IO Error.
 * @throws SAXException                 Document parsing error.
 * @throws ParserConfigurationException if a SAX parser cannot
 *                                      be created which satisfies the requested configuration.
 *//* w  w w  .  j  a  v a 2  s  .co  m*/
private boolean checkFileModifications() throws Exception {
    long destFileTime = destFile.lastModified();

    if (sourceFile.lastModified() > destFileTime) {
        logger.debug("Source file was modified ");
        return true;
    }

    Properties metadata = restoreFileModifications(metaDataFile);

    if (metadata == null) // new file or smth else.
        return true;

    SAXParserFactory parserFactory = SAXParserFactory.newInstance();

    SAXParser parser = parserFactory.newSAXParser();

    TimeCheckerHandler handler = new TimeCheckerHandler(baseDir, metadata);

    parser.parse(sourceFile, handler);

    return handler.isModified();
}

From source file:fr.paris.lutece.plugins.dila.modules.solr.utils.parsers.DilaSolrLocalParser.java

/**
 * Launches the parsing on each local card
 *
 * @param localCardsList the local cards
 * @param parser the SAX parser/*from  w w w.  ja v a  2s  . c o m*/
 */
private void parseAllLocalCards(List<LocalDTO> localCardsList, SAXParser parser) {
    if (CollectionUtils.isNotEmpty(localCardsList)) {
        for (LocalDTO currentCard : localCardsList) {
            InputStream xmlInput = new ByteArrayInputStream(currentCard.getXml().getBytes());

            // Launches the parsing of this local card (with the current handler)
            try {
                parser.parse(xmlInput, this);
            } catch (SAXException e) {
                AppLogService.error(e.getMessage(), e);
            } catch (IOException e) {
                AppLogService.error(e.getMessage(), e);
            }
        }
    }
}

From source file:com.centurylink.mdw.util.HttpHelper.java

/**
 * Use SAX for fastest parsing.//from  ww  w.  j  a  v  a  2 s . c  o m
 */
private URL parseResponseForHtmlMetaEquiv(String response)
        throws IOException, SAXException, ParserConfigurationException {
    final StringBuffer urlBuf = new StringBuffer();
    InputStream xmlStream = new ByteArrayInputStream(response.getBytes());
    InputSource src = new InputSource(xmlStream);
    SAXParserFactory parserFactory = SAXParserFactory.newInstance();
    SAXParser parser = parserFactory.newSAXParser();
    parser.parse(src, new DefaultHandler() {
        boolean inHtml;
        boolean inHead;
        boolean inMeta;

        public void startElement(String uri, String localName, String qName, Attributes attrs)
                throws SAXException {
            if (qName.equals("html"))
                inHtml = true;
            else if (qName.equals("head"))
                inHead = true;
            else if (qName.equals("meta"))
                inMeta = true;

            if (inHtml && inHead && inMeta) {
                if ("refresh".equals(attrs.getValue("http-equiv"))) {
                    String cAttr = attrs.getValue("content");
                    if (cAttr != null) {
                        int urlIdx = cAttr.indexOf("url=");
                        if (urlIdx >= 0)
                            urlBuf.append(cAttr.substring(urlIdx + 4));
                    }
                }
            }
        }

        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (qName.equals("html"))
                inHtml = false;
            else if (qName.equals("head"))
                inHead = false;
            else if (qName.equals("meta"))
                inMeta = false;
        }
    });

    String str = urlBuf.toString().trim();
    if (str.isEmpty())
        return null;
    else
        return new URL(str);
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * Remove a recording from the Dreambox//from ww  w . ja va  2 s  . co  m
 * 
 * @param dreamboxChannel
 *          the DreamboxChannel for the Program
 * @param prgTime
 *          ProgramTime to remove @return true, if successful
 * @param timezone
 *          Timezone to use for recording
 * @return True, if successful
 */
public boolean removeRecording(DreamboxChannel dreamboxChannel, ProgramTime prgTime, TimeZone timezone) {
    if (!mConfig.hasValidAddress()) {
        return false;
    }
    try {
        Calendar start = prgTime.getStartAsCalendar();
        start.setTimeZone(timezone);

        Calendar end = prgTime.getEndAsCalendar();
        end.setTimeZone(timezone);

        String shortInfo = prgTime.getProgram().getShortInfo();
        if (shortInfo == null) {
            shortInfo = "";
        }

        InputStream stream = openStreamForLocalUrl(
                "/web/tvbrowser?&command=del&action=0" + "&syear=" + start.get(Calendar.YEAR) + "&smonth="
                        + (start.get(Calendar.MONTH) + 1) + "&sday=" + start.get(Calendar.DAY_OF_MONTH)
                        + "&shour=" + start.get(Calendar.HOUR_OF_DAY) + "&smin=" + start.get(Calendar.MINUTE) +

                        "&eyear=" + end.get(Calendar.YEAR) + "&emonth=" + (end.get(Calendar.MONTH) + 1)
                        + "&eday=" + end.get(Calendar.DAY_OF_MONTH) + "&ehour=" + end.get(Calendar.HOUR_OF_DAY)
                        + "&emin=" + end.get(Calendar.MINUTE) +

                        "&sRef="
                        + URLEncoder.encode(dreamboxChannel.getName() + "|" + dreamboxChannel.getReference(),
                                "UTF8")
                        + "&name=" + URLEncoder.encode(prgTime.getProgram().getTitle(), "UTF8")
                        + "&description=" + URLEncoder.encode(shortInfo, "UTF8") +

                        "&afterevent=0&eit=&disabled=0&justplay=0&repeated=0");

        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxStateHandler handler = new DreamboxStateHandler();
        saxParser.parse(stream, handler);
        return Boolean.valueOf(handler.getState());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:captureplugin.drivers.dreambox.connector.DreamboxConnector.java

/**
 * Add a recording to the Dreambox//from w  w w. ja v a 2  s .  co  m
 * 
 * @param dreamboxChannel
 *          the DreamboxChannel for the Program
 * @param prgTime
 *          add this ProgramTime
 * @param afterEvent
 *          0=nothing, 1=standby, 2=deepstandby, 3=auto
 * @param timezone
 *          TimeZone to use for recording
 * @return True, if successful
 */
public boolean addRecording(DreamboxChannel dreamboxChannel, ProgramTime prgTime, int afterEvent,
        TimeZone timezone) {
    if (!mConfig.hasValidAddress()) {
        return false;
    }
    try {
        Calendar start = prgTime.getStartAsCalendar();
        start.setTimeZone(timezone);

        Calendar end = prgTime.getEndAsCalendar();
        end.setTimeZone(timezone);

        String shortInfo = prgTime.getProgram().getShortInfo();
        if (shortInfo == null) {
            shortInfo = "";
        }

        InputStream stream = openStreamForLocalUrl(
                "/web/tvbrowser?&command=add&action=0" + "&syear=" + start.get(Calendar.YEAR) + "&smonth="
                        + (start.get(Calendar.MONTH) + 1) + "&sday=" + start.get(Calendar.DAY_OF_MONTH)
                        + "&shour=" + start.get(Calendar.HOUR_OF_DAY) + "&smin=" + start.get(Calendar.MINUTE) +

                        "&eyear=" + end.get(Calendar.YEAR) + "&emonth=" + (end.get(Calendar.MONTH) + 1)
                        + "&eday=" + end.get(Calendar.DAY_OF_MONTH) + "&ehour=" + end.get(Calendar.HOUR_OF_DAY)
                        + "&emin=" + end.get(Calendar.MINUTE) +

                        "&sRef="
                        + URLEncoder.encode(dreamboxChannel.getName() + "|" + dreamboxChannel.getReference(),
                                "UTF8")
                        + "&name=" + URLEncoder.encode(prgTime.getProgram().getTitle(), "UTF8")
                        + "&description=" + URLEncoder.encode(shortInfo, "UTF8") +

                        "&afterevent=" + afterEvent + "&eit=&disabled=0&justplay=0&repeated=0");

        SAXParser saxParser = SAXParserFactory.newInstance().newSAXParser();
        DreamboxStateHandler handler = new DreamboxStateHandler();
        saxParser.parse(stream, handler);
        return (Boolean.valueOf(handler.getState()));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (MalformedURLException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    return false;
}