Example usage for org.xml.sax XMLReader setContentHandler

List of usage examples for org.xml.sax XMLReader setContentHandler

Introduction

In this page you can find the example usage for org.xml.sax XMLReader setContentHandler.

Prototype

public void setContentHandler(ContentHandler handler);

Source Link

Document

Allow an application to register a content event handler.

Usage

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);
    try {//from   w w  w  .j av  a2 s.  c  o  m
        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   w  w  w .  jav  a  2s  .  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.
 *///from  w  w w  .ja va  2  s  .  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  v  a  2  s  .co m
                    });

            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 {//from  w  ww. j ava2  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./*  www  .j av  a2  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 {// ww  w .j  a  va  2  s. co  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;
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.cda.CdaResponseParser.java

public static TypedTableModel performParse(final InputStream postResult)
        throws IOException, ReportDataFactoryException {
    try {//from   w  w  w .j ava 2  s. c  o m
        final CdaResponseParser contentHandler = new CdaResponseParser();
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final SAXParser parser = factory.newSAXParser();
        final XMLReader reader = parser.getXMLReader();

        try {
            reader.setFeature("http://xml.org/sax/features/xmlns-uris", false);
        } catch (SAXException e) {
            // ignored
        }
        try {
            reader.setFeature("http://xml.org/sax/features/namespaces", false);
            reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        } catch (final SAXException e) {
            logger.warn("No Namespace features will be available. (Yes, this is serious)", e);
        }

        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(postResult));

        return (contentHandler.getResult());
    } catch (final ParserConfigurationException e) {
        throw new ReportDataFactoryException("Failed to init XML system", e);
    } catch (final SAXException e) {
        throw new ReportDataFactoryException("Failed to parse document", e);
    }
}

From source file:org.pentaho.reporting.libraries.pensol.vfs.XmlSolutionFileModel.java

protected FileInfo performParse(final InputStream postResult) throws IOException {
    ArgumentNullException.validate("postResult", postResult);

    try {/*ww  w. java2s  .  c  om*/
        final FileInfoParser contentHandler = new FileInfoParser();
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final SAXParser parser = factory.newSAXParser();
        final XMLReader reader = parser.getXMLReader();

        try {
            reader.setFeature("http://xml.org/sax/features/xmlns-uris", false);
        } catch (SAXException e) {
            // ignored
        }
        try {
            reader.setFeature("http://xml.org/sax/features/namespaces", false);
            reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        } catch (final SAXException e) {
            logger.warn("No Namespace features will be available. (Yes, this is serious)", e);
        }

        reader.setContentHandler(contentHandler);
        reader.parse(new InputSource(postResult));

        majorVersion = contentHandler.getMajorVersion();
        minorVersion = contentHandler.getMinorVersion();
        releaseVersion = contentHandler.getReleaseVersion();
        buildVersion = contentHandler.getBuildVersion();
        milestoneVersion = contentHandler.getMilestoneVersion();

        return (contentHandler.getRoot());
    } catch (final ParserConfigurationException e) {
        throw new FileSystemException("Failed to init XML system", e);
    } catch (final SAXException e) {
        throw new FileSystemException("Failed to parse document", e);
    }
}

From source file:org.pentaho.reporting.libraries.xmlns.parser.AbstractXmlResourceFactory.java

/**
 * Creates a resource by interpreting the data given in the resource-data object. If additional datastreams need to be
 * parsed, the provided resource manager should be used. This method parses the given resource-data as XML stream.
 *
 * @param manager the resource manager used for all resource loading.
 * @param data    the resource-data from where the binary data is read.
 * @param context the resource context used to resolve relative resource paths.
 * @return the parsed result, never null.
 * @throws ResourceCreationException if the resource could not be parsed due to syntaxctial or logical errors in the
 *                                   data.
 * @throws ResourceLoadingException  if the resource could not be accessed from the physical storage.
 *///  w  w  w  .j  a v  a  2s  .c  o  m
public Resource create(final ResourceManager manager, final ResourceData data, final ResourceKey context)
        throws ResourceCreationException, ResourceLoadingException {
    try {
        final SAXParser parser = getParser();

        final XMLReader reader = parser.getXMLReader();
        final XmlFactoryModule[] rootHandlers = getModules();
        if (rootHandlers.length == 0) {
            throw new ResourceCreationException(
                    "There are no root-handlers registered for the factory for type " + getFactoryType());
        }

        final ResourceDataInputSource input = new ResourceDataInputSource(data, manager);

        final ResourceKey contextKey;
        final long version;
        final ResourceKey targetKey = data.getKey();
        if (context == null) {
            contextKey = targetKey;
            version = data.getVersion(manager);
        } else {
            contextKey = context;
            version = -1;
        }

        final RootXmlReadHandler handler = createRootHandler(manager, targetKey, rootHandlers, contextKey,
                version);

        final DefaultConfiguration parserConfiguration = handler.getParserConfiguration();
        final URL value = manager.toURL(contextKey);
        if (value != null) {
            parserConfiguration.setConfigProperty(CONTENTBASE_KEY, value.toExternalForm());
        }

        configureReader(reader, handler);
        reader.setContentHandler(handler);
        reader.setDTDHandler(handler);
        reader.setEntityResolver(handler.getEntityResolver());
        reader.setErrorHandler(getErrorHandler());

        final Map parameters = targetKey.getFactoryParameters();
        final Iterator it = parameters.keySet().iterator();
        while (it.hasNext()) {
            final Object o = it.next();
            if (o instanceof FactoryParameterKey) {
                final FactoryParameterKey fpk = (FactoryParameterKey) o;
                handler.setHelperObject(fpk.getName(), parameters.get(fpk));
            }
        }

        reader.parse(input);

        final Object createdProduct = finishResult(handler.getResult(), manager, data, contextKey);
        handler.getDependencyCollector().add(targetKey, data.getVersion(manager));
        return createResource(targetKey, handler, createdProduct, getFactoryType());
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document: " + data.getKey(), e);
    } catch (IOException e) {
        throw new ResourceLoadingException("Unable to read the stream from document: " + data.getKey(), e);
    }
}