Example usage for org.xml.sax XMLReader setEntityResolver

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

Introduction

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

Prototype

public void setEntityResolver(EntityResolver resolver);

Source Link

Document

Allow an application to register an entity resolver.

Usage

From source file:nl.nn.adapterframework.util.XmlUtils.java

public static SAXSource stringToSAXSource(String xmlString, boolean namespaceAware,
        boolean resolveExternalEntities) throws DomBuilderException {
    Variant in = new Variant(xmlString);
    InputSource is = in.asXmlInputSource();
    SAXParserFactory factory = getSAXParserFactory(namespaceAware);
    try {/*w w  w  .  j  av a  2s . com*/
        XMLReader xmlReader = factory.newSAXParser().getXMLReader();
        if (!resolveExternalEntities) {
            xmlReader.setEntityResolver(new XmlExternalEntityResolver());
        }
        return new SAXSource(xmlReader, is);
    } catch (Exception e) {
        // TODO Use DomBuilderException as the stringToSource and calling
        // methods use them a lot. Rename DomBuilderException to
        // SourceBuilderException?
        throw new DomBuilderException(e);
    }
}

From source file:org.ambraproject.wombat.service.ArticleTransformServiceImpl.java

private void transform(Site site, InputStream xml, OutputStream html, TransformerInitializer initialization)
        throws IOException {
    Objects.requireNonNull(site);
    Objects.requireNonNull(xml);/* w ww  . j a va 2s  .c om*/
    Objects.requireNonNull(html);

    log.debug("Starting XML transformation");
    SAXParserFactory spf = SAXParserFactory.newInstance();
    XMLReader xmlr;
    try {
        SAXParser sp = spf.newSAXParser();
        xmlr = sp.getXMLReader();
    } catch (ParserConfigurationException | SAXException e) {
        throw new RuntimeException(e);
    }

    /*
     * This is a little unorthodox.  Without setting this custom EntityResolver, the transform will
     * make ~50 HTTP calls to nlm.nih.gov to retrieve the DTD and various entity files referenced
     * in the article XML. By setting a custom EntityResolver that just returns an empty string
     * for each of these, we prevent that.  This seems to have no ill effects on the transformation
     * itself.  This is a roundabout way of turning off DTD validation, which is more
     * straightforward to do with a Document/DocumentBuilder, but the saxon library we're using
     * is much faster at XSLT if it uses its own XML parser instead of DocumentBuilder.  See
     * http://stackoverflow.com/questions/155101/make-documentbuilder-parse-ignore-dtd-references
     * for a discussion.
     */
    xmlr.setEntityResolver((String publicId, String systemId) -> {
        // Note: returning null here will cause the HTTP request to be made.

        if (VALID_DTDS.contains(systemId)) {
            return new InputSource(new StringReader(""));
        } else {
            throw new IllegalArgumentException("Unexpected entity encountered: " + systemId);
        }
    });
    // build the transformer and add any context-dependent parameters required for the transform
    // NOTE: the XMLReader is passed here for use in creating any required secondary SAX sources
    Transformer transformer = buildTransformer(site, xmlr, initialization);
    SAXSource saxSource = new SAXSource(xmlr, new InputSource(xml));
    try {
        transformer.transform(saxSource, new StreamResult(html));
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    }

    log.debug("Finished XML transformation");
}

From source file:org.apache.axis.utils.XMLUtils.java

/** Get a SAX parser instance from the JAXP factory.
 *
 * @return a SAXParser instance.// w  w  w.  j ava  2s .  com
 */
