Java Code Examples for org.xml.sax.XMLReader#setEntityResolver()

The following examples show how to use org.xml.sax.XMLReader#setEntityResolver() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SourceHttpMessageConverter.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@SuppressWarnings("deprecation")  // on JDK 9
private SAXSource readSAXSource(InputStream body, HttpInputMessage inputMessage) throws IOException {
	try {
		XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
		xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
		xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
		if (!isProcessExternalEntities()) {
			xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
		}
		byte[] bytes = StreamUtils.copyToByteArray(body);
		return new SAXSource(xmlReader, new InputSource(new ByteArrayInputStream(bytes)));
	}
	catch (SAXException ex) {
		throw new HttpMessageNotReadableException(
				"Could not parse document: " + ex.getMessage(), ex, inputMessage);
	}
}
 
Example 2
Source File: CatalogTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
@Test(dataProvider = "catalog")
public void testCatalogResolver(String test, String expected, String catalogFile,
        String xml, SAXParser saxParser) throws Exception {
    URI catalog = null;
    if (catalogFile != null) {
        catalog = getClass().getResource(catalogFile).toURI();
    }
    String url = getClass().getResource(xml).getFile();
    try {
        CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalog);
        XMLReader reader = saxParser.getXMLReader();
        reader.setEntityResolver(cr);
        MyHandler handler = new MyHandler(saxParser);
        reader.setContentHandler(handler);
        reader.parse(url);
        System.out.println(test + ": expected [" + expected + "] <> actual [" + handler.getResult() + "]");
        Assert.assertEquals(handler.getResult(), expected);
    } catch (SAXException | IOException e) {
        Assert.fail(e.getMessage());
    }
}
 
Example 3
Source File: SAXParser.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 4
Source File: XML_SAX_StAX_FI.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
    StAXDocumentSerializer documentSerializer = new StAXDocumentSerializer();
    documentSerializer.setOutputStream(finf);

    SAX2StAXWriter saxTostax = new SAX2StAXWriter(documentSerializer);

    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setNamespaceAware(true);
    SAXParser saxParser = saxParserFactory.newSAXParser();

    XMLReader reader = saxParser.getXMLReader();
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", saxTostax);
    reader.setContentHandler(saxTostax);

    if (workingDirectory != null) {
        reader.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    reader.parse(new InputSource(xml));

    xml.close();
    finf.close();
}
 
Example 5
Source File: SAXParser.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 6
Source File: MCRURIResolver.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Source resolve(String href, String base) throws TransformerException {
    String path = href.substring(href.indexOf(":") + 1);
    URL resource = MCRConfigurationDir.getConfigResource(path);
    if (resource != null) {
        //have to use SAX here to resolve entities
        if (path.endsWith(".xsl")) {
            XMLReader reader;
            try {
                reader = MCRXMLParserFactory.getNonValidatingParser().getXMLReader();
            } catch (SAXException | ParserConfigurationException e) {
                throw new TransformerException(e);
            }
            reader.setEntityResolver(MCREntityResolver.instance());
            InputSource input = new InputSource(resource.toString());
            SAXSource saxSource = new SAXSource(reader, input);
            LOGGER.debug("include stylesheet: {}", saxSource.getSystemId());
            return saxSource;
        }
        return MCRURIResolver.instance().resolve(resource.toString(), base);
    }
    return null;
}
 
Example 7
Source File: XmlParser.java    From cloudhopper-commons with Apache License 2.0 6 votes vote down vote up
/**
    public synchronized void addContentHandler(String trigger, ContentHandler observer)
    {
        if (_observerMap == null)
            _observerMap = new HashMap();
        _observerMap.put(trigger, observer);
    }
     */

    /* ------------------------------------------------------------ */
    public synchronized Node parse(InputSource source) throws IOException, SAXException
    {
//        _dtd=null;
        Handler handler = new Handler();
        XMLReader reader = _parser.getXMLReader();
        reader.setContentHandler(handler);
        reader.setErrorHandler(handler);
        reader.setEntityResolver(handler);
        if (logger.isDebugEnabled())
            logger.debug("parsing: sid=" + source.getSystemId() + ",pid=" + source.getPublicId());
        _parser.parse(source, handler);
        if (handler.error != null)
            throw handler.error;
        Node root = (Node)handler.root;
        handler.reset();
        return root;
    }
 
