下面列出了org.xml.sax.helpers.XMLReaderFactory#createXMLReader ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private FileChecksum getFileChecksum(String f) throws IOException {
final HttpURLConnection connection = openConnection(
"/fileChecksum" + ServletUtil.encodePath(f),
"ugi=" + getEncodedUgiParameter());
try {
final XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler(this);
xr.parse(new InputSource(connection.getInputStream()));
} 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);
} finally {
connection.disconnect();
}
return filechecksum;
}
private synchronized OutputStream encode(InputStream jaxbXML, Grammars grammar) {
EXIResult exiResult = null;
try {
exiFactory.setGrammars(grammar);
encodeOS = new ByteArrayOutputStream();
exiResult = new EXIResult(exiFactory);
exiResult.setOutputStream(encodeOS);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setContentHandler(exiResult.getHandler());
// parse xml file
xmlReader.parse(new InputSource(jaxbXML));
encodeOS.close();
} catch (SAXException | IOException | EXIException e) {
getLogger().error(e.getClass().getSimpleName() + " occurred while trying to encode", e);
}
return encodeOS;
}
/**
* Unit test for contentHandler setter/getter along reader as handler's
* parent.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase10() throws Exception {
String outputFile = USER_DIR + "saxtf010.out";
String goldFile = GOLDEN_DIR + "saxtf010GF.out";
// The transformer will use a SAX parser as it's reader.
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory)TransformerFactory.newInstance();
XMLFilter filter =
saxTFactory.newXMLFilter(new StreamSource(XSLT_FILE));
filter.setParent(reader);
filter.setContentHandler(new MyContentHandler(outputFile));
// Now, when you call transformer.parse, it will set itself as
// the content handler for the parser object (it's "parent"), and
// will then call the parse method on the parser.
filter.parse(new InputSource(XML_FILE));
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* SAXTFactory.newTransformerhandler() method which takes SAXSource as
* argument can be set to XMLReader. SAXSource has input XML file as its
* input source. XMLReader has a transformer handler which write out the
* result to output file. Test verifies output file is same as golden file.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase01() throws Exception {
String outputFile = USER_DIR + "saxtf001.out";
String goldFile = GOLDEN_DIR + "saxtf001GF.out";
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory) TransformerFactory.newInstance();
TransformerHandler handler = saxTFactory.newTransformerHandler(new StreamSource(XSLT_FILE));
Result result = new StreamResult(fos);
handler.setResult(result);
reader.setContentHandler(handler);
reader.parse(XML_FILE);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* 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 XMLReader fetchSheetParser(SharedStringsTable sst)
throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
this.sst = sst;
parser.setContentHandler(this);
return parser;
}
protected void read(final ProtocolFactory protocols, final Local child) throws AccessDeniedException {
try {
final BufferedReader in = new BufferedReader(new InputStreamReader(child.getInputStream(),
StandardCharsets.UTF_8));
AbstractHandler handler = this.getHandler(protocols);
final XMLReader xr = XMLReaderFactory.createXMLReader();
xr.setContentHandler(handler);
xr.setErrorHandler(handler);
xr.parse(new InputSource(in));
}
catch(SAXException | IOException e) {
log.error(String.format("Error reading %s:%s", this.getFile(), e.getMessage()));
}
}
/**
* Creates a property resource bundle.
* @param filelocation location of XML file to parse
* @throws IOException if the file can't be parsed/loaded
*/
public XmlResourceBundle(String filelocation) throws IOException {
strings = new HashMap<String, String>();
try {
// These are namespace URLs, and don't actually
// resolve to real documents that get downloaded on the
// web.
// Turn on validation
String validationFeature
= "http://xml.org/sax/features/validation";
// Turn on schema validation
String schemaFeature
= "http://apache.org/xml/features/validation/schema";
// We have to store the xsd locally because we may not have
// access to it over the web when starting up the service.
String xsdLocation =
this.getClass().getResource("/xliff-core-1.1.xsd").toString();
XMLReader parser = XMLReaderFactory.
createXMLReader("org.apache.xerces.parsers.SAXParser");
parser.setFeature(validationFeature, false);
parser.setFeature(schemaFeature, false);
parser.setProperty("http://apache.org/xml/properties/schema/" +
"external-noNamespaceSchemaLocation", xsdLocation);
XmlResourceBundleParser handler = new XmlResourceBundleParser();
parser.setContentHandler(handler);
parser.parse(new InputSource(this.getClass().
getResourceAsStream(filelocation)));
strings = handler.getMessages();
}
catch (SAXException e) {
// This really should never happen, because without this file,
// the whole UI stops working.
log.error("Could not setup parser");
throw new IOException("Could not load XML bundle: " + filelocation);
}
// TODO: put the xml strings in the Map
}
private void processEntry(final ZipInputStream zis, final ZipEntry ze, final ContentHandlerFactory handlerFactory) {
ContentHandler handler = handlerFactory.createContentHandler();
try {
// if (CODE2ASM.equals(command)) { // read bytecode and process it
// // with TraceClassVisitor
// ClassReader cr = new ClassReader(readEntry(zis, ze));
// cr.accept(new TraceClassVisitor(null, new PrintWriter(os)),
// false);
// }
boolean singleInputDocument = inRepresentation == SINGLE_XML;
if (inRepresentation == BYTECODE) { // read bytecode and process it
// with handler
ClassReader cr = new ClassReader(readEntry(zis, ze));
cr.accept(new SAXClassAdapter(handler, singleInputDocument), 0);
} else { // read XML and process it with handler
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(handler);
reader
.parse(new InputSource(singleInputDocument ? (InputStream) new ProtectedInputStream(zis) : new ByteArrayInputStream(readEntry(zis, ze))));
}
} catch (Exception ex) {
update(ze.getName(), 0);
update(ex, 0);
}
}
@Override
public Multimap<String,NormalizedContentInterface> getEventFields(RawRecordContainer event) {
HashMultimap<String,String> fields = HashMultimap.create();
// Get the raw data
String data = new String(event.getRawData());
// Wrap the data
StringReader reader = new StringReader(data);
InputSource source = new InputSource(reader);
// Create an XML parser
try {
WikipediaContentHandler handler = new WikipediaContentHandler(fields, ignoreFields);
XMLReader parser = XMLReaderFactory.createXMLReader();
parser.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
parser.setFeature("http://xml.org/sax/features/external-general-entities", false);
parser.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
parser.setContentHandler(handler);
parser.parse(source);
} catch (Exception e) {
// If error, return empty results map.
log.error("Error processing Wikipedia XML document", e);
event.addError(RawDataErrorNames.FIELD_EXTRACTION_ERROR);
}
extractWikipediaTypeInformation(event, fields);
return normalize(fields);
}
/**
* Parse the file.
* @param filetoParse path of the file to parse in the client file system.
* @throws Exception if parsing fails.
*/
public void fileParser(final String filetoParse) throws Exception {
final InputStream is = getClass().getClassLoader().getResourceAsStream(filetoParse);
//InputSource src = new InputSource(is);
new InputSource(is);
// Creating XMLReader instance
//XMLReader reader = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
/* reader.setContentHandler(brsaxParser);
* reader.setErrorHandler(brsaxParser);
* // Parsing the XML file
* reader.parse(src); */
}
public XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser =
XMLReaderFactory.createXMLReader(
"org.apache.xerces.parsers.SAXParser"
);
ContentHandler handler = new SheetHandler(sst);
parser.setContentHandler(handler);
return parser;
}
/**
* Constructs the XML SAX parser.
*
* @throws SdkClientException
*/
public XmlResponsesSaxParser() throws SdkClientException {
// Ensure we can load the XML Reader.
try {
xr = XMLReaderFactory.createXMLReader();
} catch (SAXException e) {
throw new SdkClientException("Couldn't initialize a SAX driver to create an XMLReader", e);
}
}
private XMLReader fetchSheetParser(SharedStringsTable sst, ISaxRowRead rowRead)
throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
ContentHandler handler = new SheetHandler(sst, rowRead);
parser.setContentHandler(handler);
return parser;
}
/**
* Unit test for XMLReader parsing when relative URI is used in xsl file and
* SystemId was set.
*
* @throws Exception If any errors occur.
*/
@Test
public void testcase05() throws Exception {
String outputFile = USER_DIR + "saxtf005.out";
String goldFile = GOLDEN_DIR + "saxtf005GF.out";
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory)TransformerFactory.newInstance();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
DocumentBuilder docBuilder = dbf.newDocumentBuilder();
Document document = docBuilder.parse(new File(XSLT_INCL_FILE));
Node node = (Node)document;
DOMSource domSource= new DOMSource(node);
domSource.setSystemId("file:///" + XML_DIR);
TransformerHandler handler =
saxTFactory.newTransformerHandler(domSource);
Result result = new StreamResult(fos);
handler.setResult(result);
reader.setContentHandler(handler);
reader.parse(XML_FILE);
}
assertTrue(compareWithGold(goldFile, outputFile));
}
/**
* Unit test for simple DOM parsing.
* @throws Exception If any errors occur.
*/
@Test
public void testcase01() throws Exception {
String resultFile = USER_DIR + "domresult01.out";
String goldFile = GOLDEN_DIR + "domresult01GF.out";
String xsltFile = XML_DIR + "cities.xsl";
String xmlFile = XML_DIR + "cities.xml";
XMLReader reader = XMLReaderFactory.createXMLReader();
SAXTransformerFactory saxTFactory
= (SAXTransformerFactory) TransformerFactory.newInstance();
SAXSource saxSource = new SAXSource(new InputSource(xsltFile));
TransformerHandler handler
= saxTFactory.newTransformerHandler(saxSource);
DOMResult result = new DOMResult();
handler.setResult(result);
reader.setContentHandler(handler);
reader.parse(xmlFile);
Node node = result.getNode();
try (BufferedWriter writer = new BufferedWriter(new FileWriter(resultFile))) {
writeNodes(node, writer);
}
assertTrue(compareWithGold(goldFile, resultFile));
}
@Before
public void setUp() throws Exception {
inputFactory = XMLInputFactory.newInstance();
standardReader = XMLReaderFactory.createXMLReader();
standardContentHandler = mockContentHandler();
standardReader.setContentHandler(standardContentHandler);
}
@Override
public void write(EXIObject<XmlObject> exiObject, OutputStream out, ResponseProxy responseProxy)
throws IOException, EncodingException {
byte[] bytes = getBytes(exiObject);
try (InputStream is = new ByteArrayInputStream(bytes)) {
EXIResult result = new EXIResult(this.exiFactory.get());
result.setOutputStream(out);
XMLReader xmlReader = XMLReaderFactory.createXMLReader();
xmlReader.setContentHandler(result.getHandler());
xmlReader.parse(new InputSource(is));
} catch (EXIException | SAXException e) {
throw new EncodingException(e);
}
}
private XMLReader fetchSheetParser(SharedStringsTable sst) throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
this.sharedStringsTable = sst;
parser.setContentHandler(this);
return parser;
}
private XMLReader fetchSheetParser(SharedStringsTable sst, ISaxRowRead rowRead) throws SAXException {
XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
ContentHandler handler = new SheetHandler(sst, rowRead);
parser.setContentHandler(handler);
return parser;
}