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:org.openhab.binding.sonos.internal.SonosXMLParser.java

public static List<String> getRadioTimeFromXML(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    OpmlHandler handler = new OpmlHandler();
    reader.setContentHandler(handler);/*from   ww w .j a v a 2 s. c  o  m*/
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        logger.error("Could not parse RadioTime from String {}", xml);
    }

    return handler.getTextFields();

}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

public static Map<String, StateVariableValue> getRenderingControlFromXML(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    RenderingControlEventHandler handler = new RenderingControlEventHandler();
    reader.setContentHandler(handler);//from   w  w w  .  ja v  a2  s  .  c  o m
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        logger.debug("Could not parse Rendering Control event: {}", e);
    }
    return handler.getChanges();
}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

public static Map<String, StateVariableValue> getAVTransportFromXML(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    AVTransportEventHandler handler = new AVTransportEventHandler();
    reader.setContentHandler(handler);//from w  ww  .j a  v  a2s  .c  o m
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        logger.error("Could not parse AV Transport Event: {}", e);
    }
    return handler.getChanges();
}

From source file:org.openhab.binding.sonos.internal.SonosXMLParser.java

public static SonosMetaData getMetaDataFromXML(String xml) throws SAXException {
    XMLReader reader = XMLReaderFactory.createXMLReader();
    //logger.debug("getTrackFromXML {}",xml);
    MetaDataHandler handler = new MetaDataHandler();
    reader.setContentHandler(handler);/*w  ww.j  av a  2  s .  c  o m*/
    try {
        reader.parse(new InputSource(new StringReader(xml)));
    } catch (IOException e) {
        // This should never happen - we're not performing I/O!
        logger.error("Could not parse AV Transport Event: {}", e);
    }
    return handler.getMetaData();
}

From source file:org.openrdf.rio.rdfxml.RDFXMLParser.java

private void parse(InputSource inputSource) throws IOException, RDFParseException, RDFHandlerException {
    try {/*from www .ja va 2  s .  c  o  m*/
        documentURI = inputSource.getSystemId();

        saxFilter.setParseStandAloneDocuments(
                getParserConfig().get(XMLParserSettings.PARSE_STANDALONE_DOCUMENTS));

        // saxFilter.clear();
        saxFilter.setDocumentURI(documentURI);

        XMLReader xmlReader;

        if (getParserConfig().isSet(XMLParserSettings.CUSTOM_XML_READER)) {
            xmlReader = getParserConfig().get(XMLParserSettings.CUSTOM_XML_READER);
        } else {
            xmlReader = XMLReaderFactory.createXMLReader();
        }

        xmlReader.setContentHandler(saxFilter);
        xmlReader.setErrorHandler(this);

        // Set all compulsory feature settings, using the defaults if they are
        // not explicitly set
        for (RioSetting<Boolean> aSetting : getCompulsoryXmlFeatureSettings()) {
            try {
                xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting));
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey()));
            }
        }

        // Set all compulsory property settings, using the defaults if they are
        // not explicitly set
        for (RioSetting<?> aSetting : getCompulsoryXmlPropertySettings()) {
            try {
                xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting));
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey()));
            }
        }

        // Check for any optional feature settings that are explicitly set in
        // the parser config
        for (RioSetting<Boolean> aSetting : getOptionalXmlFeatureSettings()) {
            try {
                if (getParserConfig().isSet(aSetting)) {
                    xmlReader.setFeature(aSetting.getKey(), getParserConfig().get(aSetting));
                }
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX feature.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX feature.", aSetting.getKey()));
            }
        }

        // Check for any optional property settings that are explicitly set in
        // the parser config
        for (RioSetting<?> aSetting : getOptionalXmlPropertySettings()) {
            try {
                if (getParserConfig().isSet(aSetting)) {
                    xmlReader.setProperty(aSetting.getKey(), getParserConfig().get(aSetting));
                }
            } catch (SAXNotRecognizedException e) {
                reportWarning(String.format("%s is not a recognized SAX property.", aSetting.getKey()));
            } catch (SAXNotSupportedException e) {
                reportWarning(String.format("%s is not a supported SAX property.", aSetting.getKey()));
            }
        }

        xmlReader.parse(inputSource);
    } catch (SAXParseException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e, e.getLineNumber(), e.getColumnNumber());
        } else {
            reportFatalError(wrappedExc, e.getLineNumber(), e.getColumnNumber());
        }
    } catch (SAXException e) {
        Exception wrappedExc = e.getException();

        if (wrappedExc == null) {
            reportFatalError(e);
        } else if (wrappedExc instanceof RDFParseException) {
            throw (RDFParseException) wrappedExc;
        } else if (wrappedExc instanceof RDFHandlerException) {
            throw (RDFHandlerException) wrappedExc;
        } else {
            reportFatalError(wrappedExc);
        }
    } finally {
        // Clean up
        saxFilter.clear();
        xmlLang = null;
        elementStack.clear();
        usedIDs.clear();
        clear();
    }
}