public static synchronized SAXParser getSAXParser() {
    if (enableParserReuse && !saxParsers.empty()) {
        return (SAXParser) saxParsers.pop();
    }

    try {
        SAXParser parser = saxFactory.newSAXParser();
        XMLReader reader = parser.getXMLReader();
        // parser.getParser().setEntityResolver(new DefaultEntityResolver());
        // The above commented line and the following line are added
        // for preventing XXE (bug #14105).
        // We may need to uncomment the deprecated setting
        // in case that it is considered necessary.
        try {
            reader.setEntityResolver(new DefaultEntityResolver());
        } catch (Throwable t) {
            log.debug("Failed to set EntityResolver on DocumentBuilder", t);
        }
        reader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        return parser;
    } catch (ParserConfigurationException e) {
        log.error(Messages.getMessage("parserConfigurationException00"), e);
        return null;
    } catch (SAXException se) {
        log.error(Messages.getMessage("SAXException00"), se);
        return null;
    }
}

From source file:org.apache.axis.utils.XMLUtils.java

/** Return a SAX parser for reuse.
 * @param parser A SAX parser that is available for reuse
 *///from   w  w  w .java 2  s  . c om
public static void releaseSAXParser(SAXParser parser) {
    if (!tryReset || !enableParserReuse)
        return;

    //Free up possible ref. held by past contenthandler.
    try {
        XMLReader xmlReader = parser.getXMLReader();
        if (null != xmlReader) {
            xmlReader.setContentHandler(doNothingContentHandler);
            xmlReader.setDTDHandler(doNothingContentHandler);
            try {
                xmlReader.setEntityResolver(doNothingContentHandler);
            } catch (Throwable t) {
                log.debug("Failed to set EntityResolver on DocumentBuilder", t);
            }
            try {
                xmlReader.setErrorHandler(doNothingContentHandler);
            } catch (Throwable t) {
                log.debug("Failed to set ErrorHandler on DocumentBuilder", t);
            }

            synchronized (XMLUtils.class) {
                saxParsers.push(parser);
            }
        } else {
            tryReset = false;
        }
    } catch (org.xml.sax.SAXException e) {
        tryReset = false;
    }
}

From source file:org.apache.fop.cli.InputHandler.java

/**
 * Creates a Source for the main input file. Processes XInclude if
 * available in the XML parser.//from   w  w  w. j  ava  2  s  .  co  m
 *
 * @return the Source for the main input file
 */
protected Source createMainSource() {
    Source source;
    InputStream in;
    String uri;
    if (this.sourcefile != null) {
        try {
            in = new java.io.FileInputStream(this.sourcefile);
            uri = this.sourcefile.toURI().toASCIIString();
        } catch (FileNotFoundException e) {
            //handled elsewhere
            return new StreamSource(this.sourcefile);
        }
    } else {
        in = System.in;
        uri = null;
    }
    try {
        InputSource is = new InputSource(in);
        is.setSystemId(uri);
        XMLReader xr = getXMLReader();
        if (entityResolver != null) {
            xr.setEntityResolver(entityResolver);
        }
        source = new SAXSource(xr, is);
    } catch (SAXException e) {
        if (this.sourcefile != null) {
            source = new StreamSource(this.sourcefile);
        } else {
            source = new StreamSource(in, uri);
        }
    } catch (ParserConfigurationException e) {
        if (this.sourcefile != null) {
            source = new StreamSource(this.sourcefile);
        } else {
            source = new StreamSource(in, uri);
        }
    }
    return source;
}

From source file:org.apache.fop.cli.InputHandler.java

/**
 * Creates a Source for the selected stylesheet.
 *
 * @return the Source for the selected stylesheet or null if there's no stylesheet
 *//* www .ja v a 2 s.  com*/
protected Source createXSLTSource() {
    Source xslt = null;
    if (this.stylesheet != null) {
        if (entityResolver != null) {
            try {
                InputSource is = new InputSource(this.stylesheet.getPath());
                XMLReader xr = getXMLReader();
                xr.setEntityResolver(entityResolver);
                xslt = new SAXSource(xr, is);
            } catch (SAXException e) {
                // return StreamSource
            } catch (ParserConfigurationException e) {
                // return StreamSource
            }
        }
        if (xslt == null) {
            xslt = new StreamSource(this.stylesheet);
        }
    }
    return xslt;
}

From source file:org.apache.fop.fotreetest.FOTreeTestCase.java

