Example usage for org.xml.sax XMLReader setContentHandler

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

Introduction

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

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

From source file:com.sonicle.webtop.contacts.io.input.ContactExcelFileReader.java

private void readXlsxContacts(File file, BeanHandler beanHandler) throws IOException, FileReaderException {
    OPCPackage opc = null;//from   w  w  w.  j a v a2s .com
    HashMap<String, Integer> columnIndexes = listXlsxColumnIndexes(file);
    XlsRowHandler rowHandler = new XlsRowHandler(this, columnIndexes, beanHandler);

    try {
        opc = OPCPackage.open(file, PackageAccess.READ);
        XSSFReader reader = new XSSFReader(opc);
        ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(opc);
        StylesTable styles = reader.getStylesTable();

        XlsxRowsHandler rowsHandler = null;
        XSSFReader.SheetIterator sit = (XSSFReader.SheetIterator) reader.getSheetsData();
        while (sit.hasNext()) {
            InputStream is = null;
            try {
                is = sit.next();
                if (StringUtils.equals(sit.getSheetName(), sheet)) {
                    XMLReader xmlReader = SAXHelper.newXMLReader();
                    rowsHandler = new XlsxRowsHandler(is, headersRow, firstDataRow, lastDataRow, rowHandler);
                    ContentHandler xhandler = new XSSFSheetXMLHandler(styles, null, strings, rowsHandler, fmt,
                            false);
                    xmlReader.setContentHandler(xhandler);
                    xmlReader.parse(new InputSource(is));
                }
            } catch (SAXException | ParserConfigurationException ex) {
                throw new FileReaderException(ex, "Error processing file content");
            } catch (NullPointerException ex) {
                // Thrown when stream is forcibly closed. Simply ignore this!
            } finally {
                IOUtils.closeQuietly(is);
            }
            if (rowsHandler != null)
                break;
        }

    } catch (OpenXML4JException | SAXException ex) {
        throw new FileReaderException(ex, "Error opening file");
    } finally {
        IOUtils.closeQuietly(opc);
    }
}

From source file:cm.aptoide.pt.Aptoide.java

private void parseXmlString(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from   ww  w  .  j  a  v a 2s  . co m
        keepScreenOn.acquire();

        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputSource is = new InputSource();
        is.setCharacterStream(new StringReader(file));
        xr.parse(is);
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
    } catch (SAXException e) {
    } catch (ParserConfigurationException e) {
    }
}

From source file:edu.harvard.iq.dataverse.ingest.tabulardata.impl.plugins.xlsx.XLSXFileReader.java

public XMLReader fetchSheetParser(SharedStringsTable sst, DataTable dataTable, PrintWriter tempOut)
        throws SAXException {
    // An attempt to use org.apache.xerces.parsers.SAXParser resulted 
    // in some weird conflict in the app; the default XMLReader obtained 
    // from the XMLReaderFactory (from xml-apis.jar) appears to be working
    // just fine. however, 
    // TODO: verify why the app gets built with xml-apis-1.0.b2.jar; it's 
    // an old version - 1.4 seems to be the current release, and 2.0.2
    // (a new development?) appears to be available. We don't specifically
    // request this 1.0.* version, so another package must have it defined
    // as a dependency. We need to verify our dependencies, we most likely 
    // have some hard-coded versions in our pom.xml that are both old and 
    // unnecessary.
    // -- L.A. 4.0 alpha 1

    XMLReader xReader = XMLReaderFactory.createXMLReader();
    dbglog.fine("creating new SheetHandler;");
    ContentHandler handler = new SheetHandler(sst, dataTable, tempOut);
    xReader.setContentHandler(handler);
    return xReader;
}

From source file:com.vkassin.mtrade.Common.java

public static String generalWebServiceCall(String urlStr, ContentHandler handler) {

    String errorMsg = "";

    try {//from  w  w w .  java 2s  .co  m
        URL url = new URL(urlStr);

        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        urlc.setRequestProperty("User-Agent", "Android Application: aMTrade");
        urlc.setRequestProperty("Connection", "close");
        // urlc.setRequestProperty("Accept-Charset", "windows-1251");
        // urlc.setRequestProperty("Accept-Charset",
        // "windows-1251,utf-8;q=0.7,*;q=0.7");
        urlc.setRequestProperty("Accept-Charset", "utf-8");

        urlc.setConnectTimeout(1000 * 5); // mTimeout is in seconds
        urlc.setDoInput(true);
        urlc.connect();

        if (urlc.getResponseCode() == HttpURLConnection.HTTP_OK) {
            // 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();

            // Apply the handler to the XML-Reader
            xr.setContentHandler(handler);

            // Parse the XML-data from our URL.
            InputStream is = urlc.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(is);
            ByteArrayBuffer baf = new ByteArrayBuffer(500);
            int current = 0;
            while ((current = bis.read()) != -1) {
                baf.append((byte) current);
            }
            ByteArrayInputStream bais = new ByteArrayInputStream(baf.toByteArray());
            // Reader isr = new InputStreamReader(bais, "windows-1251");
            Reader isr = new InputStreamReader(bais, "utf-8");
            InputSource ist = new InputSource();
            // ist.setEncoding("UTF-8");
            ist.setCharacterStream(isr);
            xr.parse(ist);
            // Parsing has finished.

            bis.close();
            baf.clear();
            bais.close();
            is.close();
        }

        urlc.disconnect();

    } catch (SAXException e) {
        // All is OK :)
    } catch (MalformedURLException e) {
        Log.e(TAG, errorMsg = "MalformedURLException");
    } catch (IOException e) {
        Log.e(TAG, errorMsg = "IOException");
    } catch (ParserConfigurationException e) {
        Log.e(TAG, errorMsg = "ParserConfigurationException");
    } catch (ArrayIndexOutOfBoundsException e) {
        Log.e(TAG, errorMsg = "ArrayIndexOutOfBoundsException");
    }

    return errorMsg;
}

