List of usage examples for javax.xml.parsers SAXParser getXMLReader
public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;
From source file:Examples.java
/** * This example shows how to chain events from one Transformer * to another transformer, using the Transformer as a * SAX2 XMLFilter/XMLReader./*from w w w . j av a 2s. c o m*/ */ public static void exampleXMLFilterChain(String sourceID, String xslID_1, String xslID_2, String xslID_3) throws TransformerException, TransformerConfigurationException, SAXException, IOException { TransformerFactory tfactory = TransformerFactory.newInstance(); Templates stylesheet1 = tfactory.newTemplates(new StreamSource(xslID_1)); Transformer transformer1 = stylesheet1.newTransformer(); // If one success, assume all will succeed. if (tfactory.getFeature(SAXSource.FEATURE)) { SAXTransformerFactory stf = (SAXTransformerFactory) tfactory; XMLReader reader = null; // Use JAXP1.1 ( if possible ) try { javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser(); reader = jaxpParser.getXMLReader(); } catch (javax.xml.parsers.ParserConfigurationException ex) { throw new org.xml.sax.SAXException(ex); } catch (javax.xml.parsers.FactoryConfigurationError ex1) { throw new org.xml.sax.SAXException(ex1.toString()); } catch (NoSuchMethodError ex2) { } if (reader == null) reader = XMLReaderFactory.createXMLReader(); XMLFilter filter1 = stf.newXMLFilter(new StreamSource(xslID_1)); XMLFilter filter2 = stf.newXMLFilter(new StreamSource(xslID_2)); XMLFilter filter3 = stf.newXMLFilter(new StreamSource(xslID_3)); if (null != filter1) // If one success, assume all were success. { // transformer1 will use a SAX parser as it's reader. filter1.setParent(reader); // transformer2 will use transformer1 as it's reader. filter2.setParent(filter1); // transform3 will use transform2 as it's reader. filter3.setParent(filter2); filter3.setContentHandler(new ExampleContentHandler()); // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler()); // Now, when you call transformer3 to parse, it will set // itself as the ContentHandler for transform2, and // call transform2.parse, which will set itself as the // content handler for transform1, and call transform1.parse, // which will set itself as the content listener for the // SAX parser, and call parser.parse(new InputSource("xml/foo.xml")). filter3.parse(new InputSource(sourceID)); } else { System.out.println("Can't do exampleXMLFilter because " + "tfactory doesn't support asXMLFilter()"); } } else { System.out.println("Can't do exampleXMLFilter because " + "tfactory is not a SAXTransformerFactory"); } }
From source file:org.metawatch.manager.Monitors.java
private static synchronized void updateWeatherDataGoogle(Context context) { try {/*from ww w.j a va 2 s.co m*/ if (WeatherData.updating) return; // Prevent weather updating more frequently than every 5 mins if (WeatherData.timeStamp != 0 && WeatherData.received) { long currentTime = System.currentTimeMillis(); long diff = currentTime - WeatherData.timeStamp; if (diff < 5 * 60 * 1000) { if (Preferences.logging) Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago"); //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context); return; } } WeatherData.updating = true; if (Preferences.logging) Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start"); String queryString; List<Address> addresses; if (Preferences.weatherGeolocation && LocationData.received) { Geocoder geocoder; String locality = ""; String PostalCode = ""; try { geocoder = new Geocoder(context, Locale.getDefault()); addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1); for (Address address : addresses) { if (!address.getPostalCode().equalsIgnoreCase("")) { PostalCode = address.getPostalCode(); locality = address.getLocality(); if (locality.equals("")) { locality = PostalCode; } else { PostalCode = locality + ", " + PostalCode; } } } } catch (IOException e) { if (Preferences.logging) Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e); } if (PostalCode.equals("")) { PostalCode = Preferences.weatherCity; } if (locality.equals("")) { WeatherData.locationName = PostalCode; } else { WeatherData.locationName = locality; } queryString = "http://www.google.com/ig/api?weather=" + PostalCode; } else { queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity; WeatherData.locationName = Preferences.weatherCity; } URL url = new URL(queryString.replace(" ", "%20")); SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); GoogleWeatherHandler gwh = new GoogleWeatherHandler(); xr.setContentHandler(gwh); xr.parse(new InputSource(url.openStream())); WeatherSet ws = gwh.getWeatherSet(); WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition(); ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions(); int days = conditions.size(); WeatherData.forecast = new Forecast[days]; for (int i = 0; i < days; ++i) { WeatherForecastCondition wfc = conditions.get(i); WeatherData.forecast[i] = m.new Forecast(); WeatherData.forecast[i].day = null; WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition()); WeatherData.forecast[i].day = wfc.getDayofWeek(); if (Preferences.weatherCelsius) { WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString(); WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString(); } else { WeatherData.forecast[i].tempHigh = Integer .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius())); WeatherData.forecast[i].tempLow = Integer .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius())); } } WeatherData.celsius = Preferences.weatherCelsius; String cond = wcc.getCondition(); WeatherData.condition = cond; if (Preferences.weatherCelsius) { WeatherData.temp = Integer.toString(wcc.getTempCelcius()); } else { WeatherData.temp = Integer.toString(wcc.getTempFahrenheit()); } cond = cond.toLowerCase(); WeatherData.icon = getIconGoogleWeather(cond); WeatherData.received = true; WeatherData.timeStamp = System.currentTimeMillis(); Idle.updateIdle(context, true); MetaWatchService.notifyClients(); } catch (Exception e) { if (Preferences.logging) Log.e(MetaWatch.TAG, "Exception while retreiving weather", e); } finally { if (Preferences.logging) Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish"); } }
From source file:com.vionto.vithesaurus.wikipedia.WiktionarySynonymDumper.java
private void run(InputStream is) throws IOException, SAXException, ParserConfigurationException { WiktionaryPageHandler handler = new WiktionaryPageHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);// w ww . j av a2 s . c om System.out.println("SET NAMES utf8;"); System.out.println("DROP TABLE IF EXISTS wiktionary;"); System.out.println("CREATE TABLE `wiktionary` ( " + "`headword` varchar(255) NOT NULL default '', " + "`meanings` text, " + "`synonyms` text, " + "KEY `headword` (`headword`)" + ") ENGINE = MYISAM;"); saxParser.parse(is, handler); System.err.println("Exported: " + handler.exported); System.err.println("Skipped: " + handler.skipped); }
From source file:com.inferiorhumanorgans.WayToGo.Agency.BART.Route.RouteTask.java
@Override protected Void doInBackground(BARTAgency... someAgencies) { super.doInBackground(someAgencies); Log.i(LOG_NAME, "Trying to get BART route list."); InputStream content = null;/*from w ww .j a v a 2s .co m*/ ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient hc = new DefaultHttpClient(connman, params); Log.i(LOG_NAME, "Fetching from: " + BART_URL + BARTAgency.API_KEY); HttpGet getRequest = new HttpGet(BART_URL + BARTAgency.API_KEY); try { content = hc.execute(getRequest).getEntity().getContent(); } catch (ClientProtocolException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } Log.i(LOG_NAME, "Put the station list in the background."); try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(dataHandler); xr.parse(new InputSource(content)); } catch (ParserConfigurationException pce) { Log.e(LOG_NAME + " SAX XML", "sax parse error", pce); } catch (AbortXMLParsingException abrt) { Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!"); } catch (SAXException se) { Log.e(LOG_NAME + " SAX XML", "sax error", se); } catch (IOException ioe) { Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe); } Log.i(LOG_NAME + " SAX XML", "Done parsing BART station XML"); return null; }
From source file:eionet.gdem.conversion.excel.ExcelProcessor.java
/** * Converts XML string to OutputStream/* w w w. java2s. co m*/ * @param sIn Input string * @param sOut OutputStream * @throws GDEMException In case an error occurs. */ public void makeExcel(String sIn, OutputStream sOut) throws GDEMException { if (sIn == null) { return; } if (sOut == null) { return; } try { ExcelConversionHandlerIF excel = ExcelUtils.getExcelConversionHandler(); //excel.setFileName(sOut); ExcelXMLHandler handler = new ExcelXMLHandler(excel); SAXParserFactory spfact = SAXParserFactory.newInstance(); SAXParser parser = spfact.newSAXParser(); XMLReader reader = parser.getXMLReader(); spfact.setValidating(true); reader.setContentHandler(handler); reader.parse(sIn); excel.writeToFile(sOut); } catch (Exception e) { throw new GDEMException("Error generating Excel file: " + e.toString(), e); } return; }
From source file:com.inferiorhumanorgans.WayToGo.Agency.NextBus.RouteList.RouteListXMLTask.java
@Override protected Void doInBackground(final NextBusAgency... someAgencies) { Assert.assertEquals(1, someAgencies.length); super.doInBackground(someAgencies); String theNBName = theAgency.getNextBusName(); Log.i(LOG_NAME, "Trying to get the route list for " + theNBName + "."); InputStream content = null;/* w w w . ja v a 2 s . c om*/ ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry); DefaultHttpClient hc = new DefaultHttpClient(connman, params); String theNBURL = "http://webservices.nextbus.com/service/publicXMLFeed?command=routeList&a="; theNBURL += Uri.encode(theNBName); Log.i(LOG_NAME, "Fetching from: " + theNBURL); HttpGet getRequest = new HttpGet(theNBURL); try { content = hc.execute(getRequest).getEntity().getContent(); } catch (ClientProtocolException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(LOG_NAME).log(Level.SEVERE, null, ex); this.cancel(true); return null; } try { SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); xr.setContentHandler(theDataHandler); xr.parse(new InputSource(content)); } catch (ParserConfigurationException pce) { Log.e(LOG_NAME + " SAX XML", "sax parse error", pce); } catch (AbortXMLParsingException abrt) { Log.i(LOG_NAME + " AsyncXML", "Cancelled!!!!!"); } catch (SAXException se) { Log.e(LOG_NAME + " SAX XML", "sax error", se); } catch (IOException ioe) { Log.e(LOG_NAME + " SAX XML", "sax parse io error", ioe); } //Log.i(LOG_NAME + " SAX XML", "Done parsing XML for " + theNBName); return null; }
From source file:com.rany.albeg.wein.rssr.RssReader.java
private void init(RssReaderListener readCompleteListener) { mReadyToRead = true;//ww w. jav a2s . c o m mRssReaderListener = readCompleteListener; mRssReaderXmlHandler = new RssReaderXMLHandler(); try { SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser parser = factory.newSAXParser(); mXMLReader = parser.getXMLReader(); mXMLReader.setContentHandler(mRssReaderXmlHandler); } catch (ParserConfigurationException e) { Log.e(TAG, "ParserConfigurationException"); } catch (SAXException e) { Log.e(TAG, "SAXException init()"); } }
From source file:com.vionto.vithesaurus.wikipedia.CommonsAudioDumper.java
private void run(InputStream is) throws IOException, SAXException, ParserConfigurationException { CommonsPageHandler handler = new CommonsPageHandler(); SAXParserFactory factory = SAXParserFactory.newInstance(); SAXParser saxParser = factory.newSAXParser(); saxParser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);//w ww . j a v a2s. c om System.out.println("SET NAMES utf8;"); saxParser.parse(is, handler); System.err.println("Exported: " + handler.exported); System.err.println("Skipped: " + handler.skipped); System.err.println("Skipped " + handler.noLicense + " because of missing/undetected license"); }
From source file:fr.eyal.lib.data.parser.GenericParser.java
public void parseSheet(final Object content, final int parseType) throws ParseException { //Sax method used for XML if (parseType == PARSE_TYPE_SAX) { //we convert the content to String String xml = new String((byte[]) content); final SAXParserFactory factory = SAXParserFactory.newInstance(); try {// w ww. ja va 2 s. c om final SAXParser sp = factory.newSAXParser(); final XMLReader xr = sp.getXMLReader(); final InputSource is = new InputSource(); is.setCharacterStream(new StringReader(xml)); //we set the SAX DefaultHandler xr.setContentHandler((DefaultHandler) mHandler); Out.v(TAG, "start parsing SAX"); xr.parse(is); Out.v(TAG, "end parsing SAX"); } catch (final Exception e) { e.printStackTrace(); throw new ParseException("Parsing error"); } } else if (parseType == PARSE_TYPE_JSON) { mHandler.parse(content); } else if (parseType == PARSE_TYPE_IMAGE) { mHandler.parse(content); } }
From source file:com.entertailion.android.slideshow.rss.RssHandler.java
public RssFeed getFeed(String data) throws Exception { feed = null;/* ww w .jav a2s.c om*/ SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser sp = spf.newSAXParser(); XMLReader xr = sp.getXMLReader(); InputSource inStream = new org.xml.sax.InputSource(); inStream.setCharacterStream(new StringReader(data)); xr.setContentHandler(this); feed = new RssFeed(); xr.parse(inStream); xr = null; sp = null; spf = null; return feed; }