Example usage for javax.xml.parsers SAXParserFactory newSAXParser

List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newSAXParser.

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and SAX events out.
 *///from w  ww.j  a  va2s . c  o  m
public static void exampleContentHandlerToContentHandler(String sourceID, String xslID)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Does this factory support SAX features?
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        // If so, we can safely cast.
        SAXTransformerFactory stfactory = ((SAXTransformerFactory) tfactory);

        // A TransformerHandler is a ContentHandler that will listen for 
        // SAX events, and transform them to the result.
        TransformerHandler handler = stfactory.newTransformerHandler(new StreamSource(xslID));

        // Set the result handling to be a serialization to System.out.
        Result result = new SAXResult(new ExampleContentHandler());
        handler.setResult(result);

        // Create a reader, and set it's content handler to be the TransformerHandler.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);

        // It's a good idea for the parser to send lexical events.
        // The TransformerHandler is also a LexicalHandler.
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Parse the source XML, and send the parse events to the TransformerHandler.
        reader.parse(sourceID);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:Examples.java

/**
 * Show the Transformer using SAX events in and DOM nodes out.
 *//* w w  w  .j  av a2 s.  c o m*/
public static void exampleContentHandler2DOM(String sourceID, String xslID) throws TransformerException,
        TransformerConfigurationException, SAXException, IOException, ParserConfigurationException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    // Make sure the transformer factory we obtained supports both
    // DOM and SAX.
    if (tfactory.getFeature(SAXSource.FEATURE) && tfactory.getFeature(DOMSource.FEATURE)) {
        // We can now safely cast to a SAXTransformerFactory.
        SAXTransformerFactory sfactory = (SAXTransformerFactory) tfactory;

        // Create an Document node as the root for the output.
        DocumentBuilderFactory dfactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder docBuilder = dfactory.newDocumentBuilder();
        org.w3c.dom.Document outNode = docBuilder.newDocument();

        // Create a ContentHandler that can liston to SAX events 
        // and transform the output to DOM nodes.
        TransformerHandler handler = sfactory.newTransformerHandler(new StreamSource(xslID));
        handler.setResult(new DOMResult(outNode));

        // Create a reader and set it's ContentHandler to be the 
        // transformer.
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();
        reader.setContentHandler(handler);
        reader.setProperty("http://xml.org/sax/properties/lexical-handler", handler);

        // Send the SAX events from the parser to the transformer,
        // and thus to the DOM tree.
        reader.parse(sourceID);

        // Serialize the node for diagnosis.
        exampleSerializeNode(outNode);
    } else {
        System.out.println(
                "Can't do exampleContentHandlerToContentHandler because tfactory is not a SAXTransformerFactory");
    }
}

From source file:org.springsource.ide.eclipse.commons.core.SpringCoreUtils.java

public static SAXParser getSaxParser() {
    if (!SAX_PARSER_ERROR) {
        try {/*from  w w w  . j  a  v a 2 s  . co  m*/
            SAXParserFactory factory = SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            SAXParser parser = factory.newSAXParser();
            return parser;
        } catch (Exception e) {
            StatusHandler.log(new Status(IStatus.INFO, CorePlugin.PLUGIN_ID,
                    "Error creating SaxParserFactory. Switching to OSGI service reference."));
            SAX_PARSER_ERROR = true;
        }
    }

    BundleContext bundleContext = CorePlugin.getDefault().getBundle().getBundleContext();
    ServiceReference reference = bundleContext.getServiceReference(SAXParserFactory.class.getName());
    if (reference != null) {
        try {
            synchronized (SAX_PARSER_LOCK) {
                SAXParserFactory factory = (SAXParserFactory) bundleContext.getService(reference);
                return factory.newSAXParser();
            }
        } catch (Exception e) {
            StatusHandler
                    .log(new Status(IStatus.ERROR, CorePlugin.PLUGIN_ID, "Error creating SaxParserFactory", e));
        } finally {
            bundleContext.ungetService(reference);
        }
    }

    return null;
}

From source file:Examples.java