/**
 * Runs a test.//from  w  w w . j  a v  a  2 s  .  c  om
 * @throws Exception if a test or FOP itself fails
 */
@Test
public void runTest() throws Exception {
    try {
        ResultCollector collector = ResultCollector.getInstance();
        collector.reset();

        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        spf.setValidating(false);
        SAXParser parser = spf.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        // Resetting values modified by processing instructions
        fopFactory.setBreakIndentInheritanceOnReferenceAreaBoundary(
                FopFactoryConfigurator.DEFAULT_BREAK_INDENT_INHERITANCE);
        fopFactory.setSourceResolution(FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION);

        FOUserAgent ua = fopFactory.newFOUserAgent();
        ua.setBaseURL(testFile.getParentFile().toURI().toURL().toString());
        ua.setFOEventHandlerOverride(new DummyFOEventHandler(ua));
        ua.getEventBroadcaster().addEventListener(new ConsoleEventListenerForTests(testFile.getName()));

        // Used to set values in the user agent through processing instructions
        reader = new PIListener(reader, ua);

        Fop fop = fopFactory.newFop(ua);

        reader.setContentHandler(fop.getDefaultHandler());
        reader.setDTDHandler(fop.getDefaultHandler());
        reader.setErrorHandler(fop.getDefaultHandler());
        reader.setEntityResolver(fop.getDefaultHandler());
        try {
            reader.parse(testFile.toURI().toURL().toExternalForm());
        } catch (Exception e) {
            collector.notifyError(e.getLocalizedMessage());
            throw e;
        }

        List<String> results = collector.getResults();
        if (results.size() > 0) {
            for (int i = 0; i < results.size(); i++) {
                System.out.println((String) results.get(i));
            }
            throw new IllegalStateException((String) results.get(0));
        }
    } catch (Exception e) {
        org.apache.commons.logging.LogFactory.getLog(this.getClass()).info("Error on " + testFile.getName());
        throw e;
    }
}

From source file:org.apache.ode.bpel.compiler.bom.BpelObjectFactory.java

/**
 * Parse a BPEL process found at the input source.
 * @param isrc input source.//w w w.  j  av a2 s  . c  om
 * @return
 * @throws SAXException
 */
