下面列出了javax.xml.parsers.SAXParserFactory#newSAXParser ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Extract coverage data from a JaCoCo XML report file.
*
* @param xml the JaCoCo XML report file.
* @return the coverage data of each Java class registered in the JaCoCo XML report.
* @throws ParserConfigurationException if an error occurs during the parsing of the JaCoCo XML report.
* @throws SAXException if an error occurs during the parsing of the JaCoCo XML report.
* @throws IOException if an error occurs during the parsing of the JaCoCo XML report.
*/
public static Map<String, JavaClass> getCoverageData(File xml)
throws ParserConfigurationException,
SAXException,
IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setFeature("http://xml.org/sax/features/validation", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-dtd-grammar", false);
factory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
factory.setFeature("http://xml.org/sax/features/external-general-entities", false);
factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
SAXParser saxParser = factory.newSAXParser();
JaCoCoXmlReportParser handler = new JaCoCoXmlReportParser();
saxParser.parse(xml, handler);
return handler.getClasses();
}
public ArrayList<BeerStyle> getStylesFromXml(String filePath) throws IOException {
ArrayList<BeerStyle> list = new ArrayList<BeerStyle>();
BeerXmlReader myXMLHandler = new BeerXmlReader();
SAXParserFactory spf = SAXParserFactory.newInstance();
try {
SAXParser sp = spf.newSAXParser();
InputStream is = mContext.getAssets().open(filePath);
sp.parse(is, myXMLHandler);
list.addAll(myXMLHandler.getBeerStyles());
} catch (Exception e) {
Log.e("getStylesFromXml", e.toString());
}
return list;
}
/**
* Test an identity transform of an XML document with NS decls using a
* non-ns-aware parser. Output result to a StreamSource. Set ns-awareness to
* TRUE and prefixes to TRUE.
*/
@Test
public void testXMLNoNsAwareStreamResult4() {
try {
// Create SAX parser *without* enabling ns
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true); // Same as default
spf.setFeature("http://xml.org/sax/features/namespace-prefixes", true);
SAXParser sp = spf.newSAXParser();
// Make sure that the output is well formed
String xml = runTransform(sp);
checkWellFormedness(xml);
} catch (Throwable ex) {
Assert.fail(ex.toString());
}
}
/**
* Loads routes from file
*
* @param file valid <code>File</code> with routes
* @return <code>List</code> of <code>Route</code>s
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static List<Route> loadRoutesFromFile(final File file) throws SAXException, IOException, ParserConfigurationException
{
List<Route> routes = new ArrayList<Route>();
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = null;
parser = factory.newSAXParser();
parser.parse(file, new GpxParser(file.getName(), null, null, routes));
if (routes.size() > 0)
{
routes.get(0).filepath = file.getCanonicalPath();
}
return routes;
}
/**
* Reads a {@link CategoryDataset} from a stream.
*
* @param in the stream.
*
* @return A dataset.
*
* @throws IOException if there is a problem reading the file.
*/
public static CategoryDataset readCategoryDatasetFromXML(InputStream in)
throws IOException {
CategoryDataset result = null;
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
CategoryDatasetHandler handler = new CategoryDatasetHandler();
parser.parse(in, handler);
result = handler.getDataset();
}
catch (SAXException e) {
System.out.println(e.getMessage());
}
catch (ParserConfigurationException e2) {
System.out.println(e2.getMessage());
}
return result;
}
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();
}
public static Puzzle readPuzzle(InputStream is) {
Puzzle puz = new Puzzle();
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser parser = factory.newSAXParser();
// parser.setProperty("http://xml.org/sax/features/validation",
// false);
XMLReader xr = parser.getXMLReader();
xr.setContentHandler(new JPZXMLParser(puz));
xr.parse(new InputSource(unzipOrPassthrough(is)));
puz.setVersion(IO.VERSION_STRING);
} catch (Exception e) {
e.printStackTrace();
System.err.println("Unable to parse XML file: " + e.getMessage());
throw new RuntimeException(e);
}
return puz;
}
public static void main(String[] args) throws Exception {
if (args.length != 2 && args.length != 3) {
usage();
exit(-1);
}
String mtEvalFn = args[0];
String outputFn = args[1];
String genre = args.length == 3 ? args[2] : null;
SAXParserFactory saxpf = SAXParserFactory.newInstance();
SAXParser saxParser = saxpf.newSAXParser();
saxParser.parse(new File(mtEvalFn), new MTEvalContentHandler(outputFn, genre));
}
public static WsdlServiceHandler parse(String wsdlUrl) throws ParserConfigurationException, SAXException, IOException {
WsdlServiceHandler handler = new WsdlServiceHandler();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(wsdlUrl, handler);
return handler;
}
@Override
public void prepare() throws Exception {
super.prepare();
checkState(content == null);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
try (InputStream input = new BufferedInputStream(new FileInputStream(file))) {
try (OutputStream output = new BufferedOutputStream(stream)) {
StreamSource styleSource = new StreamSource(new StringReader(stylesheet));
TransformerFactory transformerFactory = SafeXml.newTransformerFactory();
Transformer transformer = transformerFactory.newTransformer(styleSource);
SAXParserFactory parserFactory = SafeXml.newSaxParserFactory();
parserFactory.setNamespaceAware(true);
SAXParser parser = parserFactory.newSAXParser();
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_DTD, "");
parser.setProperty(XMLConstants.ACCESS_EXTERNAL_SCHEMA, "");
XMLReader reader = parser.getXMLReader();
reader.setFeature("http://apache.org/xml/features/disallow-doctype-decl", false);
reader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
transformer.transform(new SAXSource(reader, new InputSource(input)), new StreamResult(output));
}
}
content = stream.toByteArray();
}
public void fillPermissions(DataLogicSystem dlSystem) {
// inicializamos los permisos
m_apermissions = new HashSet<>();
// Y lo que todos tienen permisos
m_apermissions.add("com.openbravo.pos.forms.JPanelMenu");
m_apermissions.add("Menu.Exit");
String sRolePermisions = dlSystem.findRolePermissions(m_sRole);
if (sRolePermisions != null) {
try {
if (m_sp == null) {
SAXParserFactory spf = SAXParserFactory.newInstance();
m_sp = spf.newSAXParser();
}
m_sp.parse(new InputSource(new StringReader(sRolePermisions)), new ConfigurationHandler());
} catch (ParserConfigurationException ePC) {
logger.log(Level.WARNING, LocalRes.getIntString("exception.parserconfig"), ePC);
} catch (SAXException eSAX) {
logger.log(Level.WARNING, LocalRes.getIntString("exception.xmlfile"), eSAX);
} catch (IOException eIO) {
logger.log(Level.WARNING, LocalRes.getIntString("exception.iofile"), eIO);
}
}
}
/**
* Action performed.
*
* @param event the event
* @see java.awt.event.ActionListener#actionPerformed(ActionEvent)
*/
@Override
public void actionPerformed(ActionEvent event) {
JFileChooser fileChooser = new JFileChooser();
fileChooser.setDialogTitle("Open XCAS file");
if (this.main.getXcasFileOpenDir() != null) {
fileChooser.setCurrentDirectory(this.main.getXcasFileOpenDir());
}
int rc = fileChooser.showOpenDialog(this.main);
if (rc == JFileChooser.APPROVE_OPTION) {
File xcasFile = fileChooser.getSelectedFile();
if (xcasFile.exists() && xcasFile.isFile()) {
try {
this.main.setXcasFileOpenDir(xcasFile.getParentFile());
Timer time = new Timer();
time.start();
SAXParserFactory saxParserFactory = XMLUtils.createSAXParserFactory();
SAXParser parser = saxParserFactory.newSAXParser();
XCASDeserializer xcasDeserializer = new XCASDeserializer(this.main.getCas()
.getTypeSystem());
this.main.getCas().reset();
parser.parse(xcasFile, xcasDeserializer.getXCASHandler(this.main.getCas()));
time.stop();
this.main.handleSofas();
this.main.setTitle("XCAS");
this.main.updateIndexTree(true);
this.main.setRunOnCasEnabled();
this.main.setEnableCasFileReadingAndWriting();
this.main.setStatusbarMessage("Done loading XCAS file in " + time.getTimeSpan() + ".");
} catch (Exception e) {
e.printStackTrace();
this.main.handleException(e);
}
}
}
}
/**
* <p>
* Set the customizable SAX Parser Service Properties.
*
* <p>
* This method attempts to instantiate a validating parser and a namespace
* aware parser to determine if the parser can support those features. The
* appropriate properties are then set in the specified properties object.
*
* <p>
* This method can be overridden to add additional SAX2 features and
* properties. If you want to be able to filter searches of the OSGi service
* registry, this method must put a key, value pair into the properties
* object for each feature or property. For example,
*
* properties.put("http://www.acme.com/features/foo", Boolean.TRUE);
*
* @param factory - the SAXParserFactory object
* @param properties - the properties object for the service
*/
public void setSAXProperties(SAXParserFactory factory, Hashtable properties) {
// check if this parser can be configured to validate
boolean validating = true;
factory.setValidating(true);
factory.setNamespaceAware(false);
try {
factory.newSAXParser();
}
catch (Exception pce_val) {
validating = false;
}
// check if this parser can be configured to be namespaceaware
boolean namespaceaware = true;
factory.setValidating(false);
factory.setNamespaceAware(true);
try {
factory.newSAXParser();
}
catch (Exception pce_nsa) {
namespaceaware = false;
}
// set the factory values
factory.setValidating(validating);
factory.setNamespaceAware(namespaceaware);
// set the OSGi service properties
properties.put(PARSER_NAMESPACEAWARE, new Boolean(namespaceaware));
properties.put(PARSER_VALIDATING, new Boolean(validating));
}
public static void main(String[] args) throws Throwable {
System.setSecurityManager(new SecurityManager());
try {
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
spf.setValidating(true);
SAXParser sp = spf.newSAXParser();
// The following line shouldn't throw a
// java.security.AccessControlException.
sp.setProperty("foo", "bar");
} catch (SAXNotRecognizedException e) {
// Ignore this expected exception.
}
}
/**
* @see java.lang.Runnable#run()
*/
public void run() {
setStatus(TaskStatus.PROCESSING);
logger.info("Started parsing file " + file);
// Use the default (non-validating) parser
SAXParserFactory factory = SAXParserFactory.newInstance();
try {
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(file, handler);
// Close file
finalRawDataFile = newMZmineFile.finishWriting();
project.addFile(finalRawDataFile);
} catch (Throwable e) {
e.printStackTrace();
/* we may already have set the status to CANCELED */
if (getStatus() == TaskStatus.PROCESSING) {
setStatus(TaskStatus.ERROR);
setErrorMessage(ExceptionUtils.exceptionToString(e));
}
return;
}
if (parsedScans == 0) {
setStatus(TaskStatus.ERROR);
setErrorMessage("No scans found");
return;
}
logger.info(
"Finished parsing " + file + ", parsed " + parsedScans + " of " + totalScans + " scans");
setStatus(TaskStatus.FINISHED);
}
@Test
public void testParse() throws ParserConfigurationException, SAXException, IOException {
String file = getClass().getResource("Bug6608841.xml").getFile();
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser parser = spf.newSAXParser();
parser.parse(new File(file), new MyHandler());
}
/**
* Setting the EntityExpansion Limit to 128000 and checks if the XML
* document that has more than two levels of entity expansion is parsed or
* not. Previous system property was changed to jdk.xml.entityExpansionLimit
* see http://docs.oracle.com/javase/tutorial/jaxp/limits/limits.html.
*
* @throws Exception If any errors occur.
*/
@Test
public void testEntityExpansionSAXPos() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
// Secure processing will limit XML processing to conform to
// implementation limits.
factory.setFeature(FEATURE_SECURE_PROCESSING, true);
// Set entityExpansionLimit as 2 should expect fatalError
setSystemProperty(SP_ENTITY_EXPANSION_LIMIT, String.valueOf(128000));
SAXParser parser = factory.newSAXParser();
MyErrorHandler fatalHandler = new MyErrorHandler();
parser.parse(new File(ENTITY_XML), fatalHandler);
assertFalse(fatalHandler.isAnyError());
}
public CmsConfiguration readConfiguration(InputStream is) throws Exception
{
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setNamespaceAware(true);
SAXParser saxParser = spf.newSAXParser();
XMLReader xmlReader = saxParser.getXMLReader();
XMLConfigContentHandler contentHandler = new XMLConfigContentHandler();
xmlReader.setContentHandler(contentHandler);
xmlReader.parse(new InputSource(is));
return contentHandler.getConfiguration();
}
/**
* Entry point for log file parsing with a file reader.
* {@see #parse(String,boolean)}
*/
public static ArrayList<LogEvent> parse(Reader reader, boolean cleanup) throws Exception {
// Create the XML input factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// Create the XML LogEvent reader
SAXParser p = factory.newSAXParser();
if (cleanup) {
// some versions of the log have slightly malformed XML, so clean it
// up before passing it to SAX
reader = new LogCleanupReader(reader);
}
LogParser log = new LogParser();
try {
p.parse(new InputSource(reader), log);
} catch (Throwable th) {
th.printStackTrace();
// Carry on with what we've got...
}
// Associate compilations with their NMethods and other kinds of events
for (LogEvent e : log.events) {
if (e instanceof BasicLogEvent) {
BasicLogEvent ble = (BasicLogEvent) e;
Compilation c = log.compiles.get(ble.getId());
if (c == null) {
if (!(ble instanceof NMethod)) {
throw new InternalError("only nmethods should have a null compilation, here's a " + ble.getClass());
}
continue;
}
ble.setCompilation(c);
if (ble instanceof NMethod) {
c.setNMethod((NMethod) ble);
}
}
}
return log.events;
}
void parse() throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
XMLReader reader = parser.getXMLReader();
reader.setContentHandler(new LiveContentHandler());
reader.parse(new InputSource(new ByteArrayInputStream(null)));
}