Example usage for javax.xml.parsers SAXParser getXMLReader

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

Introduction

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

Prototype


public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;

Source Link

Document

Returns the org.xml.sax.XMLReader that is encapsulated by the implementation of this class.

Usage

From source file:nz.co.wholemeal.christchurchmetro.Stop.java

public ArrayList getArrivals() throws Exception {
    arrivals.clear();/*  w  w w.j  a va  2s.  co m*/

    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        URL source = new URL(arrivalURL + platformTag);
        EtaHandler handler = new EtaHandler();
        xr.setContentHandler(handler);
        xr.parse(new InputSource(source.openStream()));
        lastArrivalFetch = System.currentTimeMillis();
    } catch (Exception e) {
        throw e;
    }

    Collections.sort(arrivals, new ComparatorByEta());
    return arrivals;
}

From source file:com.pontecultural.flashcards.ReadSpreadsheet.java

public void run() {
    try {//w  ww . j  av a2s . c  om
        // This class is used to upload a zip file via 
        // the web (ie,fileData). To test it, the file is 
        // give to it directly via odsFile. One of 
        // which must be defined. 
        assertFalse(odsFile == null && fileData == null);
        XMLReader reader = null;
        final String ZIP_CONTENT = "content.xml";
        // Open office files are zipped. 
        // Walk through it and find "content.xml"

        ZipInputStream zin = null;
        try {
            if (fileData != null) {
                zin = new ZipInputStream(new BufferedInputStream(fileData.getInputStream()));
            } else {
                zin = new ZipInputStream(new BufferedInputStream(new FileInputStream(odsFile)));
            }

            ZipEntry entry;
            while ((entry = zin.getNextEntry()) != null) {
                if (entry.getName().equals(ZIP_CONTENT)) {
                    break;
                }
            }
            SAXParserFactory spf = SAXParserFactory.newInstance();
            //spf.setValidating(validate);

            SAXParser parser = spf.newSAXParser();
            reader = parser.getXMLReader();

            // reader.setErrorHandler(new MyErrorHandler());
            reader.setContentHandler(this);
            // reader.parse(new InputSource(zf.getInputStream(entry)));

            reader.parse(new InputSource(zin));

        } catch (ParserConfigurationException pce) {
            pce.printStackTrace();
        } catch (SAXParseException spe) {
            spe.printStackTrace();
        } catch (SAXException se) {
            se.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zin != null)
                zin.close();
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
}

From source file:cauchy.android.tracker.PicasaWSUtils.java

public Map<String, String> getAlbumsIdsByAlbumTitles() {
    String url_string = "http://picasaweb.google.com/data/feed/api/user/" + userID;
    try {//from   w w w. jav  a2s  .  co  m
        URL url = new URL(url_string);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(this);
        InputStream openStream = url.openStream();
        xr.parse(new InputSource(openStream));
        openStream.close();
        return albumsIdsByAlbumTitles;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.ewhoxford.android.bloodpressure.ghealth.gdata.GDataHealthClient.java

@Override
public List<Result> retrieveResults()
        throws AuthenticationException, InvalidProfileException, ServiceException {

    if (authToken == null) {
        throw new IllegalStateException("authToken must not be null");
    }/*  w w  w .j  av  a2s . c  o m*/

    if (profileId == null) {
        throw new IllegalStateException("profileId must not be null.");
    }

    String url = service.getBaseURL() + "/profile/ui/" + profileId + "/-/labtest";
    InputStream istream = retreiveData(url);

    HealthGDataContentHandler ccrHandler = new HealthGDataContentHandler();
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        XMLReader xr = sp.getXMLReader();
        xr.setContentHandler(ccrHandler);
        xr.parse(new InputSource(istream));
    } catch (ParserConfigurationException e) {
        throw new ServiceException(e);
    } catch (SAXException e) {
        throw new ServiceException(e);
    } catch (IOException e) {
        throw new ServiceException(e);
    } finally {
        if (istream != null) {
            try {
                istream.close();
            } catch (IOException e) {
                throw new ServiceException(e);
            }
        }
    }

    return ccrHandler.getResults();
}

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

public void updateDBLP() {
    try {/*ww w  .ja  va 2 s.co  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.aurel.track.exchange.docx.importer.HTMLParser.java

private void parse(String fileName, Locale locale) {
    //get a factory
    localizedHeading = "berschrift";//LocalizeUtil.getLocalizedTextFromApplicationResources(HEADING_KEY, locale);
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from  w  w w .java 2 s.  com
        //get a new instance of parser
        SAXParser sp = spf.newSAXParser();
        //spf.setValidating(true);
        XMLReader xmlReader = sp.getXMLReader();
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        xmlReader.setContentHandler(this);
        //parse the file and also register this class for call backs
        //InputSource is=new InputSource(new StringReader(xml));
        xmlReader.parse(convertToFileURL(fileName));
    } catch (SAXException se) {
        LOGGER.error("Parsing the file " + fileName + " failed with " + se.getMessage());
        LOGGER.debug(ExceptionUtils.getStackTrace(se));
    } catch (ParserConfigurationException pce) {
        LOGGER.error("Parsing the file " + fileName + " failed with " + pce.getMessage());
        if (LOGGER.isDebugEnabled()) {
            LOGGER.error(ExceptionUtils.getStackTrace(pce));
        }
    } catch (IOException ie) {
        LOGGER.error("Reading the file " + fileName + " failed with " + ie.getMessage());
        LOGGER.error(ExceptionUtils.getStackTrace(ie));
    }

}

From source file:es.prodevelop.gvsig.mini.tasks.weather.WeatherFunctionality.java

@Override
public boolean execute() {
    URL url;//w w w  .j  a v  a2s.  c  o  m
    try {
        String queryString = "http://ws.geonames.org/findNearbyPlaceName?lat=" + lat + "&lng=" + lon;
        InputStream is = Utils.openConnection(queryString);
        BufferedInputStream bis = new BufferedInputStream(is);

        /* Read bytes to the Buffer until there is nothing more to read(-1). */
        ByteArrayBuffer baf = new ByteArrayBuffer(50);
        int current = 0;
        while ((current = bis.read()) != -1) {
            if (isCanceled()) {
                res = TaskHandler.CANCELED;
                return true;
            }
            baf.append((byte) current);

        }

        place = this.parseGeoNames(baf.toByteArray());

        queryString = "http://www.google.com/ig/api?weather=" + place;
        /* Replace blanks with HTML-Equivalent. */
        url = new URL(queryString.replace(" ", "%20"));

        /* Get a SAXParser from the SAXPArserFactory. */
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();

        /* Get the XMLReader of the SAXParser we created. */
        XMLReader xr = sp.getXMLReader();

        /*
         * Create a new ContentHandler and apply it to the XML-Reader
         */
        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Parse the xml-data our URL-call returned. */
        xr.parse(new InputSource(url.openStream()));

        if (isCanceled()) {
            res = TaskHandler.CANCELED;
            return true;
        }
        /* Our Handler now provides the parsed weather-data to us. */
        ws = gwh.getWeatherSet();

        ws.place = place;
        res = TaskHandler.FINISHED;
        // map.showWeather(ws);
    } catch (IOException e) {
        if (e instanceof UnknownHostException) {
            res = TaskHandler.NO_RESPONSE;
        }
    } catch (Exception e) {
        log.log(Level.SEVERE, "", e);
        res = TaskHandler.ERROR;
    } finally {
        //         super.stop();
        return true;
    }
}

From source file:org.peterbaldwin.client.android.delicious.DeliciousApiRequest.java

/**
 * {@inheritDoc}// ww  w.j a v a2  s.c  o m
 */
public void run() {
    Message msg = mHandler.obtainMessage();
    msg.arg1 = mRequestType;
    msg.arg2 = mRequestId;
    msg.what = HANDLE_ERROR;
    msg.obj = "unknown error";
    boolean cacheUpdated = false;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        ContentHandler handler = mResponseHandler.getContentHandler();
        reader.setContentHandler(handler);

        InputStream in = null;
        if (in == null && mUseCache && mCacheFile != null) {
            in = readFromCache();
        }
        if (in == null) {
            in = readFromNetwork();

            if (mUpdateCache && mCacheFile != null) {
                in = updateCache(in);
                cacheUpdated = true;
            }
        }
        try {
            InputSource input = new InputSource(in);
            long start = now();
            try {
                reader.parse(input);
            } finally {
                logTiming("parse", start);
            }
        } finally {
            in.close();
        }
        msg.what = HANDLE_DONE;
        msg.obj = mResponseHandler;
    } catch (ConnectionException e) {
        setError(msg, e);
        int statusCode = e.getStatusCode();
        if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
            msg.what = HANDLE_AUTH_ERROR;
            msg.obj = "invalid username or password";
        } else {
            msg.what = HANDLE_ERROR;
            msg.obj = "unexpected response: " + statusCode;
        }
    } catch (IOException e) {
        setError(msg, e);
    } catch (ParserConfigurationException e) {
        setError(msg, e);
    } catch (SAXException e) {
        setError(msg, e);
    } catch (RuntimeException e) {
        setError(msg, e);
    } catch (Error e) {
        setError(msg, e);
    } finally {
        mHandler.sendMessage(msg);
    }

    if (msg.what != HANDLE_AUTH_ERROR && !cacheUpdated && mAlwaysUpdateCache && mCacheFile != null) {
        // If the authentication is valid, but the cache was not updated,
        // silently update the cache in the background after dispatching the
        // result to the handler.
        try {
            InputStream in = readFromNetwork();
            in = updateCache(in);
            in.close();
            Log.i(LOG_TAG, "cache file updated: " + mCacheFile);
        } catch (IOException e) {
            Log.e(LOG_TAG, "error updating cache", e);
        } catch (RuntimeException e) {
            Log.e(LOG_TAG, "error updating cache", e);
        } catch (Error e) {
            Log.e(LOG_TAG, "error updating cache", e);
        }
    }
}