public Process parse(InputSource isrc, URI systemURI) throws IOException, SAXException {
    XMLReader _xr = XMLParserUtils.getXMLReader();
    LocalEntityResolver resolver = new LocalEntityResolver();
    resolver.register(Bpel11QNames.NS_BPEL4WS_2003_03, getClass().getResource("/bpel4ws_1_1-fivesight.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0, getClass().getResource("/wsbpel_main-draft-Apr-29-2006.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT,
            getClass().getResource("/ws-bpel_abstract_common_base.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC, getClass().getResource("/ws-bpel_executable.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_PLINK, getClass().getResource("/ws-bpel_plnktype.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_SERVREF,
            getClass().getResource("/ws-bpel_serviceref.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL2_0_FINAL_VARPROP, getClass().getResource("/ws-bpel_varprop.xsd"));
    resolver.register(XML, getClass().getResource("/xml.xsd"));
    resolver.register(WSDL, getClass().getResource("/wsdl.xsd"));
    resolver.register(Bpel20QNames.NS_WSBPEL_PARTNERLINK_2004_03,
            getClass().getResource("/wsbpel_plinkType-draft-Apr-29-2006.xsd"));
    _xr.setEntityResolver(resolver);
    Document doc = DOMUtils.newDocument();
    _xr.setContentHandler(new DOMBuilderContentHandler(doc));
    _xr.setFeature("http://xml.org/sax/features/namespaces", true);
    _xr.setFeature("http://xml.org/sax/features/namespace-prefixes", true);

    _xr.setFeature("http://xml.org/sax/features/validation", true);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel11QNames.NS_BPEL4WS_2003_03, Bpel11QNames.NS_BPEL4WS_2003_03);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0, Bpel20QNames.NS_WSBPEL2_0);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC,
            Bpel20QNames.NS_WSBPEL2_0_FINAL_EXEC);
    XMLParserUtils.addExternalSchemaURL(_xr, Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT,
            Bpel20QNames.NS_WSBPEL2_0_FINAL_ABSTRACT);

    boolean strict = Boolean
            .parseBoolean(System.getProperty("org.apache.ode.compiler.failOnValidationErrors", "false"));
    BOMSAXErrorHandler errorHandler = new BOMSAXErrorHandler(strict);
    _xr.setErrorHandler(errorHandler);
    _xr.parse(isrc);
    if (strict) {
        if (!errorHandler.wasOK()) {
            throw new SAXException("Validation errors during parsing");
        }
    } else {
        if (!errorHandler.wasOK()) {
            __log.warn(
                    "Validation errors during parsing, continuing due to -Dorg.apache.ode.compiler.failOnValidationErrors=false switch");
        }
    }
    return (Process) createBpelObject(doc.getDocumentElement(), systemURI);
}

From source file:org.apache.solr.handler.loader.XMLLoader.java

@Override
public void load(SolrQueryRequest req, SolrQueryResponse rsp, ContentStream stream,
        UpdateRequestProcessor processor) throws Exception {
    final String charset = ContentStreamBase.getCharsetFromContentType(stream.getContentType());

    InputStream is = null;/*from   w w w .ja  v a  2  s  .  c o m*/
    XMLStreamReader parser = null;

    String tr = req.getParams().get(CommonParams.TR, null);
    if (tr != null) {
        final Transformer t = getTransformer(tr, req);
        final DOMResult result = new DOMResult();

        // first step: read XML and build DOM using Transformer (this is no overhead, as XSL always produces
        // an internal result DOM tree, we just access it directly as input for StAX):
        try {
            is = stream.getStream();
            final InputSource isrc = new InputSource(is);
            isrc.setEncoding(charset);
            final XMLReader xmlr = saxFactory.newSAXParser().getXMLReader();
            xmlr.setErrorHandler(xmllog);
            xmlr.setEntityResolver(EmptyEntityResolver.SAX_INSTANCE);
            final SAXSource source = new SAXSource(xmlr, isrc);
            t.transform(source, result);
        } catch (TransformerException te) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, te.getMessage(), te);
        } finally {
            IOUtils.closeQuietly(is);
        }
        // second step: feed the intermediate DOM tree into StAX parser:
        try {
            parser = inputFactory.createXMLStreamReader(new DOMSource(result.getNode()));
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
        }
    }
    // Normal XML Loader
    else {
        try {
            is = stream.getStream();
            if (log.isTraceEnabled()) {
                final byte[] body = IOUtils.toByteArray(is);
                // TODO: The charset may be wrong, as the real charset is later
                // determined by the XML parser, the content-type is only used as a hint!
                log.trace("body",
                        new String(body, (charset == null) ? ContentStreamBase.DEFAULT_CHARSET : charset));
                IOUtils.closeQuietly(is);
                is = new ByteArrayInputStream(body);
            }
            parser = (charset == null) ? inputFactory.createXMLStreamReader(is)
                    : inputFactory.createXMLStreamReader(is, charset);
            this.processUpdate(req, processor, parser);
        } catch (XMLStreamException e) {
            throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, e.getMessage(), e);
        } finally {
            if (parser != null)
                parser.close();
            IOUtils.closeQuietly(is);
        }
    }
}

From source file:org.betaconceptframework.astroboa.test.util.JAXBValidationUtils.java

public void validateUsingSAX(InputStream is) throws Exception {
    SAXParser saxParser = parserFactory.newSAXParser();

    XMLReader xmlReader = saxParser.getXMLReader();
    xmlReader.setEntityResolver(entityResolver);
    xmlReader.setErrorHandler(errorHandler);

    errorHandler.setIgnoreInvalidElementSequence(false);

    is = encodeURLsFoundInXML(is);//  w  w w. j  a  v a2s .c om

    xmlReader.parse(new InputSource(is));
}