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:com.badugi.game.logic.model.utils.common.XmlUtils.java

/**
 * Retrieve the text for a group of elements. Each text element is an entry
 * in a list.//  w w w  .j  a  v a  2s. c om
 * <p>This method is currently optimized for the use case of two elements in a list.
 *
 * @param xmlAsString the xml response
 * @param element     the element to look for
 * @return the list of text from the elements.
 */
public static List<String> getTextForElements(final String xmlAsString, final String element) {
    final List<String> elements = new ArrayList<String>(2);
    final XMLReader reader = getXmlReader();

    final DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        private StringBuilder buffer = new StringBuilder();

        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;
                elements.add(this.buffer.toString());
                this.buffer = new StringBuilder();
            }
        }

        public void characters(char[] ch, int start, int length) throws SAXException {
            if (this.foundElement) {
                this.buffer.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 elements;
}

From source file:com.keithhutton.ws.proxy.ProxyServlet.java

private XmlRpcRequest getMethodAndParamsFromRequest(ServletRequest req) throws XmlRpcException {
    final XmlRpcStreamRequestConfig pConfig = getConfig((HttpServletRequest) req);
    final XmlRpcRequestParser parser = new XmlRpcRequestParser(pConfig, getTypeFactory());
    final XMLReader xr = SAXParsers.newXMLReader();
    xr.setContentHandler(parser);/*from w ww . j  a v  a  2 s  .co  m*/
    try {
        xr.parse(new InputSource(req.getInputStream()));
    } catch (SAXException e) {
        Exception ex = e.getException();
        if (ex != null && ex instanceof XmlRpcException) {
            throw (XmlRpcException) ex;
        }
        throw new XmlRpcException("Failed to parse XML-RPC request: " + e.getMessage(), e);
    } catch (IOException e) {
        throw new XmlRpcException("Failed to read XML-RPC request: " + e.getMessage(), e);
    }
    final List params = parser.getParams();
    final int paramCount = params == null ? 0 : params.size();
    XmlRpcRequest xmlRpcRequest = new XmlRpcRequest() {
        public XmlRpcRequestConfig getConfig() {
            return pConfig;
        }

        public String getMethodName() {
            return parser.getMethodName();
        }

        public int getParameterCount() {
            return params == null ? 0 : params.size();
        }

        public Object getParameter(int pIndex) {
            return paramCount > 0 ? params.get(pIndex) : null;
        }
    };
    this.log.info("xmlRpcRequest method = " + xmlRpcRequest.getMethodName());
    this.log.info("xmlRpcRequest pcount = " + xmlRpcRequest.getParameterCount());
    this.log.info("xmlRpcRequest param1 = " + xmlRpcRequest.getParameter(0));
    return xmlRpcRequest;

}

From source file:com.zegoggles.smssync.auth.XOAuthConsumer.java

private String extractEmail(HttpResponse response)
        throws ParserConfigurationException, SAXException, IOException {
    final XMLReader xmlReader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
    final FeedHandler feedHandler = new FeedHandler();
    xmlReader.setContentHandler(feedHandler);
    xmlReader.parse(new InputSource(response.getEntity().getContent()));
    return feedHandler.getEmail();
}

From source file:importer.handler.post.annotate.HTMLConverter.java

/**
 * Turn XML note content for Harpur to HTML
 * @param xml the xml note//from w w  w  .  j  a v a2 s. co  m
 * @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: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");
    }/* ww  w. j a  v a2 s  .  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:org.apache.commons.rdf.impl.sparql.SparqlClient.java

List<Map<String, RdfTerm>> queryResultSet(final String query) throws IOException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpPost httpPost = new HttpPost(endpoint);
    List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpPost.setEntity(new UrlEncodedFormEntity(nvps));
    CloseableHttpResponse response2 = httpclient.execute(httpPost);

    try {/*from  w  w w.  j  a va2 s .c o  m*/
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser saxParser = spf.newSAXParser();
        XMLReader xmlReader = saxParser.getXMLReader();
        final SparqlsResultsHandler sparqlsResultsHandler = new SparqlsResultsHandler();
        xmlReader.setContentHandler(sparqlsResultsHandler);
        xmlReader.parse(new InputSource(in));
        /*
         for (int ch = in.read(); ch != -1; ch = in.read()) {
         System.out.print((char)ch);
         }
         */
        // do something useful with the response body
        // and ensure it is fully consumed
        EntityUtils.consume(entity2);
        return sparqlsResultsHandler.getResults();
    } catch (ParserConfigurationException ex) {
        throw new RuntimeException(ex);
    } catch (SAXException ex) {
        throw new RuntimeException(ex);
    } finally {
        response2.close();
    }

}

From source file:com.webcohesion.ofx4j.io.BaseOFXReader.java

/**
 * Parse an OFX version 2 stream from the first OFX element (defined by the {@link #getFirstElementStart() first element characters}).
 *
 * @param reader The reader.// w  w  w .j a v a2s .c o  m
 */
protected void parseV2FromFirstElement(Reader reader) throws IOException, OFXParseException {
    try {
        XMLReader xmlReader = XMLReaderFactory.createXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
        xmlReader.setContentHandler(new OFXV2ContentHandler(getContentHandler()));
        xmlReader.parse(new InputSource(reader));
    } catch (SAXException e) {
        if (e.getCause() instanceof OFXParseException) {
            throw (OFXParseException) e.getCause();
        }

        throw new OFXParseException(e);
    }
}

From source file:com.myjeeva.poi.ExcelXSSFRowCallbackHandler.java

/**
 * Parses the file, passing each row to the given callback.
 * At the end closes the opc package and underling input stream.
 *//*from   w  w  w .ja  va  2  s  .  com*/
public void parse() throws Exception {

    XSSFReader reader = new XSSFReader(this.opcPackage);

    StylesTable styles = reader.getStylesTable();
    ReadOnlySharedStringsTable sharedStrings = new ReadOnlySharedStringsTable(this.opcPackage);

    ContentHandler handler = new XSSFSheetXMLHandler(styles, sharedStrings,
            new ExcelXSSFRowCallbackSheetContentsHandler(this.rowCallback), true);

    XMLReader parser = XMLReaderFactory.createXMLReader();
    parser.setContentHandler(handler);

    InputStream sheetInputStream = reader.getSheetsData().next();

    try {

        parser.parse(new InputSource(sheetInputStream));

    } finally {

        IOUtils.closeQuietly(sheetInputStream);
        this.opcPackage.close();

    }

}

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 ww w . j av a 2  s . 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.chitek.util.XMLConfigParser.java

/**
 * Parses the given XML and uses reflection to apply the configuration.<br />
 * 'setting' uses the set... methods in the configuration for all found settings.
 *  Supported types are boolean, int and String.<br />
 * 'config' creates a new instance of the given type and uses the add... method
 * in the configuration class to add new elements. The type of the new class is
 * determined by the parameter type of the add... method. 
 * //from  w ww. j a  v  a 2 s .  c o  m
 * @param clazz
 *            The Class to return
 * @param typeName
 *            The name of the XML-Element with the configuration
 * @param configXML
 *            The XML configuration to parse
 * @return A new instance of clazz
 * @throws Exception
 */
public Object parseXML(Class<?> clazz, String typeName, String configXML) throws Exception {
    Object config = clazz.newInstance();

    try {
        XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
        reader.setContentHandler(new ContentHandler(config, typeName));
        reader.parse(new InputSource(new StringReader(configXML)));
    } catch (Exception e) {
        throw e;
    }
    return config;
}