Example 8
Source File: SAXParser.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 9
Source File: SAXParser.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 10
Source File: SAXParser.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Parse the content given {@link org.xml.sax.InputSource}
 * as XML using the specified
 * {@link org.xml.sax.helpers.DefaultHandler}.
 *
 * @param is The InputSource containing the content to be parsed.
 * @param dh The SAX DefaultHandler to use.
 *
 * @throws IllegalArgumentException If the <code>InputSource</code> object
 *   is <code>null</code>.
 * @throws IOException If any IO errors occur.
 * @throws SAXException If any SAX errors occur during processing.
 *
 * @see org.xml.sax.DocumentHandler
 */
public void parse(InputSource is, DefaultHandler dh)
    throws SAXException, IOException {
    if (is == null) {
        throw new IllegalArgumentException("InputSource cannot be null");
    }

    XMLReader reader = this.getXMLReader();
    if (dh != null) {
        reader.setContentHandler(dh);
        reader.setEntityResolver(dh);
        reader.setErrorHandler(dh);
        reader.setDTDHandler(dh);
    }
    reader.parse(is);
}
 
Example 11
Source File: AutomaticDependencies.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/**
 * The recognizer entry method taking an InputSource.
 * @param input InputSource to be parsed.
 * @throws IOException on I/O error.
 * @throws SAXException propagated exception thrown by a DocumentHandler.
 */
public void parse(final InputSource input) throws SAXException, IOException {
    XMLReader parser = XMLUtil.createXMLReader(false, false); // fastest mode
    parser.setContentHandler(this);
    parser.setErrorHandler(this);
    parser.setEntityResolver(this);
    parser.parse(input);
}
 
Example 12
Source File: XMLPListParser.java    From tm4e with Eclipse Public License 1.0 5 votes vote down vote up
public T parse(InputStream contents) throws Exception {
	SAXParserFactory spf = SAXParserFactory.newInstance();
	spf.setNamespaceAware(true);
	SAXParser saxParser = spf.newSAXParser();
	XMLReader xmlReader = saxParser.getXMLReader();
	xmlReader.setEntityResolver((arg0, arg1) -> new InputSource(new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())));
	PList<T> result = new PList<>(theme);
	xmlReader.setContentHandler(result);
	xmlReader.parse(new InputSource(contents));
	return result.getResult();
}
 
Example 13
Source File: XSLTransformationDialog.java    From tmxeditor8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 转换文件
 * @param strSourcePath
 *            源文件路径
 * @param strXSLPath
 *            XSL 文件路径
 * @param strTargetPath
 *            转变文件路径
 * @throws Exception
 *             ;
 */
private void transform(String strSourcePath, String strXSLPath, String strTargetPath) throws Exception {
	TransformerFactory tfactory = TransformerFactory.newInstance();
	String catalogPath = PluginUtil.getCataloguePath();

	if (tfactory.getFeature(SAXSource.FEATURE)) {
		// Standard way of creating an XMLReader in JAXP 1.1.
		SAXParserFactory pfactory = SAXParserFactory.newInstance();
		pfactory.setNamespaceAware(true); // Very important!
		// Turn on validation.
		// pfactory.setValidating(true);
		// Get an XMLReader.
		XMLReader reader = pfactory.newSAXParser().getXMLReader();
		reader.setEntityResolver(new Catalogue(catalogPath));

		// Instantiate an error handler (see the Handler inner class below)
		// that will report any
		// errors or warnings that occur as the XMLReader is parsing the XML
		// input.
		reader.setErrorHandler(new HSErrorHandler());

		// Standard way of creating a transformer from a URL.
		Transformer t = tfactory.newTransformer(new StreamSource(strXSLPath));

		// Specify a SAXSource that takes both an XMLReader and a URL.
		SAXSource source = new SAXSource(reader, new InputSource(strSourcePath));

		// Transform to a file.
		t.transform(source, new StreamResult(strTargetPath));

	} else {
		throw new Exception(Messages.getString("dialog.XSLTransformationDialog.msg6")); //$NON-NLS-1$
	}
}
 
Example 14
Source File: XmlUtils.java    From iaf with Apache License 2.0 5 votes vote down vote up
private static XMLReader getXMLReader(boolean namespaceAware, ClassLoader classLoader) throws ParserConfigurationException, SAXException {
	SAXParserFactory factory = getSAXParserFactory(namespaceAware);
	factory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
	XMLReader xmlReader = factory.newSAXParser().getXMLReader();
	if (classLoader!=null) {
		xmlReader.setEntityResolver(new ClassLoaderEntityResolver(classLoader));
	} else {
		xmlReader.setEntityResolver(new NonResolvingExternalEntityResolver());
	}
	return xmlReader;
}
 
