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.zazuko.blv.outbreak.tools.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 {//  w  w w  .  j a  v  a 2 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:fr.eyal.lib.data.parser.GenericParser.java

public void parseSheet(final Object content, final int parseType) throws ParseException {

    //Sax method used for XML
    if (parseType == PARSE_TYPE_SAX) {

        //we convert the content to String
        String xml = new String((byte[]) content);
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        try {//from www.j  a  v a2  s  .  c  om
            final SAXParser sp = factory.newSAXParser();
            final XMLReader xr = sp.getXMLReader();

            final InputSource is = new InputSource();
            is.setCharacterStream(new StringReader(xml));

            //we set the SAX DefaultHandler
            xr.setContentHandler((DefaultHandler) mHandler);

            Out.v(TAG, "start parsing SAX");

            xr.parse(is);

            Out.v(TAG, "end parsing SAX");

        } catch (final Exception e) {
            e.printStackTrace();
            throw new ParseException("Parsing error");
        }

    } else if (parseType == PARSE_TYPE_JSON) {

        mHandler.parse(content);

    } else if (parseType == PARSE_TYPE_IMAGE) {

        mHandler.parse(content);

    }

}

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 {/*from   w ww.  j  av  a  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());
}

From source file:com.zazuko.wikidata.municipalities.SparqlClient.java

List<Map<String, RDFTerm>> queryResultSet(final String query) throws IOException, URISyntaxException {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    URIBuilder builder = new URIBuilder(endpoint);
    builder.addParameter("query", query);
    HttpGet httpGet = new HttpGet(builder.build());
    /*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
    nvps.add(new BasicNameValuePair("query", query));
    httpGet.setEntity(new UrlEncodedFormEntity(nvps));*/
    CloseableHttpResponse response2 = httpclient.execute(httpGet);

    try {// w w w.  j a v  a 2 s .c om
        HttpEntity entity2 = response2.getEntity();
        InputStream in = entity2.getContent();
        if (debug) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            for (int ch = in.read(); ch != -1; ch = in.read()) {
                System.out.print((char) ch);
                baos.write(ch);
            }
            in = new ByteArrayInputStream(baos.toByteArray());
        }
        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.myjeeva.poi.ExcelReader.java

/**
 * Parses the content of one sheet using the specified styles and shared-strings tables.
 * /*  w w  w .ja va2 s .c om*/
 * @param styles a {@link StylesTable} object
 * @param sharedStringsTable a {@link ReadOnlySharedStringsTable} object
 * @param sheetInputStream a {@link InputStream} object
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 */
private void readSheet(StylesTable styles, ReadOnlySharedStringsTable sharedStringsTable,
        InputStream sheetInputStream) throws IOException, ParserConfigurationException, SAXException {

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    XMLReader sheetParser = saxFactory.newSAXParser().getXMLReader();

    ContentHandler handler = new XSSFSheetXMLHandler(styles, sharedStringsTable, sheetContentsHandler, true);

    sheetParser.setContentHandler(handler);
    sheetParser.parse(new InputSource(sheetInputStream));
}

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

public ArrayList getArrivals() throws Exception {
    arrivals.clear();/*  w ww  . j  ava2s  . 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.webcohesion.ofx4j.client.impl.OFXHomeFIDataStore.java

private void initializeFIData() throws IOException, SAXException {
    URL url = new URL(getUrl());
    XMLReader xmlReader = new Parser();
    xmlReader.setFeature("http://xml.org/sax/features/namespaces", false);
    xmlReader.setFeature("http://xml.org/sax/features/validation", false);
    xmlReader.setContentHandler(new DirectoryContentHandler());
    xmlReader.parse(new InputSource(url.openStream()));
}

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 a v  a2s  .co m
            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:no.uis.service.studinfo.commons.StudinfoValidator.java

protected List<String> validate(String studieinfoXml, StudinfoType infoType, int year, FsSemester semester,
        String language) throws Exception {

    // save xml/*from   www .j a v a2  s.c om*/
    File outFile = new File("target/out", infoType.toString() + year + semester + language + ".xml");
    if (outFile.exists()) {
        outFile.delete();
    } else {
        outFile.getParentFile().mkdirs();
    }
    File outBackup = new File("target/out", infoType.toString() + year + semester + language + "_orig.xml");
    Writer backupWriter = new OutputStreamWriter(new FileOutputStream(outBackup), IOUtils.UTF8_CHARSET);
    backupWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
    IOUtils.copy(new StringReader(studieinfoXml), backupWriter, IOBUFFER_SIZE);
    backupWriter.flush();
    backupWriter.close();

    TransformerFactory trFactory = TransformerFactory.newInstance();
    Source schemaSource = new StreamSource(getClass().getResourceAsStream("/fspreprocess.xsl"));
    Transformer stylesheet = trFactory.newTransformer(schemaSource);

    Source input = new StreamSource(new StringReader(studieinfoXml));

    Result result = new StreamResult(outFile);
    stylesheet.transform(input, result);

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(false);
    factory.setNamespaceAware(true);

    SchemaFactory schemaFactory = SchemaFactory.newInstance("http://www.w3.org/2001/XMLSchema");
    Schema schema = schemaFactory
            .newSchema(new Source[] { new StreamSource(new File("src/main/xsd/studinfo.xsd")) });

    factory.setSchema(schema);

    SAXParser parser = factory.newSAXParser();

    XMLReader reader = parser.getXMLReader();
    ValidationErrorHandler errorHandler = new ValidationErrorHandler(infoType, year, semester, language);
    reader.setErrorHandler(errorHandler);
    reader.setContentHandler(errorHandler);
    try {
        reader.parse(
                new InputSource(new InputStreamReader(new FileInputStream(outFile), IOUtils.UTF8_CHARSET)));
    } catch (SAXException ex) {
        // do nothing. The error is handled in the error handler
    }
    return errorHandler.getMessages();
}

From source file:de.ifgi.lodum.sparqlfly.SparqlFly.java

/**
 * Returns jena model from URL//from ww w  .j  av a2s  . c  o  m
 * @throws ParseException 
 */
private Model getModelFromURL(String urlString, String format) throws Exception {
    Model m = ModelFactory.createDefaultModel(ReificationStyle.Standard);

    if (format.equals("HTML")) {
        StatementSink sink = new JenaStatementSink(m);
        XMLReader parser = ParserFactory.createReaderForFormat(sink, Format.HTML);
        parser.parse(urlString);
    } else {
        URL url = null;
        try {
            url = new URL(urlString);
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        }

        URLConnection c = null;
        try {
            c = url.openConnection();
            c.setConnectTimeout(10000);
        } catch (IOException e) {
            e.printStackTrace();
        }

        BufferedReader in = null;
        try {
            in = new BufferedReader(new InputStreamReader(c.getInputStream(), Charset.forName("UTF-8")));
        } catch (IOException e) {
            e.printStackTrace();
        }

        m.read(in, "", format);
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        RSIterator it = m.listReifiedStatements();
        while (it.hasNext()) {
            m.add(it.nextRS().getStatement());
        }
    }

    return m;
}