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.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   www . ja v  a  2  s .  c  o  m*/
    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();/*ww  w. j a  v  a2 s  .  c om*/
    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:importer.handler.post.annotate.HTMLConverter.java

/**
 * Turn XML note content for Harpur to HTML
 * @param xml the xml note/*from   www  .jav  a 2  s  .com*/
 * @param config the JSON config to control the conversion
 * @return a HTML string
 */
String convert(String xml) throws HTMLException {
    try {
        SAXParserFactory spf = SAXParserFactory.newInstance();
        HTMLConverter conv = new HTMLConverter(patterns);
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        XMLReader xmlReader = parser.getXMLReader();
        xmlReader.setContentHandler(conv);
        xmlReader.setErrorHandler(new MyErrorHandler(System.err));
        CharArrayReader car = new CharArrayReader(xml.toCharArray());
        InputSource input = new InputSource(car);
        xmlReader.parse(input);
        return conv.body.toString();
    } catch (Exception e) {
        throw new HTMLException(e);
    }
}

From source file:it.openyoureyes.test.OpenCellId.java

private String parseImage(HttpEntity entity, DefaultHandler dd) throws IOException {
    String result = "";
    String line;//from  ww w  .  j  a  v  a2s  .  c om

    try {

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

        /* Parse the xml-data from our URL. */
        xr.parse(new InputSource(entity.getContent()));

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        entity.consumeContent();
    }
    return result;
}

From source file:com.badugi.game.logic.model.utils.common.XmlUtils.java

/**
 * Retrieve the text for a specific element (when we know there is only
 * one)./*from  w ww  .  j a v a  2s.co  m*/
 *
 * @param xmlAsString the xml response
 * @param element     the element to look for
 * @return the text value of the element.
 */
public static String getTextForElement(final String xmlAsString, final String element) {
    final XMLReader reader = getXmlReader();
    final StringBuilder builder = new StringBuilder();

    final DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        public void startElement(final String uri, final String localName, final String qName,
                final Attributes attributes) throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = true;
            }
        }

        public void endElement(final String uri, final String localName, final String qName)
                throws SAXException {
            if (localName.equals(element)) {
                this.foundElement = false;
            }
        }

        public void characters(char[] ch, int start, int length) throws SAXException {
            if (this.foundElement) {
                builder.append(ch, start, length);
            }
        }
    };

    reader.setContentHandler(handler);
    reader.setErrorHandler(handler);

    try {
        reader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (final Exception e) {
        LOG.error(e, e);
        return null;
    }

    return builder.toString();
}

From source file:eionet.gdem.conversion.excel.ExcelProcessor.java

/**
 * Converts XML string to OutputStream//from   w ww  .  j a  v  a 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:de.faustedition.tei.TeiValidator.java

public List<String> validate(FaustURI uri) throws SAXException, IOException {
    if (logger.isDebugEnabled()) {
        logger.debug("Validating via RelaxNG: " + uri);
    }/*  w  w  w  . j a  v a 2 s. co  m*/
    final CustomErrorHandler errorHandler = new CustomErrorHandler();
    final Validator validator = schema
            .createValidator(errorHandler.configurationWithErrorHandler().toPropertyMap());

    final XMLReader xmlReader = XMLReaderFactory.createXMLReader();
    xmlReader.setContentHandler(validator.getContentHandler());
    xmlReader.parse(xml.getInputSource(uri));

    return errorHandler.getErrors();
}

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 {//from w w  w  .j a v a 2s  . c  o  m
        log.debug("empty content");
        return new ParseResult(new HashMap<QName, String>(), new HashSet<QName>());
    }

}

From source file:com.notesrender.templatej.TemplateProcessor.java

public void process(String filePath) {
    try {/*from   w w w .j a v  a 2 s  .c o  m*/
        XMLReader rd = XMLReaderFactory.createXMLReader();
        rd.setContentHandler(this);
        rd.parse(new InputSource(new FileInputStream(filePath)));

        String fullFilePath = new File(filePath).getAbsolutePath();
        String dir = FilenameUtils.getFullPath(fullFilePath);
        String tplFullFilePath = new File(dir, _ref).getAbsolutePath();
        String outFullFilePath = new File(dir, _out).getAbsolutePath();

        _writer = new PrintWriter(new BufferedWriter(new FileWriter(outFullFilePath)));
        rd.parse(new InputSource(new FileInputStream(tplFullFilePath)));
        _writer.close();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:cn.com.loopj.android.http.SaxAsyncHttpResponseHandler.java

/**
 * Deconstructs response into given content handler
 *
 * @param entity returned HttpEntity/*from w  w w . jav  a  2 s .  c  om*/
 * @return deconstructed response
 * @throws IOException if there is problem assembling SAX response from stream
 * @see HttpEntity
 */
@Override
protected byte[] getResponseData(HttpEntity entity) throws IOException {
    if (entity != null) {
        InputStream instream = entity.getContent();
        InputStreamReader inputStreamReader = null;
        if (instream != null) {
            try {
                SAXParserFactory sfactory = SAXParserFactory.newInstance();
                SAXParser sparser = sfactory.newSAXParser();
                XMLReader rssReader = sparser.getXMLReader();
                rssReader.setContentHandler(handler);
                inputStreamReader = new InputStreamReader(instream, getCharset());
                rssReader.parse(new InputSource(inputStreamReader));
            } catch (SAXException e) {
                AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e);
            } catch (ParserConfigurationException e) {
                AsyncHttpClient.log.e(LOG_TAG, "getResponseData exception", e);
            } finally {
                AsyncHttpClient.silentCloseInputStream(instream);
                if (inputStreamReader != null) {
                    try {
                        inputStreamReader.close();
                    } catch (IOException e) {
                        /*ignore*/ }
                }
            }
        }
    }
    return null;
}