Example usage for javax.xml.parsers SAXParser getXMLReader

List of usage examples for javax.xml.parsers SAXParser getXMLReader

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser getXMLReader.

Prototype


public abstract org.xml.sax.XMLReader getXMLReader() throws SAXException;

Source Link

Document

Returns the org.xml.sax.XMLReader that is encapsulated by the implementation of this class.

Usage

From source file:com.edgenius.wiki.ext.textnut.NutParser.java

public Map<String, File> parseBPlist(InputStream bs) {

    try {/*from   w  w w. j  a va 2s  .co m*/
        NSObject obj = BinaryPropertyListParser.parse(bs);

        //parse BPList
        BPListParaserHandler handler = new BPListParaserHandler(new File(FileUtil.createTempDirectory("_nut")));
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        XMLReader reader = parser.getXMLReader();
        reader.setContentHandler(handler);

        //parse
        reader.parse(new org.xml.sax.InputSource(new StringReader(obj.toXML())));

        //all files - main HTML file key is "MAIN_RESOURCE_URL"
        return handler.getFiles();
    } catch (UnsupportedEncodingException e) {
        log.error("Unsupport encoding for BPList", e);
    } catch (Exception e) {
        log.error("Parase BPList error.", e);
    }
    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//  w w w.  j  a  v  a 2s .co m
    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:com.travelguide.GuideActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main2);
    final String TAG = "Activity2";

    String ln = getIntent().getExtras().getString("tag");
    if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Gracias por usar mi aplicacin.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText("Las ubicaciones de visitantes en el interior "
                + getIntent().getExtras().getString("com.travelguide.radius") + " millas para "
                + getIntent().getExtras().getString("com.travelguide.location"));

    } else {/*from www.j  a v a  2  s  . c o  m*/
        TextView t1 = (TextView) findViewById(R.id.thanks);
        t1.setText("Thanks for using my App.");

        TextView t2 = (TextView) findViewById(R.id.link);
        t2.setText(
                "Visitor locations found within " + getIntent().getExtras().getString("com.travelguide.radius")
                        + " miles for " + getIntent().getExtras().getString("com.travelguide.location"));

    }

    String url = getIntent().getExtras().getString("com.travelguide.link");
    Log.i(TAG, url);

    try {
        //***** Parsing the xml file*****
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();

        tgparse myXML_parser = new tgparse();
        xr.setContentHandler(myXML_parser);

        HttpClient httpclient = new DefaultHttpClient();
        HttpGet httpget = new HttpGet(url.replace(" ", "%20"));
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String responseBody = httpclient.execute(httpget, responseHandler);
        Log.i(TAG, "responseBody: " + responseBody);
        ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());
        xr.parse(new InputSource(is));

        Log.i(TAG, "parse complete");

        TextView placename[];
        TextView placeaddress[];
        TextView placerating[];

        tgxml data;
        data = tgparse.getXMLData();
        placename = new TextView[data.getName().size()];
        placeaddress = new TextView[data.getName().size()];
        placerating = new TextView[data.getName().size()];

        webview = (WebView) findViewById(R.id.myWebView);

        //    webview.setBackgroundColor(0);
        //    webview.setBackgroundResource(R.drawable.openbook);

        String stg1 = new String();
        stg1 = "<html>";
        for (int i = 1; i < (data.getName().size()); i++) {
            Log.i(TAG, " " + i);
            Log.i(TAG, "Name= " + data.getName().get(i));
            Log.i(TAG, "Address= " + data.getAddress().get(i));
            Log.i(TAG, "Rating= " + data.getRating().get(i));

            placename[i] = new TextView(this);
            placename[i].setText("Name= " + data.getName().get(i));

            placeaddress[i] = new TextView(this);
            placeaddress[i].setText("Address= " + data.getAddress().get(i));

            placerating[i] = new TextView(this);
            placerating[i].setText("Rating= " + data.getRating().get(i));

            if ((ln.equals("Espaol")) || (ln.equals("Spanish"))) {
                stg1 = stg1 + "Nombre: " + data.getName().get(i) + "<br>" + " Direccin: "
                        + data.getAddress().get(i) + "<br>" + " clasificacin= " + data.getRating().get(i)
                        + "<br>" + "<br>";
            } else {
                stg1 = stg1 + "Name: " + data.getName().get(i) + "<br>" + " Address: "
                        + data.getAddress().get(i) + "<br>" + " Rating= " + data.getRating().get(i) + "<br>"
                        + "<br>";
            }

        }
        stg1 = stg1 + "</html>";
        webview.loadDataWithBaseURL(null, stg1, "text/html", "utf-8", "about:blank");

    } catch (Exception e) {
        Log.i(TAG, "Exception caught", e);

    }

}

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 {/*w w  w .  ja v  a2s .co  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:net.sourceforge.fenixedu.utilTests.ParseMetadata.java

public Vector<Element> parseMetadata(String metadataFile) throws ParseException {
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(true);/* w w w.ja  v a2 s .c om*/
    try {
        SAXParser saxParser = spf.newSAXParser();
        XMLReader reader = saxParser.getXMLReader();
        reader.setContentHandler(this);
        reader.setErrorHandler(this);
        StringReader sr = new StringReader(metadataFile);
        InputSource input = new InputSource(sr);
        MetadataResolver resolver = new MetadataResolver();
        reader.setEntityResolver(resolver);
        reader.parse(input);
    } catch (Exception e) {
        throw new ParseException();
    }

    setMembers(vector);
    return vector;
}

