下面列出了怎么用javax.xml.stream.XMLInputFactory的API类实例代码及写法,或者点击链接到github查看源代码。
private boolean scanForChildTag(String tagName, String xml) throws XMLStreamException {
final XMLInputFactory factory = XMLInputFactory.newInstance();
final XMLStreamReader reader = factory
.createXMLStreamReader(new ByteArrayInputStream(xml.getBytes()));
//advance to first tag (reader starts at "begin document")
reader.next();
final boolean found = PayloadNameRequestWrapper.scanForChildTag(reader, tagName);
if (found) {
assertEquals("Found wrong tag", tagName, reader.getLocalName());
}
reader.close();
return found;
}
/**
* Method checks if the storage type is supported and transforms it to XMLEventReader instance which is then returned.
* Throws PolicyException if the transformation is not succesfull or if the storage type is not supported.
*
* @param storage An XMLEventReader instance.
* @return The storage cast to an XMLEventReader.
* @throws PolicyException If the XMLEventReader cast failed.
*/
private XMLEventReader createXMLEventReader(final Object storage)
throws PolicyException {
if (storage instanceof XMLEventReader) {
return (XMLEventReader) storage;
}
else if (!(storage instanceof Reader)) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0022_STORAGE_TYPE_NOT_SUPPORTED(storage.getClass().getName())));
}
try {
return XMLInputFactory.newInstance().createXMLEventReader((Reader) storage);
} catch (XMLStreamException e) {
throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0014_UNABLE_TO_INSTANTIATE_READER_FOR_STORAGE(), e));
}
}
/**
* 默认转换将指定的xml转化为
* 方法描述
* @param inputStream
* @param fileName
* @return
* @throws JAXBException
* @throws XMLStreamException
* @创建日期 2016年9月16日
*/
public Object baseParseXmlToBean(String fileName) throws JAXBException, XMLStreamException {
// 搜索当前转化的文件
InputStream inputStream = XmlProcessBase.class.getResourceAsStream(fileName);
// 如果能够搜索到文件
if (inputStream != null) {
// 进行文件反序列化信息
XMLInputFactory xif = XMLInputFactory.newFactory();
xif.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLStreamReader xmlRead = xif.createXMLStreamReader(new StreamSource(inputStream));
return unmarshaller.unmarshal(xmlRead);
}
return null;
}
@Test
public void testChildlessResource() throws Exception {
MyParser parser = new ChildlessParser();
String xml =
"<subsystem xmlns=\"" + MyParser.NAMESPACE + "\">" +
" <cluster attr1=\"alice\"/>" +
"</subsystem>";
StringReader strReader = new StringReader(xml);
XMLMapper mapper = XMLMapper.Factory.create();
mapper.registerRootElement(new QName(MyParser.NAMESPACE, "subsystem"), parser);
XMLStreamReader reader = XMLInputFactory.newInstance().createXMLStreamReader(new StreamSource(strReader));
List<ModelNode> operations = new ArrayList<>();
mapper.parseDocument(operations, reader);
ModelNode subsystem = opsToModel(operations);
StringWriter stringWriter = new StringWriter();
XMLExtendedStreamWriter xmlStreamWriter = createXMLStreamWriter(XMLOutputFactory.newInstance()
.createXMLStreamWriter(stringWriter));
SubsystemMarshallingContext context = new SubsystemMarshallingContext(subsystem, xmlStreamWriter);
mapper.deparseDocument(parser, context, xmlStreamWriter);
String out = stringWriter.toString();
Assert.assertEquals(normalizeXML(xml), normalizeXML(out));
}
public XmlRecordSource(final InputStream in, final boolean ignoreWrapper) throws IOException {
try {
final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
// Avoid XXE Vulnerabilities
xmlInputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
xmlInputFactory.setProperty("javax.xml.stream.isSupportingExternalEntities", false);
xmlEventReader = xmlInputFactory.createXMLEventReader(in);
if (ignoreWrapper) {
readStartElement();
}
} catch (XMLStreamException e) {
throw new IOException("Could not parse XML", e);
}
}
public static RDBMSConfiguration loadConfig(String xmlConfiguration)
throws DataSourceException {
try {
xmlConfiguration = CarbonUtils.replaceSystemVariablesInXml(xmlConfiguration);
JAXBContext ctx = JAXBContext.newInstance(RDBMSConfiguration.class);
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
XMLStreamReader xmlReader = inputFactory.createXMLStreamReader(new StringReader(xmlConfiguration));
return (RDBMSConfiguration) ctx.createUnmarshaller().unmarshal(xmlReader);
} catch (Exception e) {
throw new DataSourceException("Error in loading RDBMS configuration: " +
e.getMessage(), e);
}
}
protected XmlFilterReader( Reader reader, UrlRewriteFilterContentDescriptor config ) throws IOException, XMLStreamException {
this.reader = reader;
this.config = config;
writer = new StringWriter();
buffer = writer.getBuffer();
offset = 0;
document = null;
stack = new Stack<>();
isEmptyElement = false;
factory = XMLInputFactory.newFactory();
//KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_DTD, Boolean.FALSE );
//KNOX-620 factory.setProperty( XMLConstants.ACCESS_EXTERNAL_SCHEMA, Boolean.FALSE );
/* This disables DTDs entirely for that factory */
factory.setProperty(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
/* disable external entities */
factory.setProperty("javax.xml.stream.isSupportingExternalEntities", Boolean.FALSE);
factory.setProperty( "javax.xml.stream.isReplacingEntityReferences", Boolean.FALSE );
factory.setProperty("http://java.sun.com/xml/stream/"
+ "properties/report-cdata-event", Boolean.TRUE);
parser = factory.createXMLEventReader( reader );
}
@Test
public void testStreamReader() {
XMLInputFactory ifac = XMLInputFactory.newInstance();
XMLOutputFactory ofac = XMLOutputFactory.newInstance();
try {
ifac.setProperty(ifac.IS_REPLACING_ENTITY_REFERENCES, new Boolean(false));
XMLStreamReader re = ifac.createXMLStreamReader(this.getClass().getResource(INPUT_FILE).toExternalForm(),
this.getClass().getResourceAsStream(INPUT_FILE));
while (re.hasNext()) {
int event = re.next();
if (event == XMLStreamConstants.START_ELEMENT && re.getLocalName().equals("bookurn")) {
Assert.assertTrue(re.getAttributeCount() == 0, "No attributes are expected for <bookurn> ");
Assert.assertTrue(re.getNamespaceCount() == 2, "Two namespaces are expected for <bookurn> ");
}
}
} catch (Exception e) {
e.printStackTrace();
Assert.fail("Exception occured: " + e.getMessage());
}
}
@Test
@SuppressWarnings("unchecked")
public void readXmlRootElementExternalEntityEnabled() throws Exception {
Resource external = new ClassPathResource("external.txt", getClass());
String content = "<!DOCTYPE root [" +
" <!ELEMENT external ANY >\n" +
" <!ENTITY ext SYSTEM \"" + external.getURI() + "\" >]>" +
" <list><rootElement><type s=\"1\"/><external>&ext;</external></rootElement></list>";
MockHttpInputMessage inputMessage = new MockHttpInputMessage(content.getBytes("UTF-8"));
Jaxb2CollectionHttpMessageConverter<?> c = new Jaxb2CollectionHttpMessageConverter<Collection<Object>>() {
@Override
protected XMLInputFactory createXmlInputFactory() {
XMLInputFactory inputFactory = XMLInputFactory.newInstance();
inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, true);
return inputFactory;
}
};
Collection<RootElement> result = c.read(rootElementListType, null, inputMessage);
assertEquals(1, result.size());
assertEquals("Foo Bar", result.iterator().next().external);
}
/**
* Test if this file is an XML file
*
* @param path
* the path to check
* @return <code>true</code> if this is an XML file
* @throws IOException
* if the probing fails
*/
public static boolean isXml ( final Path path ) throws IOException
{
final XmlToolsFactory xml = Activator.getXmlToolsFactory ();
final XMLInputFactory xin = xml.newXMLInputFactory ();
try ( InputStream stream = new BufferedInputStream ( Files.newInputStream ( path ) ) )
{
try
{
final XMLStreamReader reader = xin.createXMLStreamReader ( stream );
reader.next ();
return true;
}
catch ( final XMLStreamException e )
{
return false;
}
}
}
private XMLStreamReader parse(InputStream is, String systemIdStr,
boolean restricted) throws IOException, XMLStreamException {
if (!quietmode) {
LOG.debug("parsing input stream " + is);
}
if (is == null) {
return null;
}
SystemId systemId = SystemId.construct(systemIdStr);
ReaderConfig readerConfig = XML_INPUT_FACTORY.createPrivateConfig();
if (restricted) {
readerConfig.setProperty(XMLInputFactory.SUPPORT_DTD, false);
}
return XML_INPUT_FACTORY.createSR(readerConfig, systemId,
StreamBootstrapper.getInstance(null, systemId, is), false, true);
}
private XMLStreamReader createStreamReader(final String fileName) throws IOException, EntityProviderException {
XMLInputFactory factory = XMLInputFactory.newInstance();
factory.setProperty(XMLInputFactory.IS_VALIDATING, false);
factory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, true);
InputStream in = ClassLoader.class.getResourceAsStream(fileName);
if (in == null) {
throw new IOException("Requested file '" + fileName + "' was not found.");
}
XMLStreamReader streamReader;
try {
streamReader = factory.createXMLStreamReader(in);
} catch (XMLStreamException e) {
throw new EntityProviderException(EntityProviderException.COMMON.addContent("Invalid Service Document"));
}
return streamReader;
}
@Test
public void testXml() throws IOException, XMLStreamException {
String xml = "<?xml version=\"1.0\" ?><index name=\"tso-generator-speed-automaton\"><onUnderSpeedDisconnectedGenerators><gen>a</gen><gen>b</gen></onUnderSpeedDisconnectedGenerators><onOverSpeedDisconnectedGenerators><gen>c</gen></onOverSpeedDisconnectedGenerators></index>";
XMLInputFactory xmlif = XMLInputFactory.newInstance();
TsoGeneratorSpeedAutomaton index;
try (Reader reader = new StringReader(xml)) {
XMLStreamReader xmlReader = xmlif.createXMLStreamReader(reader);
try {
index = TsoGeneratorSpeedAutomaton.fromXml("c1", xmlReader);
} finally {
xmlReader.close();
}
}
assertTrue(index.getOnUnderSpeedDiconnectedGenerators().equals(Arrays.asList("a", "b")));
assertTrue(index.getOnOverSpeedDiconnectedGenerators().equals(Arrays.asList("c")));
assertEquals(xml, index.toXml());
}
@Test
public void test() {
try {
Source source = new StreamSource(util.BOMInputStream.createStream("UTF-16BE", this.getClass().getResourceAsStream("Hello.wsdl.data")),
this.getClass().getResource("Hello.wsdl.data").toExternalForm());
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer();
transformer.transform(source, new StreamResult(baos));
System.out.println(new String(baos.toByteArray()));
ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
InputSource inSource = new InputSource(bis);
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
xmlInputFactory.setProperty(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
XMLStreamReader reader = xmlInputFactory.createXMLStreamReader(inSource.getSystemId(), inSource.getByteStream());
while (reader.hasNext()) {
reader.next();
}
} catch (Exception ex) {
ex.printStackTrace(System.err);
Assert.fail("Exception occured: " + ex.getMessage());
}
}
public void testLongCDATA() throws Exception {
try {
Reader reader = createLongReader("<![CDATA[", "]]>", true);
XMLInputFactory factory = getNewInputFactory();
factory.setProperty(WstxInputProperties.P_MAX_TEXT_LENGTH, Integer.valueOf(50000));
XMLStreamReader xmlreader = factory.createXMLStreamReader(reader);
while (xmlreader.next() != XMLStreamReader.START_ELEMENT) {
}
assertEquals(XMLStreamReader.CDATA, xmlreader.next());
while (xmlreader.next() != XMLStreamReader.START_ELEMENT) {
}
fail("Should have failed");
} catch (XMLStreamException ex) {
_verifyTextLimitException(ex);
}
}
public void addExistingConfiguration(DataHandler dh)
throws IOException, LocalEntryAdminException, XMLStreamException {
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement configSourceElem = builder.getDocumentElement();
configServiceAdminStub.addExistingConfiguration(configSourceElem.toString());
}
/**
* Creates a new StAX XMLInputFactory, with sensible defaults
*/
public static XMLInputFactory newXMLInputFactory() {
XMLInputFactory factory = XMLInputFactory.newFactory();
trySetProperty(factory, XMLInputFactory.IS_NAMESPACE_AWARE, true);
trySetProperty(factory, XMLInputFactory.IS_VALIDATING, false);
trySetProperty(factory, XMLInputFactory.SUPPORT_DTD, false);
trySetProperty(factory, XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
return factory;
}
public Zephyr(XMLInputFactory xif, Class clazz) throws NoSuchMethodException {
zephyrClass = clazz;
setInputSourceMethod = clazz.getMethod("setInputSource", InputSource.class);
resetMethod = clazz.getMethod("reset");
try {
// Turn OFF internal factory caching in Zephyr.
// Santiago told me that this makes it thread-safe.
xif.setProperty("reuse-instance", false);
} catch (IllegalArgumentException e) {
// falls through
}
this.xif = xif;
}
private void readXML(byte[] xmlData, String expectedContent)
throws Exception {
InputStream stream = new ByteArrayInputStream(xmlData);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader xmlReader
= factory.createXMLStreamReader(stream);
boolean inTestElement = false;
StringBuilder sb = new StringBuilder();
while (xmlReader.hasNext()) {
String ename;
switch (xmlReader.getEventType()) {
case XMLStreamConstants.START_ELEMENT:
ename = xmlReader.getLocalName();
if (ename.equals("writeCharactersWithString")
|| ename.equals("writeCharactersWithArray")) {
inTestElement = true;
}
break;
case XMLStreamConstants.END_ELEMENT:
ename = xmlReader.getLocalName();
if (ename.equals("writeCharactersWithString")
|| ename.equals("writeCharactersWithArray")) {
inTestElement = false;
String content = sb.toString();
System.out.println(ename + " text:'" + content + "' expected:'" + expectedContent+"'");
Assert.assertEquals(content, expectedContent);
sb.setLength(0);
}
break;
case XMLStreamConstants.CHARACTERS:
if (inTestElement) {
sb.append(xmlReader.getText());
}
break;
}
xmlReader.next();
}
}
public void addDynamicSequenceTemplate(String key, DataHandler dh) throws IOException, XMLStreamException {
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
//create the builder
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement template = builder.getDocumentElement();
templateAdminStub.addDynamicTemplate(key, template);
}
public void addPriorityMediator(String name, DataHandler dh)
throws IOException, XMLStreamException {
XMLStreamReader parser =
XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement messageProcessorElem = builder.getDocumentElement();
priorityMediationAdmin.add(name, messageProcessorElem);
}
public void addDynamicEndpointTemplate(String key, DataHandler dh) throws IOException, XMLStreamException {
XMLStreamReader parser = XMLInputFactory.newInstance().createXMLStreamReader(dh.getInputStream());
//create the builder
StAXOMBuilder builder = new StAXOMBuilder(parser);
OMElement endpointTemplate = builder.getDocumentElement();
endpointTemplateAdminStub.addDynamicEndpointTemplate(key, endpointTemplate.toString());
}
public void setProperty(String name, Object value){
checkProperty(name);
if (name.equals(XMLInputFactory.IS_VALIDATING) &&
Boolean.TRUE.equals(value)){
throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.validationNotSupported") +
CommonResourceBundle.getInstance().getString("support_validation"));
} else if (name.equals(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES) &&
Boolean.TRUE.equals(value)) {
throw new IllegalArgumentException(CommonResourceBundle.getInstance().getString("message.externalEntities") +
CommonResourceBundle.getInstance().getString("resolve_external_entities_"));
}
features.put(name,value);
}
private OMElement updateSynapseConfiguration(File synapseFile)
throws IOException, XMLStreamException {
OMElement synapseContent;
BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(synapseFile));
XMLStreamReader xmlStreamReader = XMLInputFactory.newInstance().createXMLStreamReader(bufferedInputStream);
StAXOMBuilder stAXOMBuilder = new StAXOMBuilder(xmlStreamReader);
synapseContent = stAXOMBuilder.getDocumentElement();
synapseContent.build();
bufferedInputStream.close();
OMElement targetElement = synapseContent.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "target"));
OMElement outSequenceElement = targetElement.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "outSequence"));
OMElement dbReportElement = outSequenceElement.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "dbreport"));
OMElement connectionElement = dbReportElement.getFirstChildWithName(
new QName("http://ws.apache.org/ns/synapse", "connection"));
OMElement poolElement = connectionElement.getFirstElement();
OMElement driverElemnt = poolElement.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "driver"));
OMElement urlElemnt = poolElement.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "url"));
OMElement userElemnt = poolElement.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "user"));
OMElement passwordElemnt = poolElement.getFirstChildWithName(new QName("http://ws.apache.org/ns/synapse", "password"));
driverElemnt.setText(JDBC_DRIVER);
urlElemnt.setText(JDBC_URL);
userElemnt.setText(DB_USER);
passwordElemnt.setText(DB_PASSWORD);
return synapseContent;
}
@Inject
BatchJobHelperUtility(
Supplier<Transformer> transformerSupplier,
XMLInputFactory xmlInputFactory,
XMLOutputFactory xmlOutputFactory,
XMLEventFactory xmlEventFactory) {
this.transformerSupplier = transformerSupplier;
this.xmlInputFactory = xmlInputFactory;
this.xmlOutputFactory = xmlOutputFactory;
this.xmlEventFactory = xmlEventFactory;
}
@Test(dataProvider = "supportXMLResolver")
public void supportXMLResolver(URI catalogFile, String xml, String expected) throws Exception {
String xmlSource = getClass().getResource(xml).getFile();
CatalogResolver cr = CatalogManager.catalogResolver(CatalogFeatures.defaults(), catalogFile);
XMLInputFactory xifactory = XMLInputFactory.newInstance();
xifactory.setProperty(XMLInputFactory.IS_COALESCING, true);
xifactory.setProperty(XMLInputFactory.RESOLVER, cr);
File file = new File(xmlSource);
String systemId = file.toURI().toASCIIString();
InputStream entityxml = new FileInputStream(file);
XMLStreamReader streamReader = xifactory.createXMLStreamReader(systemId, entityxml);
String result = null;
while (streamReader.hasNext()) {
int eventType = streamReader.next();
if (eventType == XMLStreamConstants.START_ELEMENT) {
eventType = streamReader.next();
if (eventType == XMLStreamConstants.CHARACTERS) {
result = streamReader.getText();
}
}
}
System.out.println(": expected [" + expected + "] <> actual [" + result.trim() + "]");
Assert.assertEquals(result.trim(), expected);
}
public static OMElement nonCoalescingStringToOm(String xmlStr) throws XMLStreamException {
StringReader strReader = new StringReader(xmlStr);
XMLInputFactory xmlInFac = XMLInputFactory.newInstance();
// Non-Coalescing parsing
xmlInFac.setProperty("javax.xml.stream.isCoalescing", false);
XMLStreamReader parser = xmlInFac.createXMLStreamReader(strReader);
StAXOMBuilder builder = new StAXOMBuilder(parser);
return builder.getDocumentElement();
}
private void initConfigurableReaderProperties(){
//spec v1.0 default values
features.put(XMLInputFactory.IS_NAMESPACE_AWARE, Boolean.TRUE);
features.put(XMLInputFactory.IS_VALIDATING, Boolean.FALSE);
features.put(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, Boolean.TRUE);
features.put(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, Boolean.TRUE);
features.put(XMLInputFactory.IS_COALESCING, Boolean.FALSE);
features.put(XMLInputFactory.SUPPORT_DTD, Boolean.FALSE);
features.put(XMLInputFactory.REPORTER, null);
features.put(XMLInputFactory.RESOLVER, null);
features.put(XMLInputFactory.ALLOCATOR, null);
features.put(STAX_NOTATIONS,null );
}
public Zephyr(XMLInputFactory xif, Class clazz) throws NoSuchMethodException {
zephyrClass = clazz;
setInputSourceMethod = clazz.getMethod("setInputSource", InputSource.class);
resetMethod = clazz.getMethod("reset");
try {
// Turn OFF internal factory caching in Zephyr.
// Santiago told me that this makes it thread-safe.
xif.setProperty("reuse-instance", false);
} catch (IllegalArgumentException e) {
// falls through
}
this.xif = xif;
}
XmlHandler(byte[] content, Set<? extends Iterable<String>> paths)
throws XMLStreamException {
prefixTrie = new PathTrie(paths);
Reader reader = new InputStreamReader(new ByteArrayInputStream(content), UTF_8);
XMLInputFactory f = XMLInputFactory.newInstance();
xmlr = f.createXMLEventReader(reader);
}