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:org.pencilsofpromise.rss.RSSFragment.java

public RSSFeed getFeed(String urlToRssFeed) {
    try {//from  ww w.j  av a 2s. 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;
    }
}

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 ww  w .  ja  va 2 s  . c om
        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 {//w ww. j  a  v  a  2 s .co  m
        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.
 *//*from   w  w  w .j ava2 s  . 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);
    }
}

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

/**
 * A method to allow to invoke the parsing without accessing the LibLoader layer. The data to be parsed is held in the
 * given InputSource object./*from   w w  w. jav  a2  s.c  om*/
 *
 * @param manager    the resource manager used for all resource loading.
 * @param input      the raw-data given as SAX-InputSource.
 * @param context    the resource context used to resolve relative resource paths.
 * @param parameters the parse parameters.
 * @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.
 * @throws ResourceKeyCreationException if creating the context key failed.
 */
public Object parseDirectly(final ResourceManager manager, final InputSource input, final ResourceKey context,
        final Map parameters)
        throws ResourceKeyCreationException, ResourceCreationException, ResourceLoadingException {
    try {
        final SAXParser parser = getParser();

        final XMLReader reader = parser.getXMLReader();

        final ResourceKey targetKey = manager.createKey(EMPTY_DATA);
        final ResourceKey contextKey;
        if (context == null) {
            contextKey = targetKey;
        } else {
            contextKey = context;
        }

        final XmlFactoryModule[] rootHandlers = getModules();
        final RootXmlReadHandler handler = createRootHandler(manager, targetKey, rootHandlers, contextKey, -1);

        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 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);

        return finishResult(handler.getResult(), manager, new RawResourceData(targetKey), contextKey);
    } catch (ParserConfigurationException e) {
        throw new ResourceCreationException("Unable to initialize the XML-Parser", e);
    } catch (SAXException e) {
        throw new ResourceCreationException("Unable to parse the document", e);
    } catch (IOException e) {
        throw new ResourceLoadingException("Unable to read the stream", e);
    }

}

From source file:org.plasma.sdo.helper.PlasmaXMLHelper.java