From source file:eu.apenet.dpt.utils.util.Ead2EdmInformation.java

private void determineDaoInformation(File fileToRead)
        throws IOException, SAXException, ParserConfigurationException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();
    EadContentHandler myContentHandler = new EadContentHandler();
    xr.setContentHandler(myContentHandler);
    xr.parse(new InputSource(new InputStreamReader(new BOMInputStream(new FileInputStream(fileToRead)))));

    if (this.roleType == null) {
        this.roleType = "UNSPECIFIED";
    }/*ww w  . j  av a2s.  c o  m*/
}

From source file:com.edgenius.wiki.render.impl.FilterPipeImpl.java

public void load() throws FilterInitializeException {
    ClassLoader classLoader = Filter.class.getClassLoader();
    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //               Load filter configure XML file
    try {/* w  w w . j  a  va  2s  .c o m*/
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader reader = parser.getXMLReader();

        reader.setContentHandler(this.new FilterMetaParaser());
        reader.parse(new InputSource(classLoader.getResourceAsStream(filterResource)));
    } catch (Exception e) {
        log.error("Unable load filter configuare file " + filterResource, e);
        throw new FilterInitializeException(e);
    }

    //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    //               Load filter Pattern resource bundle file
    Properties patternResource = new Properties();
    try {
        patternResource.load(classLoader.getResourceAsStream(filterResourcePattern));
    } catch (Exception e) {
        log.error("Unable load PatternFilter pattern file " + filterResourcePattern, e);
        throw new FilterInitializeException(e);
    }

    Map<Integer, Filter> sortSet = new TreeMap<Integer, Filter>(new CompareToComparator());
    Map<Integer, RegionContentFilter> regionSortSet = new TreeMap<Integer, RegionContentFilter>(
            new CompareToComparator());
    for (FilterMetadata filterMeta : filterMetaList) {
        try {
            Object obj = classLoader.loadClass(filterMeta.getClassName().trim()).newInstance();
            if (obj instanceof Filter) {
                if (obj instanceof MacroFilter)
                    ((MacroFilter) obj).setMacroMgr(macroManager);

                //initial filter, if it is patternFilter, then do further initial
                if (obj instanceof PatternFilter) {
                    //!!! this markupPring must happen before setRegex() which may need getMarkupPrint() to build regex
                    String markupPrintVal = patternResource.getProperty(
                            ((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_MARKUP_PRINT);
                    if (!StringUtils.isBlank(markupPrintVal)) {
                        ((PatternFilter) obj).setMarkupPrint(markupPrintVal);
                    }
                    String matchVal = patternResource
                            .getProperty(((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_MATCH);
                    if (!StringUtils.isBlank(matchVal)) {
                        //special for link replacer
                        if (obj instanceof LinkFilter) {
                            linkReplacerFilter.setRegex(matchVal);
                        }
                        ((PatternFilter) obj).setRegex(matchVal);
                    }
                    String printVal = patternResource
                            .getProperty(((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_PRINT);
                    if (!StringUtils.isBlank(printVal)) {
                        ((PatternFilter) obj).setReplacement(printVal);
                    }
                    String htmlIDVal = patternResource.getProperty(
                            ((PatternFilter) obj).getPatternKey() + PatternFilter.SUFFIX_HTML_IDENTIFIER);
                    if (!StringUtils.isBlank(htmlIDVal)) {
                        ((PatternFilter) obj).setHTMLIdentifier(htmlIDVal);
                    }

                }
                filterNameMap.put(obj.getClass().getName(), (Filter) obj);

                ((Filter) obj).init();

                //new line filter always be last, but need special handle. see MarkupRenderEngineImpl.render()
                sortSet.put(filterMeta.getOrder(), (Filter) obj);
                if (obj instanceof RegionContentFilter) {
                    regionSortSet.put(filterMeta.getOrder(), (RegionContentFilter) obj);
                }

                log.info("Filter loaded into FilterPipe:" + obj.getClass().getName());
            } else {
                log.warn("Class " + obj.getClass().getName() + " does not implement Filter interface. "
                        + "It cannot be loaded into FilterPipe.");
            }
        } catch (InstantiationException e) {
            log.error("Filter failed on Instantiation " + filterMeta, e);
        } catch (IllegalAccessException e) {
            log.error("Filter failed on IllegalAccessException " + filterMeta, e);
        } catch (ClassNotFoundException e) {
            log.error("Filter ClassNotFoundException failed " + filterMeta, e);
        }
    }

    linkReplacerFilter.init();

    filterList.clear();
    filterList.addAll(sortSet.values());
    regionFilterList.clear();
    regionFilterList.addAll(regionSortSet.values());
}