From source file:org.gots.weather.provider.google.GoogleWeatherTask.java

@Override
protected WeatherConditionInterface doInBackground(Object... arg0) {
    if (force || ws == null) {

        try {//from w w w  .  ja  va2s .co m

            // android.os.Debug.waitForDebugger();
            /*************/

            HttpClient httpclient = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(url.toURI());

            // create a response handler
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            String responseBody = httpclient.execute(httpget, responseHandler);
            // Log.d(DEBUG_TAG, "response from httpclient:n "+responseBody);

            ByteArrayInputStream is = new ByteArrayInputStream(responseBody.getBytes());

            /* 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();

            /* Create a new ContentHandler and apply it to the XML-Reader */
            GoogleWeatherHandler gwh = new GoogleWeatherHandler();
            xr.setContentHandler(gwh);

            // InputSource is = new InputSource(url.openStream());
            /* Parse the xml-data our URL-call returned. */
            xr.parse(new InputSource(is));

            /* Our Handler now provides the parsed weather-data to us. */
            ws = gwh.getWeatherSet();
        } catch (Exception e) {
            Log.e("WeatherManager", "WeatherQueryError", e);

        }
        force = false;
    }
    Calendar requestCalendar = Calendar.getInstance();
    requestCalendar.setTime(requestedDay);
    if (ws == null)
        return new WeatherCondition(requestedDay);
    else if (requestCalendar.get(Calendar.DAY_OF_YEAR) == Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
        return ws.getWeatherCurrentCondition();
    else if (requestCalendar.get(Calendar.DAY_OF_YEAR) > Calendar.getInstance().get(Calendar.DAY_OF_YEAR))
        return ws.getWeatherForecastConditions().get(
                requestCalendar.get(Calendar.DAY_OF_YEAR) - Calendar.getInstance().get(Calendar.DAY_OF_YEAR));
    return new WeatherCondition(requestedDay);

}

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 {//from   ww w.j a va 2s. co  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.gc.iotools.fmt.detect.droid.DroidDetectorImpl.java

private XMLReader getXMLReader(final SAXModelBuilder mb) throws Exception {
    final SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setNamespaceAware(true);//w w  w. java  2s.co  m
    // factory.setValidating(true);
    final SAXParser saxParser = factory.newSAXParser();
    final XMLReader parser = saxParser.getXMLReader();
    // URL url = DroidDetectorImpl.class
    // .getResource("DROID_SignatureFile.xsd");
    // parser.setProperty(
    // "http://java.sun.com/xml/jaxp/properties/schemaSource", url);
    mb.setupNamespace(SIGNATURE_FILE_NS, true);
    parser.setContentHandler(mb);
    return parser;
}

From source file:com.dhenton9000.excel.ExcelParser.java

public SheetResults parse(InputStream inputStream) throws Exception {

    OPCPackage pkg = OPCPackage.open(inputStream);
    XSSFReader reader = new XSSFReader(pkg);
    this.sst = reader.getSharedStringsTable();

    SAXParserFactory saxFactory = SAXParserFactory.newInstance();
    SAXParser saxParser = saxFactory.newSAXParser();
    XMLReader parser = saxParser.getXMLReader();
    parser.setContentHandler(this);

    // There should only be one sheet
    final Iterator<InputStream> it = reader.getSheetsData();
    final InputStream sheet = it.next();

    final InputSource sheetSource = new InputSource(sheet);
    parser.parse(sheetSource);//ww  w  .  j  av  a2  s.com
    sheet.close();

    return getSheetResults();

}

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 {//  ww w  . j ava2 s  .  c o m
        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();
    }

}