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.atguigu.bibiq.gsyvideoplay.BiliDanmukuParser.java

@Override
public Danmakus parse() {

    if (mDataSource != null) {
        AndroidFileSource source = (AndroidFileSource) mDataSource;
        try {/*from  w  w w .j av  a2  s.  c om*/
            XMLReader xmlReader = XMLReaderFactory.createXMLReader();
            XmlContentHandler contentHandler = new XmlContentHandler();
            xmlReader.setContentHandler(contentHandler);
            xmlReader.parse(new InputSource(source.data()));
            return contentHandler.getResult();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    return null;
}

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

public ArrayList getArrivals() throws Exception {
    arrivals.clear();//from  ww  w .  j  a  v a  2  s  .com

    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.typhoon.newsreader.engine.ChannelRefresh.java

public long syncDB(Handler h, long id, String rssurl) throws Exception {
    mHandler = h;/*  w  w w.j a v a  2  s.c  om*/
    mID = id;
    mRSSURL = rssurl;

    SAXParserFactory spf = SAXParserFactory.newInstance();
    SAXParser sp = spf.newSAXParser();
    XMLReader xr = sp.getXMLReader();

    xr.setContentHandler(this);
    xr.setErrorHandler(this);

    URL url = new URL(mRSSURL);

    URLConnection c = url.openConnection();
    c.setRequestProperty("User-Agent", "Android/m3-rc37a");
    xr.parse(new InputSource(c.getInputStream()));

    return mID;
}

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 {//  w  ww .  j a v  a 2 s .  co m
        //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:be.fedict.eidviewer.lib.file.imports.EidQuickKeyXMLFile.java

public void load(File file) throws CertificateException, FileNotFoundException, SAXException, IOException {
    logger.fine("Loading eID Quick Keys XML File");

    XMLReader reader = null;

    certificateFactory = CertificateFactory.getInstance("X.509");
    FileInputStream fis = new FileInputStream(file);

    reader = XMLReaderFactory.createXMLReader();
    reader.setContentHandler(this);
    reader.setErrorHandler(this);
    BufferedReader in = new BufferedReader(new InputStreamReader(fis));
    reader.parse(new InputSource(in));

    X509Utilities.setCertificateChainsFromCertificates(eidData, rootCert, citizenCert, authenticationCert,
            signingCert, rrnCert);//from  w ww .  ja v a 2 s .  com
}

From source file:com.mirth.connect.model.converters.ER7Serializer.java

/**
 * Returns an ER7-encoded HL7 message given an XML-encoded HL7 message.
 * /*from   ww w  . j ava 2s  .co m*/
 * @param source
 *            a XML-encoded HL7 message.
 * @return
 */
public String fromXML(String source) throws SerializerException {
    try {
        if (useStrictParser) {
            return pipeParser.encode(xmlParser.parse(source));
        } else {
            /*
             * The delimiters below need to come from the XML somehow. The
             * ER7 handler should take care of it TODO: Ensure you get these
             * elements from the XML
             */

            String segmentSeparator = "\r";
            String fieldSeparator = getNodeValue(source, "<MSH.1>", "</MSH.1>");

            if (StringUtils.isEmpty(fieldSeparator)) {
                fieldSeparator = "|";
            }

            String componentSeparator = "^";
            String repetitionSeparator = "~";
            String subcomponentSeparator = "&";
            String escapeCharacter = "\\";

            /*
             * Our delimiters usually look like this:
             * <MSH.2>^~\&amp;</MSH.2> We need to decode XML entities
             */
            String separators = getNodeValue(source, "<MSH.2>", "</MSH.2>").replaceAll("&amp;", "&");

            if (separators.length() == 4) {
                // usually ^
                componentSeparator = separators.substring(0, 1);
                // usually ~
                repetitionSeparator = separators.substring(1, 2);
                // usually \
                escapeCharacter = separators.substring(2, 3);
                // usually &
                subcomponentSeparator = separators.substring(3, 4);
            }

            XMLEncodedHL7Handler handler = new XMLEncodedHL7Handler(segmentSeparator, fieldSeparator,
                    componentSeparator, repetitionSeparator, escapeCharacter, subcomponentSeparator, true);
            XMLReader reader = XMLReaderFactory.createXMLReader();
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);

            /*
             * Parse, but first replace all spaces between brackets. This
             * fixes pretty-printed XML we might receive.
             */
            reader.parse(new InputSource(new StringReader(
                    source.replaceAll("\\s*<([^/][^>]*)>", "<$1>").replaceAll("<(/[^>]*)>\\s*", "<$1>"))));
            return handler.getOutput().toString();
        }
    } catch (Exception e) {
        throw new SerializerException(e);
    }
}

From source file:net.pandoragames.far.ui.MimeConfParser.java

/**
 * Read the mime type definition from xml.
 * @param input xml to be read/* w  ww . j  a  v a2 s. c om*/
 * @throws SAXException
 * @throws IOException
 */
public void parse(InputStream input) throws SAXException, IOException {
    Reader reader = new InputStreamReader(input);
    XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    InputSource xmlInput = new InputSource(reader);
    xmlReader.setContentHandler(new SAXHandler());
    xmlReader.parse(xmlInput);
}

From source file:com.determinato.feeddroid.parser.RssParser.java

/**
 * Persists RSS item to the database./*from  www .ja va 2  s . c o m*/
 * @param id item ID
 * @param folderId ID of containing folder
 * @param rssurl URL of RSS feed
 * @return long containing ID of inserted item
 * @throws Exception
 */
public long syncDb(long id, long folderId, String rssurl) throws Exception {
    mId = id;
    mFolderId = folderId;
    mRssUrl = rssurl;

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();
    XMLReader reader = parser.getXMLReader();

    reader.setContentHandler(this);
    reader.setErrorHandler(this);

    URL url = new URL(mRssUrl);

    URLConnection c = url.openConnection();
    // TODO: Is this a known user agent, or do I need to come up with my own?
    c.setRequestProperty("User-Agent", "Android/m3-rc37a");

    try {
        BufferedReader bufReader = new BufferedReader(new InputStreamReader(c.getInputStream()), 65535);
        reader.parse(new InputSource(bufReader));
    } catch (NullPointerException e) {
        Log.e(TAG, Log.getStackTraceString(e));
        Log.e(TAG, "Failed to load URL" + url.toString());
    }

    return mId;
}

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

/**
 * {@inheritDoc}/*from  w w  w  . ja  v a2s  . co  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:com.typhoon.newsreader.engine.ChannelRefresh.java

public List<FeedsListItem> parser(String link) {
    if (link.contains("www.24h.com.vn")) {
        try {// w  w w  .j  av a2  s .  com
            URL url = new URL(link);
            URLConnection connection = url.openConnection();
            connection.addRequestProperty("http.agent", USER_AGENT);
            InputSource input = new InputSource(url.openStream());
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();

            reader.setContentHandler(this);
            reader.parse(input);

            return getFeedsList();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    } else {
        try {
            // URL url= new URL(link);
            DefaultHttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(link);
            HttpResponse response = httpclient.execute(httpget);
            HttpEntity entity = response.getEntity();
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            factory.setValidating(false);
            SAXParser parser = factory.newSAXParser();
            XMLReader reader = parser.getXMLReader();
            reader.setContentHandler(this);
            InputSource inStream = new InputSource();
            inStream.setCharacterStream(new StringReader(EntityUtils.toString(entity)));
            reader.parse(inStream);
            return getFeedsList();
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
            return null;
        } catch (SAXException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
}