下面列出了怎么用javax.xml.transform.sax.SAXSource的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Loads the document and updates build-time (latency) statistics
*/
public void loadDocument(String uri) {
try {
final long stamp = System.currentTimeMillis();
_dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
new SAXSource(_reader, new InputSource(uri)),
false, null, true, false);
_dom.setDocumentURI(uri);
// The build time can be used for statistics for a better
// priority algorithm (currently round robin).
final long thisTime = System.currentTimeMillis() - stamp;
if (_buildTime > 0)
_buildTime = (_buildTime + thisTime) >>> 1;
else
_buildTime = thisTime;
}
catch (Exception e) {
_dom = null;
}
}
@Test
public void readSAXSourceExternal() throws Exception {
MockHttpInputMessage inputMessage = new MockHttpInputMessage(bodyExternal.getBytes("UTF-8"));
inputMessage.getHeaders().setContentType(new MediaType("application", "xml"));
converter.setSupportDtd(true);
SAXSource result = (SAXSource) converter.read(SAXSource.class, inputMessage);
InputSource inputSource = result.getInputSource();
XMLReader reader = result.getXMLReader();
reader.setContentHandler(new DefaultHandler() {
@Override
public void characters(char[] ch, int start, int length) {
String s = new String(ch, start, length);
assertNotEquals("Invalid result", "Foo Bar", s);
}
});
reader.parse(inputSource);
}
/**
* Template method for handling {@code StreamSource}s.
* <p>This implementation delegates to {@code unmarshalInputStream} or {@code unmarshalReader}.
* @param streamSource the {@code StreamSource}
* @return the object graph
* @throws IOException if an I/O exception occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
if (streamSource.getInputStream() != null) {
if (isProcessExternalEntities() && isSupportDtd()) {
return unmarshalInputStream(streamSource.getInputStream());
}
else {
InputSource inputSource = new InputSource(streamSource.getInputStream());
inputSource.setEncoding(getDefaultEncoding());
return unmarshalSaxSource(new SAXSource(inputSource));
}
}
else if (streamSource.getReader() != null) {
if (isProcessExternalEntities() && isSupportDtd()) {
return unmarshalReader(streamSource.getReader());
}
else {
return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getReader())));
}
}
else {
return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
}
}
/**
* Loads the document and updates build-time (latency) statistics
*/
public void loadDocument(String uri) {
try {
final long stamp = System.currentTimeMillis();
_dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
new SAXSource(_reader, new InputSource(uri)),
false, null, true, false);
_dom.setDocumentURI(uri);
// The build time can be used for statistics for a better
// priority algorithm (currently round robin).
final long thisTime = System.currentTimeMillis() - stamp;
if (_buildTime > 0)
_buildTime = (_buildTime + thisTime) >>> 1;
else
_buildTime = thisTime;
}
catch (Exception e) {
_dom = null;
}
}
@DataProvider(name = "data_ValidatorC")
public Object[][] getDataValidator() {
DOMSource ds = getDOMSource(xml_val_test, xml_val_test_id, true, true, xml_catalog);
SAXSource ss = new SAXSource(new InputSource(xml_val_test));
ss.setSystemId(xml_val_test_id);
StAXSource stax = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
StAXSource stax1 = getStaxSource(xml_val_test, xml_val_test_id, false, true, xml_catalog);
StreamSource source = new StreamSource(new File(xml_val_test));
return new Object[][]{
// use catalog
{false, false, true, ds, null, null, xml_bogus_catalog, null},
{false, false, true, ds, null, null, null, xml_bogus_catalog},
{false, false, true, ss, null, null, xml_bogus_catalog, null},
{false, false, true, ss, null, null, null, xml_bogus_catalog},
{false, false, true, stax, null, null, xml_bogus_catalog, null},
{false, false, true, stax1, null, null, null, xml_bogus_catalog},
{false, false, true, source, null, null, xml_bogus_catalog, null},
{false, false, true, source, null, null, null, xml_bogus_catalog},
};
}
@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();
}
/**
* 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);
}
}
@Test
public void testParse() throws Exception
{
final SAXSource source = new SAXSource(parser, new InputSource());
final DOMResult result = new DOMResult();
final Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.transform(source, result);
final Node root = ((Document) result.getNode()).getDocumentElement();
final JXPathContext ctx = JXPathContext.newContext(root);
assertEquals("Wrong name of root element", "database", root.getNodeName());
assertEquals("Wrong number of children of root", 1, ctx.selectNodes(
"/*").size());
assertEquals("Wrong number of tables", 2, ctx.selectNodes(
"/tables/table").size());
assertEquals("Wrong name of first table", "users", ctx
.getValue("/tables/table[1]/name"));
assertEquals("Wrong number of fields in first table", 5, ctx
.selectNodes("/tables/table[1]/fields/field").size());
assertEquals("Wrong attribute value", "system", ctx
.getValue("/tables/table[1]/@tableType"));
}
/**
* 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);
}
}
protected Source processSource(Source source) {
if (source instanceof StreamSource) {
StreamSource streamSource = (StreamSource) source;
InputSource inputSource = new InputSource(streamSource.getInputStream());
try {
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", !isSupportDtd());
String featureName = "http://xml.org/sax/features/external-general-entities";
xmlReader.setFeature(featureName, isProcessExternalEntities());
if (!isProcessExternalEntities()) {
xmlReader.setEntityResolver(NO_OP_ENTITY_RESOLVER);
}
return new SAXSource(xmlReader, inputSource);
}
catch (SAXException ex) {
logger.warn("Processing of external entities could not be disabled", ex);
return source;
}
}
else {
return source;
}
}
@Test
public void test02() {
String xml = "<?xml version='1.0'?><root/>";
ReaderStub.used = false;
setSystemProperty("org.xml.sax.driver", ReaderStub.class.getName());
try {
TransformerFactory transFactory = TransformerFactory.newInstance();
Transformer transformer = transFactory.newTransformer();
InputSource in = new InputSource(new StringReader(xml));
SAXSource source = new SAXSource(in);
StreamResult result = new StreamResult(new StringWriter());
transformer.transform(source, result);
Assert.assertTrue(printWasReaderStubCreated());
} catch (Exception ex) {
Assert.fail(ex.getMessage());
}
}
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();
}
public Object unmarshal( Source source ) throws JAXBException {
if( source == null ) {
throw new IllegalArgumentException(
Messages.format( Messages.MUST_NOT_BE_NULL, "source" ) );
}
if(source instanceof SAXSource)
return unmarshal( (SAXSource)source );
if(source instanceof StreamSource)
return unmarshal( streamSourceToInputSource((StreamSource)source));
if(source instanceof DOMSource)
return unmarshal( ((DOMSource)source).getNode() );
// we don't handle other types of Source
throw new IllegalArgumentException();
}
@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();
}
public static <T> T getPersistence(final Class<T> clazz, final InputStream persistenceDescriptor) throws Exception {
final JAXBContext jc = clazz.getClassLoader() == JaxbPersistenceFactory.class.getClassLoader() ?
JaxbJavaee.getContext(clazz) : JAXBContextFactory.newInstance(clazz);
final Unmarshaller u = jc.createUnmarshaller();
final UnmarshallerHandler uh = u.getUnmarshallerHandler();
// create a new XML parser
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(true);
final SAXParser parser = factory.newSAXParser();
final XMLReader xmlReader = parser.getXMLReader();
// Create a filter to intercept events
final PersistenceFilter xmlFilter = new PersistenceFilter(xmlReader);
// Be sure the filter has the JAXB content handler set (or it wont work)
xmlFilter.setContentHandler(uh);
final SAXSource source = new SAXSource(xmlFilter, new InputSource(persistenceDescriptor));
return (T) u.unmarshal(source);
}
/**
* Template method for handling {@code StreamSource}s.
* <p>This implementation delegates to {@code unmarshalInputStream} or {@code unmarshalReader}.
* @param streamSource the {@code StreamSource}
* @return the object graph
* @throws IOException if an I/O exception occurs
* @throws XmlMappingException if the given source cannot be mapped to an object
*/
protected Object unmarshalStreamSource(StreamSource streamSource) throws XmlMappingException, IOException {
if (streamSource.getInputStream() != null) {
if (isProcessExternalEntities() && isSupportDtd()) {
return unmarshalInputStream(streamSource.getInputStream());
}
else {
InputSource inputSource = new InputSource(streamSource.getInputStream());
inputSource.setEncoding(getDefaultEncoding());
return unmarshalSaxSource(new SAXSource(inputSource));
}
}
else if (streamSource.getReader() != null) {
if (isProcessExternalEntities() && isSupportDtd()) {
return unmarshalReader(streamSource.getReader());
}
else {
return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getReader())));
}
}
else {
return unmarshalSaxSource(new SAXSource(new InputSource(streamSource.getSystemId())));
}
}
@Test
public void whitespace() throws Exception {
String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><test><node1> </node1><node2> Some text </node2></test>";
Transformer transformer = TransformerFactory.newInstance().newTransformer();
AbstractStaxXMLReader staxXmlReader = createStaxXmlReader(
new ByteArrayInputStream(xml.getBytes("UTF-8")));
SAXSource source = new SAXSource(staxXmlReader, new InputSource());
DOMResult result = new DOMResult();
transformer.transform(source, result);
Node node1 = result.getNode().getFirstChild().getFirstChild();
assertEquals(" ", node1.getTextContent());
assertEquals(" Some text ", node1.getNextSibling().getTextContent());
}
@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);
}
}
public HibersapConfig parseResource(final InputStream resourceStream, final String resourceName) {
Object unmarshalledObject;
try {
SAXSource saxSource = createSaxSource(resourceStream);
unmarshalledObject = createUnmarshaller().unmarshal(saxSource);
} catch (final JAXBException e) {
throw new HibersapParseException("Cannot parse the resource " + resourceName, e);
}
if (unmarshalledObject == null) {
throw new HibersapParseException("Resource " + resourceName + " is empty.");
}
if (!(unmarshalledObject instanceof HibersapConfig)) {
throw new HibersapParseException("Resource " + resourceName
+ " does not consist of a hibersap specification. I found a "
+ unmarshalledObject.getClass().getSimpleName());
}
return (HibersapConfig) unmarshalledObject;
}
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware)
throws Exception {
if (validationMode == XmlBeanDefinitionReader.VALIDATION_NONE) {
SAXParserFactory parserFactory =
namespaceAware ? nsasaxParserFactory : saxParserFactory;
SAXParser parser = parserFactory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setEntityResolver(entityResolver);
reader.setErrorHandler(errorHandler);
SAXSource saxSource = new SAXSource(reader, inputSource);
W3CDOMStreamWriter writer = new W3CDOMStreamWriter();
StaxUtils.copy(saxSource, writer);
return writer.getDocument();
}
return super.loadDocument(inputSource, entityResolver, errorHandler, validationMode,
namespaceAware);
}
/**
* Loads the document and updates build-time (latency) statistics
*/
public void loadDocument(String uri) {
try {
final long stamp = System.currentTimeMillis();
_dom = (DOMEnhancedForDTM)_dtmManager.getDTM(
new SAXSource(_reader, new InputSource(uri)),
false, null, true, false);
_dom.setDocumentURI(uri);
// The build time can be used for statistics for a better
// priority algorithm (currently round robin).
final long thisTime = System.currentTimeMillis() - stamp;
if (_buildTime > 0)
_buildTime = (_buildTime + thisTime) >>> 1;
else
_buildTime = thisTime;
}
catch (Exception e) {
_dom = null;
}
}
private void checkTemplateUptodate()
throws TransformerConfigurationException, SAXException, ParserConfigurationException {
boolean check = System.currentTimeMillis() - modifiedChecked > CHECK_PERIOD;
boolean useCache = MCRConfiguration2.getBoolean("MCR.UseXSLTemplateCache").orElse(true);
if (check || !useCache) {
for (int i = 0; i < templateSources.length; i++) {
long lastModified = templateSources[i].getLastModified();
if (templates[i] == null || modified[i] < lastModified || !useCache) {
SAXSource source = templateSources[i].getSource();
templates[i] = tFactory.newTemplates(source);
if (templates[i] == null) {
throw new TransformerConfigurationException(
"XSLT Stylesheet could not be compiled: " + templateSources[i].getURL());
}
modified[i] = lastModified;
}
}
modifiedChecked = System.currentTimeMillis();
}
}
@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();
}
void transform(TransformerFactory factory) throws TransformerConfigurationException, TransformerException {
SAXSource xslSource = new SAXSource(new InputSource(xslFile));
xslSource.setSystemId(xslFileId);
Transformer transformer = factory.newTransformer(xslSource);
StringWriter stringResult = new StringWriter();
Result result = new StreamResult(stringResult);
transformer.transform(new SAXSource(new InputSource(xmlFile)), result);
}
/**
* @param pmmlString PMML model encoded as an XML doc in a string
* @return {@link PMML} object representing the model
* @throws IOException if XML can't be unserialized
*/
public static PMML fromString(String pmmlString) throws IOException {
try {
SAXSource transformed = SAXUtil.createFilteredSource(
new ByteArrayInputStream(pmmlString.getBytes(StandardCharsets.UTF_8)),
new ImportFilter());
return JAXBUtil.unmarshalPMML(transformed);
} catch (JAXBException | SAXException e) {
throw new IOException(e);
}
}
@Test
public void readSAXSourceWithXmlBomb() throws Exception {
// https://en.wikipedia.org/wiki/Billion_laughs
// https://msdn.microsoft.com/en-us/magazine/ee335713.aspx
String content = "<?xml version=\"1.0\"?>\n" +
"<!DOCTYPE lolz [\n" +
" <!ENTITY lol \"lol\">\n" +
" <!ELEMENT lolz (#PCDATA)>\n" +
" <!ENTITY lol1 \"&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;\">\n" +
" <!ENTITY lol2 \"&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;&lol1;\">\n" +
" <!ENTITY lol3 \"&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;&lol2;\">\n" +
" <!ENTITY lol4 \"&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;&lol3;\">\n" +
" <!ENTITY lol5 \"&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;&lol4;\">\n" +
" <!ENTITY lol6 \"&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;&lol5;\">\n" +
" <!ENTITY lol7 \"&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;&lol6;\">\n" +
" <!ENTITY lol8 \"&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;&lol7;\">\n" +
" <!ENTITY lol9 \"&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;&lol8;\">\n" +
"]>\n" +
"<root>&lol9;</root>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
SAXSource result = (SAXSource) this.converter.read(SAXSource.class, inputMessage);
InputSource inputSource = result.getInputSource();
XMLReader reader = result.getXMLReader();
assertThatExceptionOfType(SAXException.class).isThrownBy(() ->
reader.parse(inputSource))
.withMessageContaining("DOCTYPE");
}
@Test
public void writeSAXSource() throws Exception {
String xml = "<root>Hello World</root>";
SAXSource saxSource = new SAXSource(new InputSource(new StringReader(xml)));
MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
converter.write(saxSource, null, outputMessage);
assertThat("Invalid result", outputMessage.getBodyAsString(StandardCharsets.UTF_8),
isSimilarTo("<root>Hello World</root>"));
assertEquals("Invalid content-type", new MediaType("application", "xml"),
outputMessage.getHeaders().getContentType());
}
void transform(TransformerFactory factory) throws TransformerConfigurationException, TransformerException {
SAXSource xslSource = new SAXSource(new InputSource(xslFile));
xslSource.setSystemId(xslFileId);
Transformer transformer = factory.newTransformer(xslSource);
StringWriter stringResult = new StringWriter();
Result result = new StreamResult(stringResult);
transformer.transform(new SAXSource(new InputSource(xmlFile)), result);
}
/**
* convert an array of {@link InputSource InputSource} into an
* array of {@link Source Source}
*
* @param schemas array of {@link InputSource InputSource}
* @return array of {@link Source Source}
*/
private static Source[] getSchemaSource(InputSource[] schemas, EntityResolver entityResolver) throws SAXException {
SAXSource[] sources = new SAXSource[schemas.length];
for (int i = 0; i < schemas.length; i++) {
sources[i] = new SAXSource(schemas[i]);
// sources[i].getXMLReader().setEntityResolver(entityResolver);
}
return sources;
}
@Test
@SuppressWarnings("deprecation")
public void unmarshalSAXSource() throws Exception {
XMLReader reader = org.xml.sax.helpers.XMLReaderFactory.createXMLReader();
SAXSource source = new SAXSource(reader, new InputSource(new StringReader(INPUT_STRING)));
Object flights = unmarshaller.unmarshal(source);
testFlights(flights);
}