/**
 * This example shows how to chain events from one Transformer
 * to another transformer, using the Transformer as a
 * SAX2 XMLFilter/XMLReader./*from ww w . java  2 s  . c  o  m*/
 */
public static void exampleXMLFilterChain(String sourceID, String xslID_1, String xslID_2, String xslID_3)
        throws TransformerException, TransformerConfigurationException, SAXException, IOException {
    TransformerFactory tfactory = TransformerFactory.newInstance();

    Templates stylesheet1 = tfactory.newTemplates(new StreamSource(xslID_1));
    Transformer transformer1 = stylesheet1.newTransformer();

    // If one success, assume all will succeed.
    if (tfactory.getFeature(SAXSource.FEATURE)) {
        SAXTransformerFactory stf = (SAXTransformerFactory) tfactory;
        XMLReader reader = null;

        // Use JAXP1.1 ( if possible )
        try {
            javax.xml.parsers.SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance();
            factory.setNamespaceAware(true);
            javax.xml.parsers.SAXParser jaxpParser = factory.newSAXParser();
            reader = jaxpParser.getXMLReader();

        } catch (javax.xml.parsers.ParserConfigurationException ex) {
            throw new org.xml.sax.SAXException(ex);
        } catch (javax.xml.parsers.FactoryConfigurationError ex1) {
            throw new org.xml.sax.SAXException(ex1.toString());
        } catch (NoSuchMethodError ex2) {
        }
        if (reader == null)
            reader = XMLReaderFactory.createXMLReader();

        XMLFilter filter1 = stf.newXMLFilter(new StreamSource(xslID_1));
        XMLFilter filter2 = stf.newXMLFilter(new StreamSource(xslID_2));
        XMLFilter filter3 = stf.newXMLFilter(new StreamSource(xslID_3));

        if (null != filter1) // If one success, assume all were success.
        {
            // transformer1 will use a SAX parser as it's reader.    
            filter1.setParent(reader);

            // transformer2 will use transformer1 as it's reader.
            filter2.setParent(filter1);

            // transform3 will use transform2 as it's reader.
            filter3.setParent(filter2);

            filter3.setContentHandler(new ExampleContentHandler());
            // filter3.setContentHandler(new org.xml.sax.helpers.DefaultHandler());

            // Now, when you call transformer3 to parse, it will set  
            // itself as the ContentHandler for transform2, and 
            // call transform2.parse, which will set itself as the 
            // content handler for transform1, and call transform1.parse, 
            // which will set itself as the content listener for the 
            // SAX parser, and call parser.parse(new InputSource("xml/foo.xml")).
            filter3.parse(new InputSource(sourceID));
        } else {
            System.out.println("Can't do exampleXMLFilter because " + "tfactory doesn't support asXMLFilter()");
        }
    } else {
        System.out.println("Can't do exampleXMLFilter because " + "tfactory is not a SAXTransformerFactory");
    }
}

From source file:org.metawatch.manager.Monitors.java