private void validateSAX(InputStream inputStream, String locationURI, XMLOptions options) throws IOException {

    SAXParserFactory factory = SAXParserFactory.newInstance();
    factory.setValidating(true);//from ww w.  j  a v a  2s .c o m
    factory.setNamespaceAware(true);
    SAXParser parser;

    try {
        factory.setFeature("http://xml.org/sax/features/validation", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema", true);
        factory.setFeature("http://apache.org/xml/features/validation/schema-full-checking", true);
        parser = factory.newSAXParser();
        try {
            parser.setProperty(XMLConstants.JAXP_SCHEMA_LANGUAGE, SchemaConstants.XMLSCHEMA_NAMESPACE_URI);
        } catch (SAXNotRecognizedException e) {
            log.warn("parses does not support JAXP 1.2");
        }
        if (locationURI != null) {
            parser.setProperty(XMLConstants.JAXP_NO_NAMESPACE_SCHEMA_SOURCE, locationURI);
        }
        XMLReader xmlReader = parser.getXMLReader();
        //xmlReader.setEntityResolver(new SchemaLoader());
        if (options.getErrorHandler() == null)
            xmlReader.setErrorHandler(new DefaultErrorHandler(options));
        else
            xmlReader.setErrorHandler(options.getErrorHandler());
        if (log.isDebugEnabled())
            log.debug("validating...");
        xmlReader.parse(new InputSource(inputStream));

    } catch (SAXNotRecognizedException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXNotSupportedException e) {
        throw new PlasmaDataObjectException(e);
    } catch (ParserConfigurationException e) {
        throw new PlasmaDataObjectException(e);
    } catch (SAXException e) {
        throw new PlasmaDataObjectException(e);
    }
}

From source file:org.radeox.filter.XHTMLFilter.java

public String filter(String input, FilterContext context) {
    String finalOutput = input;//w  ww  .  j  ava2  s  .c  om
    try {
        DeblockFilter dbf = new DeblockFilter();
        EmptyFilter epf = new EmptyFilter();

        dbf.setBlockElements(blockElements);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        SpecialXHTMLSerializer xser = new SpecialXHTMLSerializer();
        xser.setOutputStream(baos);
        xser.setIndent(false);
        xser.setEncoding("UTF-8");
        xser.setIndentAmount(4);
        dbf.setContentHandler(epf);
        epf.setContentHander(xser.asContentHandler());

        SAXParser parser = saxParserFactory.newSAXParser();

        XMLReader xmlr = parser.getXMLReader();

        xmlr.setContentHandler(dbf);
        // log.warn("Input is "+input);
        xmlr.parse(new InputSource(new StringReader("<sr>" + input + "</sr>")));

        String output = new String(baos.toByteArray(), "UTF-8");
        int startBlock = output.indexOf("<sr>");
        int endBlock = output.indexOf("</sr>");
        finalOutput = output.substring(startBlock + 4, endBlock);
        // log.warn("Output is "+finalOutput);
    } catch (Throwable t) {
        log.error("Failed to XHTML check " + t.getMessage() + "\n Input======\n" + input + "\n=======");
        return input;
    }

    return finalOutput;
}

From source file:org.rhq.plugins.diameter.jbossas5.util.JnpConfig.java

private void parseServiceXML(File distributionDirectory, File serviceXmlFile)
        throws IOException, SAXException, ParserConfigurationException {
    FileInputStream is = null;//from w  ww . j a v  a2  s.c o  m
    try {
        is = new FileInputStream(serviceXmlFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        EntityResolver r = new LocalEntityResolver(distributionDirectory);

        JBossServiceHandler handler = new JBossServiceHandler(serviceXmlFile);

        XMLReader reader = parser.getXMLReader();

        reader.setEntityResolver(r);

        reader.setContentHandler(handler);

        reader.parse(new InputSource(is));

        this.jnpAddress = handler.getNamingBindAddress();
        this.jnpPort = handler.getNamingPort();
        this.storeFile = handler.getStoreFile();
        this.serverName = handler.getServerName();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}

From source file:org.rhq.plugins.diameter.jbossas5.util.JnpConfig.java

private void parseBindingManagerXML() throws IOException {
    InputStream bindIs = null;//from  www .ja  v a 2 s.  c o m
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        if (!this.storeFile.isFile()) {
            log.warn("Store file does not exist: " + this.storeFile);
            return;
        }

        JBossBindingManagerHandler bindingHandler = new JBossBindingManagerHandler(this.storeFile);
        bindingHandler.setServerName(this.serverName);
        XMLReader reader = parser.getXMLReader();
        bindIs = new FileInputStream(this.storeFile);
        reader.setContentHandler(bindingHandler);
        reader.parse(new InputSource(bindIs));
        this.jnpAddress = bindingHandler.getJnpAddress();
        this.jnpPort = bindingHandler.getJnpPort();
    } catch (Exception e) {
        throw new IllegalArgumentException(e.getMessage());
    } finally {
        if (bindIs != null) {
            bindIs.close();
        }
    }
}

From source file:org.rhq.plugins.jbossas.util.JnpConfig.java

private void parseServiceXML(File serviceXmlFile)
        throws IOException, SAXException, ParserConfigurationException {
    FileInputStream is = null;//from w w w  . j  a va  2s  . c o  m
    try {
        is = new FileInputStream(serviceXmlFile);
        SAXParserFactory factory = SAXParserFactory.newInstance();
        SAXParser parser = factory.newSAXParser();

        XMLReader reader = parser.getXMLReader();

        EntityResolver entityResolver = SelectiveSkippingEntityResolver.getDtdAndXsdSkippingInstance();
        reader.setEntityResolver(entityResolver);

        JBossServiceHandler contentHandler = new JBossServiceHandler(serviceXmlFile);
        reader.setContentHandler(contentHandler);

        reader.parse(new InputSource(is));

        this.jnpAddress = contentHandler.getNamingBindAddress();
        this.jnpPort = contentHandler.getNamingPort();
        this.storeFile = contentHandler.getStoreFile();
        this.serverName = contentHandler.getServerName();
    } finally {
        if (is != null) {
            is.close();
        }
    }
}