From source file:SAXTreeViewer.java

/**
 * <p>This handles building the Swing UI tree.</p>
 *
 * @param treeModel Swing component to build upon.
 * @param base tree node to build on./*from www . ja v a2  s .co  m*/
 * @param xmlURI URI to build XML document from.
 * @throws <code>IOException</code> - when reading the XML URI fails.
 * @throws <code>SAXException</code> - when errors in parsing occur.
 */
public void buildTree(DefaultTreeModel treeModel, DefaultMutableTreeNode base, String xmlURI)
        throws IOException, SAXException {

    // Create instances needed for parsing
    XMLReader reader = XMLReaderFactory.createXMLReader(vendorParserClass);
    ContentHandler jTreeContentHandler = new JTreeContentHandler(treeModel, base);
    ErrorHandler jTreeErrorHandler = new JTreeErrorHandler();

    // Register content handler
    reader.setContentHandler(jTreeContentHandler);

    // Register error handler
    reader.setErrorHandler(jTreeErrorHandler);

    // Parse
    InputSource inputSource = new InputSource(xmlURI);
    reader.parse(inputSource);
}

From source file:cm.aptoide.pt.Aptoide.java

private void getRemoteServLst(String file) {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    try {//from w ww .j a  va2s.c  o  m
        keepScreenOn.acquire();

        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        NewServerRssHandler handler = new NewServerRssHandler(this);
        xr.setContentHandler(handler);

        InputStreamReader isr = new FileReader(new File(file));
        InputSource is = new InputSource(isr);
        xr.parse(is);
        File xml_file = new File(file);
        xml_file.delete();
        server_lst = handler.getNewSrvs();
        get_apks = handler.getNewApks();

        keepScreenOn.release();

    } catch (IOException e) {
        e.printStackTrace();
    } catch (SAXException e) {
        e.printStackTrace();
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    }
}

From source file:com.commonsware.android.EMusicDownloader.SingleAlbum.java

private void getInfoFromXML() {

    //Show a progress dialog while reading XML
    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);//www.jav a2  s .  c o  m

            try {

                //Log.d("EMD - ","About to parse");

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleAlbum myXMLHandler = new XMLHandlerSingleAlbum();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                //Log.d("EMD - ","Done Parsing");

                statuscode = myXMLHandler.statuscode;
                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                genre = myXMLHandler.genre;
                genreId = myXMLHandler.genreId;
                labelId = myXMLHandler.labelId;
                label = myXMLHandler.label;
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                imageURL = myXMLHandler.imageURL;
                artist = myXMLHandler.artist;
                artistId = myXMLHandler.artistId;

                //Log.d("EMD - ","Set genre etc..");

                numberOfTracks = myXMLHandler.nItems;
                trackNames = myXMLHandler.tracks;
                //sampleAddresses = myXMLHandler.sampleAddress;
                //sampleExists = myXMLHandler.sampleExists;
                //vSamplesExist = myXMLHandler.samplesExist;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {
                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_album_info);
                    }
                });

            }

            //Remove Progress Dialog
            if (dialog.isShowing()) {
                dialog.dismiss();
            }
            handlerDoneLoading.sendEmptyMessage(0);
        }
    };
    t3.start();
}

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlParser.java

/**
 * Parse InputStream.//w  w  w.  jav a 2s  .  c om
 */
public synchronized Node parse(InputStream in) throws IOException, SAXException {
    Handler handler = new Handler();
    XMLReader reader = _parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);
    reader.setEntityResolver(handler);
    _parser.parse(new InputSource(in), handler);
    if (handler._error != null)
        throw handler._error;
    Node doc = (Node) handler._top.get(0);
    handler.clear();
    return doc;
}

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlParser.java

public synchronized Node parse(InputSource source) throws IOException, SAXException {
    Handler handler = new Handler();
    XMLReader reader = _parser.getXMLReader();
    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);/*from w ww.j a v  a2  s.  co m*/
    reader.setEntityResolver(handler);
    if (log.isDebugEnabled())
        log.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId());
    _parser.parse(source, handler);
    if (handler._error != null)
        throw handler._error;
    Node doc = (Node) handler._top.get(0);
    handler.clear();
    return doc;
}

From source file:com.cyberway.issue.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./* w  ww  .  j a  v  a 2 s .co m*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(f.getPath());
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}