private static synchronized void updateWeatherDataGoogle(Context context) {
    try {//  www .  ja v  a 2 s .  co m

        if (WeatherData.updating)
            return;

        // Prevent weather updating more frequently than every 5 mins
        if (WeatherData.timeStamp != 0 && WeatherData.received) {
            long currentTime = System.currentTimeMillis();
            long diff = currentTime - WeatherData.timeStamp;

            if (diff < 5 * 60 * 1000) {
                if (Preferences.logging)
                    Log.d(MetaWatch.TAG, "Skipping weather update - updated less than 5m ago");

                //IdleScreenWidgetRenderer.sendIdleScreenWidgetUpdate(context);

                return;
            }
        }

        WeatherData.updating = true;

        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherDataGoogle(): start");

        String queryString;
        List<Address> addresses;
        if (Preferences.weatherGeolocation && LocationData.received) {
            Geocoder geocoder;
            String locality = "";
            String PostalCode = "";
            try {
                geocoder = new Geocoder(context, Locale.getDefault());
                addresses = geocoder.getFromLocation(LocationData.latitude, LocationData.longitude, 1);

                for (Address address : addresses) {
                    if (!address.getPostalCode().equalsIgnoreCase("")) {
                        PostalCode = address.getPostalCode();
                        locality = address.getLocality();
                        if (locality.equals("")) {
                            locality = PostalCode;
                        } else {
                            PostalCode = locality + ", " + PostalCode;
                        }

                    }
                }
            } catch (IOException e) {
                if (Preferences.logging)
                    Log.e(MetaWatch.TAG, "Exception while retreiving postalcode", e);
            }

            if (PostalCode.equals("")) {
                PostalCode = Preferences.weatherCity;
            }
            if (locality.equals("")) {
                WeatherData.locationName = PostalCode;
            } else {
                WeatherData.locationName = locality;
            }

            queryString = "http://www.google.com/ig/api?weather=" + PostalCode;
        } else {
            queryString = "http://www.google.com/ig/api?weather=" + Preferences.weatherCity;
            WeatherData.locationName = Preferences.weatherCity;
        }

        URL url = new URL(queryString.replace(" ", "%20"));

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

        GoogleWeatherHandler gwh = new GoogleWeatherHandler();
        xr.setContentHandler(gwh);
        xr.parse(new InputSource(url.openStream()));
        WeatherSet ws = gwh.getWeatherSet();
        WeatherCurrentCondition wcc = ws.getWeatherCurrentCondition();

        ArrayList<WeatherForecastCondition> conditions = ws.getWeatherForecastConditions();

        int days = conditions.size();
        WeatherData.forecast = new Forecast[days];

        for (int i = 0; i < days; ++i) {
            WeatherForecastCondition wfc = conditions.get(i);

            WeatherData.forecast[i] = m.new Forecast();
            WeatherData.forecast[i].day = null;

            WeatherData.forecast[i].icon = getIconGoogleWeather(wfc.getCondition());
            WeatherData.forecast[i].day = wfc.getDayofWeek();

            if (Preferences.weatherCelsius) {
                WeatherData.forecast[i].tempHigh = wfc.getTempMaxCelsius().toString();
                WeatherData.forecast[i].tempLow = wfc.getTempMinCelsius().toString();
            } else {
                WeatherData.forecast[i].tempHigh = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMaxCelsius()));
                WeatherData.forecast[i].tempLow = Integer
                        .toString(WeatherUtils.celsiusToFahrenheit(wfc.getTempMinCelsius()));
            }
        }

        WeatherData.celsius = Preferences.weatherCelsius;

        String cond = wcc.getCondition();
        WeatherData.condition = cond;

        if (Preferences.weatherCelsius) {
            WeatherData.temp = Integer.toString(wcc.getTempCelcius());
        } else {
            WeatherData.temp = Integer.toString(wcc.getTempFahrenheit());
        }

        cond = cond.toLowerCase();

        WeatherData.icon = getIconGoogleWeather(cond);
        WeatherData.received = true;
        WeatherData.timeStamp = System.currentTimeMillis();

        Idle.updateIdle(context, true);
        MetaWatchService.notifyClients();

    } catch (Exception e) {
        if (Preferences.logging)
            Log.e(MetaWatch.TAG, "Exception while retreiving weather", e);
    } finally {
        if (Preferences.logging)
            Log.d(MetaWatch.TAG, "Monitors.updateWeatherData(): finish");
    }

}

From source file:org.sansdemeure.zenindex.indexer.odt.TestHTMLConverter.java

@Test
public void test() throws ParserConfigurationException, SAXException, IOException {
    TestAppender testAppender = new TestAppender();
    File testDir = FileUtil.prepareEmptyDirectory(TestHTMLConverter.class);
    FileUtil.copyFromResources("docs/1992/Sandokai_with_2comments.odt", testDir, "Sandokai.odt");
    File odt = new File(testDir, "Sandokai.odt");
    try (ODTResource odtRessource = new ODTResource(odt)) {
        InputStream in = odtRessource.openContentXML();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        OdtHTMLConverterHandler htmlConverter = new OdtHTMLConverterHandler();
        saxParser.parse(in, htmlConverter);
        testAppender.verify("paragraphs were created");
        testAppender.verify("spans were created");
        testAppender.verify("2 annotations were created");
        testAppender.verify("All paragraphs were closed");
        testAppender.verify("All spans were closed");
    }// w w w  .  ja  v  a 2 s  . c o  m

}