From source file:org.openstreetmap.josm.tools.ImageProvider.java

/**
 * Reads the wiki page on a certain file in html format in order to find the real image URL.
 *///  ww w . j a v  a  2s . c  om
private static String getImgUrlFromWikiInfoPage(final String base, final String fn) {

    /** Quit parsing, when a certain condition is met */
    class SAXReturnException extends SAXException {
        private String result;

        public SAXReturnException(String result) {
            this.result = result;
        }

        public String getResult() {
            return result;
        }
    }

    try {
        final XMLReader parser = XMLReaderFactory.createXMLReader();
        parser.setContentHandler(new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes atts)
                    throws SAXException {
                System.out.println();
                if (localName.equalsIgnoreCase("img")) {
                    String val = atts.getValue("src");
                    if (val.endsWith(fn))
                        throw new SAXReturnException(val); // parsing done, quit early
                }
            }
        });

        parser.setEntityResolver(new EntityResolver() {
            public InputSource resolveEntity(String publicId, String systemId) {
                return new InputSource(new ByteArrayInputStream(new byte[0]));
            }
        });

        parser.parse(new InputSource(new MirroredInputStream(base + fn,
                new File(Main.pref.getPreferencesDir(), "images").toString())));
    } catch (SAXReturnException r) {
        return r.getResult();
    } catch (Exception e) {
        System.out.println("INFO: parsing " + base + fn + " failed:\n" + e);
        return null;
    }
    System.out.println("INFO: parsing " + base + fn + " failed: Unexpected content.");
    return null;
}

