下面列出了org.w3c.dom.TypeInfo#org.xml.sax.XMLReader 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Parses the factoryConfig.xml file and sets up the ResourceFactory, ResourceSpecifierFactory,
* and XMLParser.
*
* @throws ParserConfigurationException
* if the XML parser could not be configured
* @throws SAXException
* if factoryConfig.xml could not be parsed
* @throws ClassNotFoundException -
* @throws IllegalAccessException -
* @throws InstantiationException -
* @throws IOException -
*/
protected void parseFactoryConfig() throws ParserConfigurationException, SAXException,
IOException, ClassNotFoundException, InstantiationException, IllegalAccessException {
FactoryConfigParseHandler handler = new FactoryConfigParseHandler();
// TOOD: Need UtilityClassLoader here? I don't think we do; this works
// with XML4J v3. This is a good thing, since the UtilityClassLoader writes
// to the logger, which isn't created yet!
SAXParserFactory factory = XMLUtils.createSAXParserFactory();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(handler);
reader.setErrorHandler(handler);
reader
.parse(new InputSource(UIMAFramework_impl.class
.getResourceAsStream("factoryConfig.xml")));
}
/**
* This method returns the SAX2 parser to use with the InputSource
* obtained from this URI.
* It may return null if any SAX2-conformant XML parser can be used,
* or if getInputSource() will also return null. The parser must
* be free for use (i.e., not currently in use for another parse().
* After use of the parser is completed, the releaseXMLReader(XMLReader)
* must be called.
*
* @param inputSource The value returned from the URIResolver.
* @return a SAX2 XMLReader to use to resolve the inputSource argument.
*
* @return non-null XMLReader reference ready to parse.
*/
synchronized public XMLReader getXMLReader(Source inputSource)
{
try
{
XMLReader reader = (inputSource instanceof SAXSource)
? ((SAXSource) inputSource).getXMLReader() : null;
// If user did not supply a reader, ask for one from the reader manager
if (null == reader) {
if (m_readerManager == null) {
m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
}
reader = m_readerManager.getXMLReader();
}
return reader;
} catch (SAXException se) {
throw new DTMException(se.getMessage(), se);
}
}
@SuppressWarnings("deprecation") // on JDK 9
private Schema loadSchema(Resource[] resources, String schemaLanguage) throws IOException, SAXException {
if (logger.isDebugEnabled()) {
logger.debug("Setting validation schema to " +
StringUtils.arrayToCommaDelimitedString(this.schemaResources));
}
Assert.notEmpty(resources, "No resources given");
Assert.hasLength(schemaLanguage, "No schema language provided");
Source[] schemaSources = new Source[resources.length];
XMLReader xmlReader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
for (int i = 0; i < resources.length; i++) {
Resource resource = resources[i];
Assert.isTrue(resource != null && resource.exists(), () -> "Resource does not exist: " + resource);
InputSource inputSource = SaxResourceUtils.createInputSource(resource);
schemaSources[i] = new SAXSource(xmlReader, inputSource);
}
SchemaFactory schemaFactory = SchemaFactory.newInstance(schemaLanguage);
if (this.schemaResourceResolver != null) {
schemaFactory.setResourceResolver(this.schemaResourceResolver);
}
return schemaFactory.newSchema(schemaSources);
}
public void parse (InputSource input) throws SAXException, IOException
{
XMLReader managedReader = null;
try {
if (getParent() == null) {
try {
managedReader = XMLReaderManager.getInstance(_useServicesMechanism)
.getXMLReader();
setParent(managedReader);
} catch (SAXException e) {
throw new SAXException(e.toString());
}
}
// call parse on the parent
getParent().parse(input);
} finally {
if (managedReader != null) {
XMLReaderManager.getInstance(_useServicesMechanism).releaseXMLReader(managedReader);
}
}
}
/**
* This method returns the SAX2 parser to use with the InputSource
* obtained from this URI.
* It may return null if any SAX2-conformant XML parser can be used,
* or if getInputSource() will also return null. The parser must
* be free for use (i.e., not currently in use for another parse().
* After use of the parser is completed, the releaseXMLReader(XMLReader)
* must be called.
*
* @param inputSource The value returned from the URIResolver.
* @return a SAX2 XMLReader to use to resolve the inputSource argument.
*
* @return non-null XMLReader reference ready to parse.
*/
synchronized public XMLReader getXMLReader(Source inputSource)
{
try
{
XMLReader reader = (inputSource instanceof SAXSource)
? ((SAXSource) inputSource).getXMLReader() : null;
// If user did not supply a reader, ask for one from the reader manager
if (null == reader) {
if (m_readerManager == null) {
m_readerManager = XMLReaderManager.getInstance(super.overrideDefaultParser());
}
reader = m_readerManager.getXMLReader();
}
return reader;
} catch (SAXException se) {
throw new DTMException(se.getMessage(), se);
}
}
private void fetchList(String path, boolean recur) throws IOException {
try {
XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler(this);
HttpURLConnection connection = openConnection("/listPaths" + path,
"ugi=" + ugi + (recur? "&recursive=yes" : ""));
connection.setRequestMethod("GET");
connection.connect();
InputStream resp = connection.getInputStream();
xr.parse(new InputSource(resp));
} catch(SAXException e) {
final Exception embedded = e.getException();
if (embedded != null && embedded instanceof IOException) {
throw (IOException)embedded;
}
throw new IOException("invalid xml directory content", e);
}
}
@Override
public <T> JAXBElement<T> unmarshal( Source source, Class<T> expectedType ) throws JAXBException {
if (source instanceof SAXSource) {
SAXSource ss = (SAXSource) source;
XMLReader locReader = ss.getXMLReader();
if (locReader == null) {
locReader = getXMLReader();
}
return unmarshal(locReader, ss.getInputSource(), expectedType);
}
if (source instanceof StreamSource) {
return unmarshal(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
}
if (source instanceof DOMSource) {
return unmarshal(((DOMSource) source).getNode(), expectedType);
}
// we don't handle other types of Source
throw new IllegalArgumentException();
}
/**
* Return the XMLReader to be used for parsing the input document.
*
* FIX ME: there is a bug in JAXP/XERCES that prevent the use of a
* parser that contains a schema with a DTD.
* @exception SAXException if no XMLReader can be instantiated
*/
public XMLReader getXMLReader() throws SAXException {
if (reader == null){
reader = getParser().getXMLReader();
}
reader.setDTDHandler(this);
reader.setContentHandler(this);
if (entityResolver == null){
reader.setEntityResolver(this);
} else {
reader.setEntityResolver(entityResolver);
}
reader.setProperty(
"http://xml.org/sax/properties/lexical-handler", this);
reader.setErrorHandler(this);
return reader;
}
/**
* Unit test for TemplatesHandler setter/getter.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase13() throws Exception {
String outputFile = USER_DIR + "saxtf013.out";
String goldFile = GOLDEN_DIR + "saxtf013GF.out";
try(FileInputStream fis = new FileInputStream(XML_FILE)) {
// The transformer will use a SAX parser as it's reader.
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory) TransformerFactory.newInstance();
TemplatesHandler thandler = saxTFactory.newTemplatesHandler();
// I have put this as it was complaining about systemid
thandler.setSystemId("file:///" + USER_DIR);
reader.setContentHandler(thandler);
reader.parse(XSLT_FILE);
XMLFilter filter
= saxTFactory.newXMLFilter(thandler.getTemplates());
filter.setParent(reader);
filter.setContentHandler(new MyContentHandler(outputFile));
filter.parse(new InputSource(fis));
}
assertTrue(compareWithGold(goldFile, outputFile));
}
public Object unmarshal0( Source source, JaxBeanInfo expectedType ) throws JAXBException {
if (source instanceof SAXSource) {
SAXSource ss = (SAXSource) source;
XMLReader locReader = ss.getXMLReader();
if (locReader == null) {
locReader = getXMLReader();
}
return unmarshal0(locReader, ss.getInputSource(), expectedType);
}
if (source instanceof StreamSource) {
return unmarshal0(getXMLReader(), streamSourceToInputSource((StreamSource) source), expectedType);
}
if (source instanceof DOMSource) {
return unmarshal0(((DOMSource) source).getNode(), expectedType);
}
// we don't handle other types of Source
throw new IllegalArgumentException();
}
/**
* Parse and load the given filter file.
*
* @param fileName
* name of the filter file
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
private void parse(String fileName, @WillClose InputStream stream) throws IOException, SAXException, ParserConfigurationException {
try {
SAXBugCollectionHandler handler = new SAXBugCollectionHandler(this, new File(fileName));
SAXParserFactory parserFactory = SAXParserFactory.newInstance();
parserFactory.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, Boolean.TRUE);
parserFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", Boolean.TRUE);
parserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
parserFactory.setFeature("http://xml.org/sax/features/external-general-entities", Boolean.FALSE);
parserFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", Boolean.FALSE);
SAXParser parser = parserFactory.newSAXParser();
XMLReader xr = parser.getXMLReader();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
Reader reader = Util.getReader(stream);
xr.parse(new InputSource(reader));
} finally {
Util.closeSilently(stream);
}
}
protected void decode(String fileName) {
try (InputStream exiIS = FileUtils.openInputStream(getFile(fileName, EXI_EXTENSION));
OutputStream os = FileUtils.openOutputStream(getFile(fileName, XML_EXTENSION_2))) {
Reader reader = new InputStreamReader(exiIS,"ISO-8859-1");
InputSource is = new InputSource(reader);
is.setEncoding("ISO-8859-1");
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
EXISource exiSource = new EXISource();
XMLReader exiReader = exiSource.getXMLReader();
SAXSource saxSource = new SAXSource(is);
// SAXSource saxSource = new SAXSource(new InputSource(exiIS));
exiSource.setXMLReader(exiReader);
transformer.transform(saxSource, new StreamResult(os));
} catch (Exception e) {
System.out.println(e.getStackTrace());
}
}
public void testLegacy() throws Exception {
ClassLoader clBackup = Thread.currentThread().getContextClassLoader();
try {
URL[] classUrls = { LEGACY_DIR.toUri().toURL() };
URLClassLoader loader = new URLClassLoader(classUrls, ClassLoader.getSystemClassLoader().getParent());
// set TCCL and try locating the provider
Thread.currentThread().setContextClassLoader(loader);
XMLReader reader1 = XMLReaderFactory.createXMLReader();
assertEquals(reader1.getClass().getName(), "xp3.XMLReaderImpl");
// now point to a random URL
Thread.currentThread().setContextClassLoader(
new URLClassLoader(new URL[0], ClassLoader.getSystemClassLoader().getParent()));
// ClassNotFoundException if also trying to load class of reader1, which
// would be the case before 8152912
XMLReader reader2 = XMLReaderFactory.createXMLReader();
assertEquals(reader2.getClass().getName(), "com.sun.org.apache.xerces.internal.parsers.SAXParser");
} finally {
Thread.currentThread().setContextClassLoader(clBackup);
}
}
/**
* Parses a stylesheet and builds the internal abstract syntax tree
* @param input A SAX2 InputSource can be passed to a SAX reader
* @return The root of the abstract syntax tree
*/
public SyntaxTreeNode parse(InputSource input) {
final XMLReader reader = JdkXmlUtils.getXMLReader(_overrideDefaultParser,
_xsltc.isSecureProcessing());
JdkXmlUtils.setXMLReaderPropertyIfSupport(reader, XMLConstants.ACCESS_EXTERNAL_DTD,
_xsltc.getProperty(XMLConstants.ACCESS_EXTERNAL_DTD), true);
String lastProperty = "";
try {
XMLSecurityManager securityManager =
(XMLSecurityManager) _xsltc.getProperty(XalanConstants.SECURITY_MANAGER);
for (XMLSecurityManager.Limit limit : XMLSecurityManager.Limit.values()) {
lastProperty = limit.apiProperty();
reader.setProperty(lastProperty, securityManager.getLimitValueAsString(limit));
}
if (securityManager.printEntityCountInfo()) {
lastProperty = XalanConstants.JDK_ENTITY_COUNT_INFO;
reader.setProperty(XalanConstants.JDK_ENTITY_COUNT_INFO, XalanConstants.JDK_YES);
}
} catch (SAXException se) {
XMLSecurityManager.printWarning(reader.getClass().getName(), lastProperty, se);
}
return (parse(reader, input));
}
/**
* This method returns the SAX2 parser to use with the InputSource
* obtained from this URI.
* It may return null if any SAX2-conformant XML parser can be used,
* or if getInputSource() will also return null. The parser must
* be free for use (i.e., not currently in use for another parse().
* After use of the parser is completed, the releaseXMLReader(XMLReader)
* must be called.
*
* @param inputSource The value returned from the URIResolver.
* @return a SAX2 XMLReader to use to resolve the inputSource argument.
*
* @return non-null XMLReader reference ready to parse.
*/
synchronized public XMLReader getXMLReader(Source inputSource)
{
try
{
XMLReader reader = (inputSource instanceof SAXSource)
? ((SAXSource) inputSource).getXMLReader() : null;
// If user did not supply a reader, ask for one from the reader manager
if (null == reader) {
if (m_readerManager == null) {
m_readerManager = XMLReaderManager.getInstance(super.useServicesMechnism());
}
reader = m_readerManager.getXMLReader();
}
return reader;
} catch (SAXException se) {
throw new DTMException(se.getMessage(), se);
}
}
public ArrayList<Episode> fetchEpisodes(String feedUrl, Podcast podcast) {
try {
Request request = new Request.Builder().url(feedUrl).build();
String response = BackendManager.getInstance().sendSimpleSynchronicRequest(request);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
xr.setContentHandler(episodesXMLHandler);
//TODO could be encoding problem
InputSource inputSource = new InputSource(new StringReader(response));
xr.parse(inputSource);
ArrayList<Episode> parsedEpisodes = episodesXMLHandler.getParsedEpisods();
if (podcast != null) {
podcast.setDescription(episodesXMLHandler.getPodcastSummary());
}
return parsedEpisodes;
} catch (Exception e) {
Logger.printError(TAG, "Can't fetch episodes for url: " + feedUrl);
e.printStackTrace();
return new ArrayList<Episode>();
}
}
public static ArrayList<Episode> parseEpisodes(String url) throws Exception {
Request episodesRequest = new Request.Builder().url(url).build();
String response = BackendManager.getInstance().sendSimpleSynchronicRequest(episodesRequest);
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
EpisodesXMLHandler episodesXMLHandler = new EpisodesXMLHandler();
xr.setContentHandler(episodesXMLHandler);
InputSource inputSource = new InputSource(new StringReader(response));
xr.parse(inputSource);
return episodesXMLHandler.getParsedEpisods();
}
/**
* No NPE expected when set error handler as null.
*
* @throws Exception If any errors occur.
*/
@Test
public void errorhandler02() throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
XMLReader xmlReader = spf.newSAXParser().getXMLReader();
xmlReader.setErrorHandler(null);
}
/**
* Parses a RELAX NG grammar into an annotated grammar.
*/
private Model loadRELAXNG() throws SAXException {
// build DOM forest
final DOMForest forest = buildDOMForest( new RELAXNGInternalizationLogic() );
// use JAXP masquerading to validate the input document.
// DOMForest -> ExtensionBindingChecker -> RNGOM
XMLReaderCreator xrc = new XMLReaderCreator() {
public XMLReader createXMLReader() {
// foreset parser cannot change the receivers while it's working,
// so we need to have one XMLFilter that works as a buffer
XMLFilter buffer = new XMLFilterImpl() {
@Override
public void parse(InputSource source) throws IOException, SAXException {
forest.createParser().parse( source, this, this, this );
}
};
XMLFilter f = new ExtensionBindingChecker(Const.RELAXNG_URI,opt,errorReceiver);
f.setParent(buffer);
f.setEntityResolver(opt.entityResolver);
return f;
}
};
Parseable p = new SAXParseable( opt.getGrammars()[0], errorReceiver, xrc );
return loadRELAXNG(p);
}
public XTMSnifferContentHandler(XTMTopicMapReader reader,
TopicMapStoreFactoryIF store_factory,
XMLReader parser,
LocatorIF base_address) {
this.reader = reader;
this.store_factory = store_factory;
this.parser = parser;
this.base_address = base_address;
this.entities = new HashMap();
}
public static SAXParser getParser() {
SAXParser parser;
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setValidating(false);
factory.setNamespaceAware(false);
XMLReader xmlReader;
try {
parser = factory.newSAXParser();
xmlReader = parser.getXMLReader();
} catch (ParserConfigurationException | SAXException e) {
throw new RuntimeException("Unable to create SAX parser", e);
}
setParserFeature(xmlReader, "http://xml.org/sax/features/namespaces", true);
setParserFeature(xmlReader, "http://xml.org/sax/features/namespace-prefixes", false);
// external entites
setParserFeature(xmlReader, "http://xml.org/sax/properties/external-general-entities", false);
setParserFeature(xmlReader, "http://xml.org/sax/properties/external-parameter-entities", false);
// external DTD
setParserFeature(xmlReader, "http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
// use Locator2 if possible
setParserFeature(xmlReader, "http://xml.org/sax/features/use-locator2", true);
return parser;
}
@SuppressWarnings("deprecation")
private static XMLReader getXMLReaderWXMLReaderFactory() {
try {
return org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
} catch (SAXException ex1) {
}
return null;
}
/**
* Renders the XML to the given canvas.
*/
protected void renderXml(String xml, mxICanvas2D canvas) throws SAXException, ParserConfigurationException, IOException
{
XMLReader reader = parserFactory.newSAXParser().getXMLReader();
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
reader.setFeature("http://xml.org/sax/features/external-general-entities", false);
reader.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
reader.setContentHandler(new mxSaxOutputHandler(canvas));
reader.parse(new InputSource(new StringReader(xml)));
}
protected XMLReader createXMLReader() {
XMLReader parser = null;
try {
parser = XMLUtil.createXMLReader(false, true);
try {
parser.setProperty("http://xml.org/sax/properties/lexical-handler", this); //NOI18N
} catch (SAXException sex) {
Logger.getLogger(XMLMIMEComponent.class.getName()).fine(NbBundle.getMessage(XMLMIMEComponent.class, "W-003")); //NOI18N
}
} catch (SAXException ex) {
Logger.getLogger(XMLMIMEComponent.class.getName()).log(Level.WARNING, null, ex);
}
return parser;
}
/**
* Implemented to replace the content handler currently in use by a
* NodeBuilder.
*
* @param namespaceURI the namespace URI of the matching element, or an
* empty string if the parser is not namespace aware or the element has
* no namespace
* @param name the local name if the parser is namespace aware, or just
* the element name otherwise
* @param attributes The attribute list of this element
* @throws Exception indicates a JAXP configuration problem
*/
@Override
public void begin(String namespaceURI, String name, Attributes attributes)
throws Exception {
XMLReader xmlReader = getDigester().getXMLReader();
Document doc = documentBuilder.newDocument();
NodeBuilder builder = null;
if (nodeType == Node.ELEMENT_NODE) {
Element element = null;
if (getDigester().getNamespaceAware()) {
element =
doc.createElementNS(namespaceURI, name);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttributeNS(attributes.getURI(i),
attributes.getLocalName(i),
attributes.getValue(i));
}
} else {
element = doc.createElement(name);
for (int i = 0; i < attributes.getLength(); i++) {
element.setAttribute(attributes.getQName(i),
attributes.getValue(i));
}
}
builder = new NodeBuilder(doc, element);
} else {
builder = new NodeBuilder(doc, doc.createDocumentFragment());
}
xmlReader.setContentHandler(builder);
}
public static void getSVGFromInputStream(String packageName, String className, InputStream svgData) throws Exception {
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
SVGHandler handler = new SVGHandler(packageName, className);
xr.setContentHandler(handler);
xr.parse(new InputSource(svgData));
handler.drawInstructions.print();
}
/**
* Creates a SAX parser using JAXP
*
* @return the created SAX parser
*/
static XMLReader createParser() {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
return factory.newSAXParser().getXMLReader();
} catch (Exception e) {
throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage());
}
}
private static InputSource makeInputSource(XMLReader xr, String systemId) throws IOException, SAXException {
EntityResolver er = xr.getEntityResolver();
if (er != null) {
InputSource inputSource = er.resolveEntity(null, systemId);
if (inputSource != null)
return inputSource;
}
return new InputSource(systemId);
}
@NonNull
private static Document parse(@NonNull String xml, @NonNull InputSource input, boolean checkBom,
boolean checkDtd)
throws ParserConfigurationException, SAXException, IOException {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
if (checkDtd) {
factory.setFeature(NAMESPACE_FEATURE, true);
factory.setFeature(NAMESPACE_PREFIX_FEATURE, true);
factory.setFeature(PROVIDE_XMLNS_URIS, true);
} else {
factory.setFeature(LOAD_EXTERNAL_DTD, false);
}
SAXParser parser = factory.newSAXParser();
DomBuilder handler = new DomBuilder(xml);
XMLReader xmlReader = parser.getXMLReader();
xmlReader.setProperty(
"http://xml.org/sax/properties/lexical-handler",
handler
);
parser.parse(input, handler);
return handler.getDocument();
} catch (SAXException e) {
if (checkBom && e.getMessage().contains("Content is not allowed in prolog")) {
// Byte order mark in the string? Skip it. There are many markers
// (see http://en.wikipedia.org/wiki/Byte_order_mark) so here we'll
// just skip those up to the XML prolog beginning character, <
xml = xml.replaceFirst("^([\\W]+)<","<"); //$NON-NLS-1$ //$NON-NLS-2$
return parse(xml, new InputSource(new StringReader(xml)), false, checkDtd);
}
throw e;
}
}
public static PomInfo readPom(InputStream is) throws SAXException, IOException {
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,true);
PomDependencyHandler handler = new PomDependencyHandler();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(is));
return handler.getPomInfo();
}