From source file:org.sansdemeure.zenindex.indexer.odt.TestHTMLConverter2.java

@Test
public void test() throws ParserConfigurationException, SAXException, IOException {
    TestAppender testAppender = new TestAppender();
    File testDir = FileUtil.prepareEmptyDirectory(TestHTMLConverter2.class);
    FileUtil.copyFromResources("docs/2016/2016_05_17_DZP.odt", testDir, "2016_05_17_DZP.odt");
    File odt = new File(testDir, "2016_05_17_DZP.odt");
    try (ODTResource odtRessource = new ODTResource(odt)) {
        InputStream in = odtRessource.openContentXML();
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser saxParser = factory.newSAXParser();
        WriterForTest wt = new WriterForTest();
        OdtHTMLConverterHandler htmlConverter = new OdtHTMLConverterHandler();
        saxParser.parse(in, htmlConverter);
        Map<String, Object> model = htmlConverter.getModel();
        String content = (String) model.get("content");
        Assert.assertTrue(content.contains("Il y a beaucoup de"));
        Assert.assertTrue(content.contains("Les dents se touchent"));
    }/* w  ww .  j  a  v  a  2s.  c o m*/

}

From source file:com.tupilabs.pbs.parser.NodeXmlParser.java

@Override
public List<Node> parse(String xml) throws ParseException {
    try {/* w  w  w. j a v  a  2 s . co  m*/
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final SAXParser saxParser = factory.newSAXParser();
        final NodeXmlHandler handler = new NodeXmlHandler();

        saxParser.parse(new CharSequenceInputStream(xml, Charset.defaultCharset()), handler);

        return handler.getNodes();
    } catch (IOException ioe) {
        throw new ParseException(ioe);
    } catch (SAXException e) {
        throw new ParseException(e);
    } catch (ParserConfigurationException e) {
        throw new ParseException(e);
    }
}

From source file:com.vionto.vithesaurus.wikipedia.WiktionarySynonymDumper.java

private void run(InputStream is) throws IOException, SAXException, ParserConfigurationException {
    WiktionaryPageHandler handler = new WiktionaryPageHandler();
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser = factory.newSAXParser();
    saxParser.getXMLReader().setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd",
            false);//from  w ww.  ja v a  2  s  .  c om
    System.out.println("SET NAMES utf8;");
    System.out.println("DROP TABLE IF EXISTS wiktionary;");
    System.out.println("CREATE TABLE `wiktionary` ( " + "`headword` varchar(255) NOT NULL default '', "
            + "`meanings` text, " + "`synonyms` text, " + "KEY `headword` (`headword`)" + ") ENGINE = MYISAM;");
    saxParser.parse(is, handler);
    System.err.println("Exported: " + handler.exported);
    System.err.println("Skipped: " + handler.skipped);
}

From source file:de.doering.dwca.iocwbn.ChecklistBuilder.java

private void parsePage(Eml eml) throws IOException, SAXException, ParserConfigurationException {
    // get webapge
    String url = XML_DOWNLOAD.replace("{VERSION}", VERSION);
    log.info("Downloading latest IOC world bird list from {}", url);

    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);

    // execute//w  ww. j a v  a2s  .c  o  m
    HttpResponse response = client.execute(get);
    HttpEntity entity = response.getEntity();
    // parse page
    SAXParserFactory factory = SAXParserFactory.newInstance();

    final SAXParser parser = factory.newSAXParser();
    IocXmlHandler handler = new IocXmlHandler(writer, eml);
    try {
        Reader reader = new InputStreamReader(entity.getContent(), ENCODING);
        parser.parse(new InputSource(reader), handler);
    } catch (Exception e) {
        log.error("Cannot process IOC XML", e);
    }
}