From source file:org.orbeon.oxf.processor.converter.ToXMLConverter.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new CacheableTransformerOutputImpl(ToXMLConverter.this, name) {
        public void readImpl(PipelineContext pipelineContext, XMLReceiver xmlReceiver) {

            // Read config input
            final XMLParsing.ParserConfiguration config = readCacheInputAsObject(pipelineContext,
                    getInputByName(INPUT_CONFIG), new CacheableInputReader<XMLParsing.ParserConfiguration>() {
                        public XMLParsing.ParserConfiguration read(
                                org.orbeon.oxf.pipeline.api.PipelineContext context, ProcessorInput input) {

                            final Element configElement = readInputAsDOM4J(context, input).getRootElement();

                            return new XMLParsing.ParserConfiguration(
                                    ProcessorUtils.selectBooleanValue(configElement, "/config/validating",
                                            URLGenerator.DEFAULT_VALIDATING),
                                    ProcessorUtils.selectBooleanValue(configElement, "/config/handle-xinclude",
                                            URLGenerator.DEFAULT_HANDLE_XINCLUDE),
                                    ProcessorUtils.selectBooleanValue(configElement,
                                            "/config/external-entities",
                                            URLGenerator.DEFAULT_EXTERNAL_ENTITIES));
                        }//from   w  w  w  .j a va2  s  .com
                    });

            try {
                // Get FileItem
                final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);

                // TODO: Can we avoid writing to a FileItem?

                // Read to OutputStream
                readInputAsSAX(pipelineContext, INPUT_DATA,
                        new BinaryTextXMLReceiver(fileItem.getOutputStream()));

                // Create parser
                final XMLReader reader = XMLParsing.newXMLReader(config);

                // Run parser on InputStream
                //inputSource.setSystemId();
                reader.setContentHandler(xmlReceiver);
                reader.parse(new InputSource(fileItem.getInputStream()));

            } catch (Exception e) {
                throw new OXFException(e);
            }
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.xforms.XFormsUtils.java

private static void htmlStringToResult(String value, LocationData locationData, Result result) {
    try {/*  w  w w .  j  a v  a2 s.co m*/
        final XMLReader xmlReader = new org.ccil.cowan.tagsoup.Parser();
        xmlReader.setProperty(org.ccil.cowan.tagsoup.Parser.schemaProperty, TAGSOUP_HTML_SCHEMA);
        xmlReader.setFeature(org.ccil.cowan.tagsoup.Parser.ignoreBogonsFeature, true);
        final TransformerHandler identity = TransformerUtils.getIdentityTransformerHandler();
        identity.setResult(result);
        xmlReader.setContentHandler(identity);
        final InputSource inputSource = new InputSource();
        inputSource.setCharacterStream(new StringReader(value));
        xmlReader.parse(inputSource);
    } catch (Exception e) {
        throw new ValidationException("Cannot parse value as text/html for value: '" + value + "'",
                locationData);
    }
    //         r.setFeature(Parser.CDATAElementsFeature, false);
    //         r.setFeature(Parser.namespacesFeature, false);
    //         r.setFeature(Parser.ignoreBogonsFeature, true);
    //         r.setFeature(Parser.bogonsEmptyFeature, false);
    //         r.setFeature(Parser.defaultAttributesFeature, false);
    //         r.setFeature(Parser.translateColonsFeature, true);
    //         r.setFeature(Parser.restartElementsFeature, false);
    //         r.setFeature(Parser.ignorableWhitespaceFeature, true);
    //         r.setProperty(Parser.scannerProperty, new PYXScanner());
    //          r.setProperty(Parser.lexicalHandlerProperty, h);
}

From source file:org.owasp.dependencycheck.xml.pom.PomParser.java

/**
 * Parses the given XML file and returns a Model object containing only the
 * fields dependency-check requires.// w ww.  j  a  v a 2  s .  c o  m
 *
 * @param inputStream an InputStream containing suppression rues
 * @return a list of suppression rules
 * @throws PomParseException if the XML cannot be parsed
 */
public Model parse(InputStream inputStream) throws PomParseException {
    try {
        final PomHandler handler = new PomHandler();
        final SAXParser saxParser = XmlUtils.buildSecureSaxParser();
        final XMLReader xmlReader = saxParser.getXMLReader();
        xmlReader.setContentHandler(handler);

        final BOMInputStream bomStream = new BOMInputStream(new XmlInputStream(inputStream));
        final ByteOrderMark bom = bomStream.getBOM();
        final String defaultEncoding = "UTF-8";
        final String charsetName = bom == null ? defaultEncoding : bom.getCharsetName();
        final Reader reader = new InputStreamReader(bomStream, charsetName);
        final InputSource in = new InputSource(reader);
        xmlReader.parse(in);
        return handler.getModel();
    } catch (ParserConfigurationException | SAXException | FileNotFoundException ex) {
        LOGGER.debug("", ex);
        throw new PomParseException(ex);
    } catch (IOException ex) {
        LOGGER.debug("", ex);
        throw new PomParseException(ex);
    }
}

From source file:org.pencilsofpromise.rss.RSSFragment.java

public RSSFeed getFeed(String urlToRssFeed) {
    try {/* w  ww.j  av a 2  s.  c  o m*/
        // setup the url
        URL url = new URL(urlToRssFeed);

        // create the factory
        SAXParserFactory factory = SAXParserFactory.newInstance();
        // create a parser
        SAXParser parser = factory.newSAXParser();

        // create the reader (scanner)
        XMLReader xmlreader = parser.getXMLReader();
        // instantiate our handler
        RSSHandler theRssHandler = new RSSHandler(getActivity().getApplicationContext());
        // assign our handler
        xmlreader.setContentHandler(theRssHandler);
        // get our data via the url class
        InputSource is = new InputSource(url.openStream());
        // perform the synchronous parse           
        xmlreader.parse(is);
        // get the results - should be a fully populated RSSFeed instance, or null on error
        return theRssHandler.getFeed();
    } catch (Exception ee) {
        // if we have a problem, simply return null
        return null;
    }
}