Example 15
Source File: XML_SAX_FI.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
    SAXParser saxParser = getParser();
    SAXDocumentSerializer documentSerializer = getSerializer(finf);

    XMLReader reader = saxParser.getXMLReader();
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", documentSerializer);
    reader.setContentHandler(documentSerializer);

    if (workingDirectory != null) {
        reader.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    reader.parse(new InputSource(xml));
}
 
Example 16
Source File: SaxParserSafeEntityResolver.java    From Android_Code_Arbiter with GNU Lesser General Public License v3.0 5 votes vote down vote up
private static void receiveXMLStream(final InputStream inStream,
                                     final DefaultHandler defHandler)
        throws ParserConfigurationException, SAXException, IOException {
    // ...
    SAXParserFactory spf = SAXParserFactory.newInstance();
    final SAXParser saxParser = spf.newSAXParser();

    XMLReader reader = saxParser.getXMLReader();
    reader.setEntityResolver(new CustomResolver()); //Custom resolver
    InputSource is = new InputSource(inStream);
    reader.parse(is);
}
 
Example 17
Source File: DatabaseConnectionConvertor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
public Object instanceCreate() throws java.io.IOException, ClassNotFoundException {
    synchronized (this) {
        Object o = refConnection.get();
        if (o != null) {
            return o;
        }

        XMLDataObject obj = getHolder();
        if (obj == null) {
            return null;
        }
        FileObject connectionFO = obj.getPrimaryFile();
        Handler handler = new Handler(connectionFO.getNameExt());
        try {
            XMLReader reader = XMLUtil.createXMLReader();
            InputSource is = new InputSource(obj.getPrimaryFile().getInputStream());
            is.setSystemId(connectionFO.toURL().toExternalForm());
            reader.setContentHandler(handler);
            reader.setErrorHandler(handler);
            reader.setEntityResolver(EntityCatalog.getDefault());

            reader.parse(is);
        } catch (SAXException ex) {
            Exception x = ex.getException();
            LOGGER.log(Level.FINE, "Cannot read " + obj + ". Cause: " + ex.getLocalizedMessage(), ex);
            if (x instanceof java.io.IOException) {
                throw (IOException)x;
            } else {
                throw new java.io.IOException(ex.getMessage());
        }
        }

        DatabaseConnection inst = createDatabaseConnection(handler);
        refConnection = new WeakReference<>(inst);
        attachListener();
        return inst;
    }
}
 
Example 18
Source File: XML_SAX_FI.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public void parse(InputStream xml, OutputStream finf, String workingDirectory) throws Exception {
    SAXParser saxParser = getParser();
    SAXDocumentSerializer documentSerializer = getSerializer(finf);

    XMLReader reader = saxParser.getXMLReader();
    reader.setProperty("http://xml.org/sax/properties/lexical-handler", documentSerializer);
    reader.setContentHandler(documentSerializer);

    if (workingDirectory != null) {
        reader.setEntityResolver(createRelativePathResolver(workingDirectory));
    }
    reader.parse(new InputSource(xml));
}
 
Example 19
Source File: AbstractMarshaller.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Create an {@code XMLReader} that this marshaller will when passed an empty {@code SAXSource}.
 * @return the XMLReader
 * @throws SAXException if thrown by JAXP methods
 */
protected XMLReader createXmlReader() throws SAXException {
	XMLReader xmlReader = XMLReaderFactory.createXMLReader();
	xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
	xmlReader.setFeature("http://xml.org/sax/features/external-general-entities", isProcessExternalEntities());
	if (!isProcessExternalEntities()) {
		xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
	}
	return xmlReader;
}
 
Example 20
Source File: Resolver.java    From xml-maven-plugin with Apache License 2.0 5 votes vote down vote up
private Source asSaxSource( InputSource isource )
    throws SAXException, ParserConfigurationException
{
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating( validating );
    spf.setNamespaceAware( true );
    spf.setXIncludeAware( xincludeAware );
    XMLReader xmlReader = spf.newSAXParser().getXMLReader();
    xmlReader.setEntityResolver( this );
    return new SAXSource( xmlReader, isource );
}