Example usage for org.xml.sax XMLReader parse

List of usage examples for org.xml.sax XMLReader parse

Introduction

In this page you can find the example usage for org.xml.sax XMLReader parse.

Prototype

public void parse(String systemId) throws IOException, SAXException;

Source Link

Document

Parse an XML document from a system identifier (URI).

Usage

From source file:nbxml.Base.java

public void parseXml(String resource, ContentHandler contentHandler) throws SAXException, IOException {
    InputStream inputStream = getResourceAsStream(resource);
    InputSource inputSource = new InputSource(inputStream);
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();

    xmlReader.setContentHandler(contentHandler);
    xmlReader.parse(inputSource);
}

From source file:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {//from w ww . j  a va2  s. c o  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.adamrosenfield.wordswithcrosses.net.derstandard.DerStandardParser.java

private void parse(InputSource input, ContentHandler handler) throws SAXException, IOException {
    XMLReader xmlReader = XMLReaderFactory.createXMLReader("org.ccil.cowan.tagsoup.Parser");

    xmlReader.setContentHandler(handler);
    xmlReader.parse(input);
}

From source file:org.npr.api.Client.java

public void sax(ContentHandler handler) {
    try {/*from w  ww . j  a va  2  s  .c  o  m*/
        XMLReader xr = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        xr.setContentHandler(handler);
        xr.parse(new InputSource(download()));
    } catch (SAXException e) {
        Log.e(LOG_TAG, "error creating parser", e);
    } catch (ParserConfigurationException e) {
        Log.e(LOG_TAG, "error creating parser", e);
    } catch (FactoryConfigurationError e) {
        Log.e(LOG_TAG, "error creating parser", e);
    } catch (IOException e) {
        Log.e(LOG_TAG, "error parsing", e);
    }
}

From source file:SAXLister.java

public SAXLister(String[] args) throws SAXException, IOException {
    XMLReader parser = XMLReaderFactory.createXMLReader();
    // should load properties rather than hardcoding class name
    parser.setContentHandler(new PeopleHandler());
    parser.parse(args.length == 1 ? args[0] : "people.xml");
}

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  ww w . j a v a 2s  .  c  o 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: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;//from w ww .j a v  a 2  s . com
    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.inferiorhumanorgans.WayToGo.Agency.BART.Prediction.XMLTask.java

@Override
protected Void doInBackground(BARTAgency... someAgencies) {
    super.doInBackground(someAgencies);
    theListener.startPredictionFetch();/*from  w  w w .  ja va2  s.co m*/
    Log.d(LOG_NAME, "Trying to get Predictions.");

    InputStream content = null;
    ClientConnectionManager connman = new ThreadSafeClientConnManager(params, registry);
    DefaultHttpClient hc = new DefaultHttpClient(connman, params);

    String theURL = BART_URL + BARTAgency.API_KEY + "&orig=" + theStationTag;

    Log.i(LOG_NAME, "Fetching from: " + theURL);
    HttpGet getRequest = new HttpGet(theURL);
    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.d(LOG_NAME, "Put the BART predictions 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.d(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.d(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//from ww  w  .j a  va 2  s  .c o  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.bradmcevoy.http.webdav.DefaultPropPatchParser.java

private ParseResult parseContent(byte[] arr) throws IOException, SAXException {
    if (arr.length > 0) {
        log.debug("processing content");
        ByteArrayInputStream bin = new ByteArrayInputStream(arr);
        XMLReader reader = XMLReaderFactory.createXMLReader();
        PropPatchSaxHandler handler = new PropPatchSaxHandler();
        reader.setContentHandler(handler);
        reader.parse(new InputSource(bin));
        log.debug("toset: " + handler.getAttributesToSet().size());
        return new ParseResult(handler.getAttributesToSet(), handler.getAttributesToRemove().keySet());
    } else {/* w  w w .  j a  va  2s.co  m*/
        log.debug("empty content");
        return new ParseResult(new HashMap<QName, String>(), new HashSet<QName>());
    }

}