下面列出了org.w3c.dom.TypeInfo#org.xml.sax.helpers.DefaultHandler 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Starts an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the element attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.startElement(namespaceURI, localName, qName, atts);
}
else if (qName.equals(PIEDATASET_TAG)) {
this.dataset = new DefaultPieDataset();
}
else if (qName.equals(ITEM_TAG)) {
ItemHandler subhandler = new ItemHandler(this, this);
getSubHandlers().push(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the element attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.startElement(namespaceURI, localName, qName, atts);
}
else if (qName.equals(CATEGORYDATASET_TAG)) {
this.dataset = new DefaultCategoryDataset();
}
else if (qName.equals(SERIES_TAG)) {
CategorySeriesHandler subhandler = new CategorySeriesHandler(this);
getSubHandlers().push(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
else {
throw new SAXException("Element not recognised: " + qName);
}
}
private static void receiveXMLStream(final InputStream inStream,
final DefaultHandler defHandler)
throws ParserConfigurationException, SAXException, IOException {
// ...
SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser saxParser = spf.newSAXParser();
try {
AccessController.doPrivileged(new PrivilegedExceptionAction() {
public Object run() throws SAXException, IOException {
saxParser.parse(inStream, defHandler);
return null;
}
}, RESTRICTED_ACCESS_CONTROL); // From nested class
} catch (PrivilegedActionException pae) {
System.out.println("Filesystem access blocked");
pae.printStackTrace();
}
}
/**
* Starts an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the element attributes.
*
* @throws SAXException for errors.
*/
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.startElement(namespaceURI, localName, qName, atts);
}
else if (qName.equals(PIEDATASET_TAG)) {
this.dataset = new DefaultPieDataset();
}
else if (qName.equals(ITEM_TAG)) {
ItemHandler subhandler = new ItemHandler(this, this);
getSubHandlers().push(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
}
@Test
public void testCopyWriter() throws Exception {
// Create a reader from ANSI data
String ediData = EDITestData.getAnsiInterchange();
inputSource = new InputSource(new StringReader(ediData));
reader = EDIReaderFactory.createEDIReader(inputSource);
reader.setContentHandler(new DefaultHandler());
StringWriter sw = new StringWriter();
reader.setCopyWriter(sw);
reader.parse(inputSource);
// Now compare the copy to the original
assertEquals(ediData, sw.toString());
}
@Test
public void testHandlersEtc() throws Exception {
reader = EDIReaderFactory.createEDIReader(EDITestData
.getAnsiInputSource());
assertNull(reader.getDTDHandler());
assertNull(reader.getErrorHandler());
assertNull(reader.getEntityResolver());
AnEntityResolver er = new AnEntityResolver();
reader.setEntityResolver(er);
assertSame(er, reader.getEntityResolver());
ErrorHandler eh = new AnErrorHandler();
reader.setErrorHandler(eh);
assertSame(eh, reader.getErrorHandler());
ContentHandler ch = new DefaultHandler();
reader.setContentHandler(ch);
assertSame(ch, reader.getContentHandler());
BranchingWriter ackStream = new BranchingWriter(new StringWriter());
reader.setAckStream(ackStream);
assertSame(ackStream, reader.getAckStream());
}
/**
* Find the line number of a target in an Ant script, or some other line in an XML file.
* Able to find a certain element with a certain attribute matching a given value.
* See also AntTargetNode.TargetOpenCookie.
* @param file an Ant script or other XML file
* @param match the attribute value to match (e.g. target name)
* @param elementLocalName the (local) name of the element to look for
* @param elementAttributeName the name of the attribute to match on
* @return the line number (0-based), or -1 if not found
*/
static final int findLine(FileObject file, final String match, final String elementLocalName, final String elementAttributeName) throws IOException, SAXException, ParserConfigurationException {
InputSource in = new InputSource(file.toURL().toString());
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser parser = factory.newSAXParser();
final int[] line = new int[] {-1};
class Handler extends DefaultHandler {
private Locator locator;
public void setDocumentLocator(Locator l) {
locator = l;
}
public void startElement(String uri, String localname, String qname, Attributes attr) throws SAXException {
if (line[0] == -1) {
if (localname.equals(elementLocalName) && match.equals(attr.getValue(elementAttributeName))) { // NOI18N
line[0] = locator.getLineNumber() - 1;
}
}
}
}
parser.parse(in, new Handler());
return line[0];
}
public JavaLaunchConfigurationInfo(String scope) {
super();
// Since MavenRuntimeClasspathProvider will only encluding test entries when:
// 1. Launch configuration is JUnit/TestNG type
// 2. Mapped resource is in test path.
// That's why we use JUnit launch configuration here to make sure the result is right when excludeTestCode is false.
// See: {@link org.eclipse.m2e.jdt.internal.launch.MavenRuntimeClasspathProvider#getArtifactScope(ILaunchConfiguration)}
String launchXml = null;
if ("test".equals(scope)) {
launchXml = String.format(JAVA_APPLICATION_LAUNCH, "org.eclipse.jdt.junit.launchconfig");
} else {
launchXml = String.format(JAVA_APPLICATION_LAUNCH, "org.eclipse.jdt.launching.localJavaApplication");
}
try {
DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();
parser.setErrorHandler(new DefaultHandler());
StringReader reader = new StringReader(launchXml);
InputSource source = new InputSource(reader);
Element root = parser.parse(source).getDocumentElement();
initializeFromXML(root);
} catch (ParserConfigurationException | SAXException | IOException | CoreException e) {
// do nothing
}
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the <code>InputSource</code> object
* is <code>null</code>.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null");
}
XMLReader reader = this.getXMLReader();
if (dh != null) {
reader.setContentHandler(dh);
reader.setEntityResolver(dh);
reader.setErrorHandler(dh);
reader.setDTDHandler(dh);
}
reader.parse(is);
}
public static void parse(
URL xmlURL, URL schema, DefaultHandler handler)
throws SAXException, IOException, ParserConfigurationException {
InputStream xmlStream = URLHandlerRegistry.getDefault().openStream(xmlURL);
try {
InputSource inSrc = new InputSource(xmlStream);
inSrc.setSystemId(xmlURL.toExternalForm());
parse(inSrc, schema, handler);
} finally {
try {
xmlStream.close();
} catch (IOException e) {
// ignored
}
}
}
public static void parse(
InputSource xmlStream, URL schema, DefaultHandler handler)
throws SAXException, IOException, ParserConfigurationException {
InputStream schemaStream = null;
try {
if (schema != null) {
schemaStream = URLHandlerRegistry.getDefault().openStream(schema);
}
SAXParser parser = newSAXParser(schema, schemaStream);
parser.parse(xmlStream, handler);
} finally {
if (schemaStream != null) {
try {
schemaStream.close();
} catch (IOException ex) {
// ignored
}
}
}
}
/**
* The start of an element.
*
* @param namespaceURI the namespace.
* @param localName the element name.
* @param qName the element name.
* @param atts the element attributes.
*
* @throws SAXException for errors.
*/
@Override
public void startElement(String namespaceURI,
String localName,
String qName,
Attributes atts) throws SAXException {
DefaultHandler current = getCurrentHandler();
if (current != this) {
current.startElement(namespaceURI, localName, qName, atts);
}
else if (qName.equals(CATEGORYDATASET_TAG)) {
this.dataset = new DefaultCategoryDataset();
}
else if (qName.equals(SERIES_TAG)) {
CategorySeriesHandler subhandler = new CategorySeriesHandler(this);
getSubHandlers().push(subhandler);
subhandler.startElement(namespaceURI, localName, qName, atts);
}
else {
throw new SAXException("Element not recognised: " + qName);
}
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the <code>InputSource</code> object
* is <code>null</code>.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null");
}
XMLReader reader = this.getXMLReader();
if (dh != null) {
reader.setContentHandler(dh);
reader.setEntityResolver(dh);
reader.setErrorHandler(dh);
reader.setDTDHandler(dh);
}
reader.parse(is);
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the <code>InputSource</code> object
* is <code>null</code>.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null");
}
XMLReader reader = this.getXMLReader();
if (dh != null) {
reader.setContentHandler(dh);
reader.setEntityResolver(dh);
reader.setErrorHandler(dh);
reader.setDTDHandler(dh);
}
reader.parse(is);
}
/**
* Parse the content given {@link org.xml.sax.InputSource}
* as XML using the specified
* {@link org.xml.sax.helpers.DefaultHandler}.
*
* @param is The InputSource containing the content to be parsed.
* @param dh The SAX DefaultHandler to use.
*
* @throws IllegalArgumentException If the <code>InputSource</code> object
* is <code>null</code>.
* @throws IOException If any IO errors occur.
* @throws SAXException If any SAX errors occur during processing.
*
* @see org.xml.sax.DocumentHandler
*/
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException("InputSource cannot be null");
}
XMLReader reader = this.getXMLReader();
if (dh != null) {
reader.setContentHandler(dh);
reader.setEntityResolver(dh);
reader.setErrorHandler(dh);
reader.setDTDHandler(dh);
}
reader.parse(is);
}
public void testCloseReaders() throws Exception {
if (!System.getProperty("os.name").contains("Windows")) {
System.out.println("This test only needs to be run on Windows.");
return;
}
Path testFile = createTestFile(null, "Test");
System.out.println("Test file: " + testFile.toString());
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser parser = factory.newSAXParser();
try {
parser.parse(testFile.toFile(), new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
throw new SAXException("Stop the parser.");
}
});
} catch (SAXException e) {
// Do nothing
}
// deletion failes on Windows when the file is not closed
Files.deleteIfExists(testFile);
}
private void main() throws Exception {
// final File file = new File("/Users/dblevins/work/uber/geronimo-tck-public-trunk/jcdi-tck-runner/target/surefire-reports/testng-results.xml");
final File file = new File("/Users/dblevins/work/all/trunk/openejb/tck/cdi-tomee/target/failsafe-reports/testng-results.xml");
// final File file = new File("/Users/dblevins/work/uber/testng-results.xml");
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(file, new DefaultHandler() {
@Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
final String name = qName;
if ("class".equals(name)) {
classes.add(new TestClass(attributes.getValue("name")));
}
if ("test-method".equals(name)) {
classes.getLast().addStatus(attributes.getValue("status"), attributes.getValue("name"));
}
}
});
Collections.sort(classes);
textReport(file);
passingXml(file);
failingXml(file);
}
/**
* Cosntructor - pass in reference to a TransformerImpl object
*/
public TransformerHandlerImpl(TransformerImpl transformer) {
// Save the reference to the transformer
_transformer = transformer;
if (transformer.isIdentity()) {
// Set initial handler to the empty handler
_handler = new DefaultHandler();
_isIdentity = true;
}
else {
// Get a reference to the translet wrapped inside the transformer
_translet = _transformer.getTranslet();
}
}
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException();
}
if (dh != null) {
xmlReader.setContentHandler(dh);
xmlReader.setEntityResolver(dh);
xmlReader.setErrorHandler(dh);
xmlReader.setDTDHandler(dh);
xmlReader.setDocumentHandler(null);
}
xmlReader.parse(is);
}
@Override
public void process(final Exchange exchange) throws Exception {
final File inputFile = exchange.getIn().getBody(File.class);
final Integer jobId = exchange.getIn().getHeader(Constants.JOB_ID_ATTRIBUTE_NAME, Integer.class);
final JobInstance configuration = cache.getJobInstance(jobId);
if (configuration == null) {
log.error(MessageCatalog._00038_UNKNOWN_JOB_ID, jobId);
throw new IllegalArgumentException(String.valueOf(jobId));
}
final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
parser.parse(inputFile, new DefaultHandler() {
private int howManyRecords;
@Override
public void startElement(
final String uri,
final String localName,
final String qName,
final Attributes attributes) throws SAXException {
if (qName.endsWith(recordElementNameWithNamespace) || qName.equals(recordElementName)) {
howManyRecords++;
}
}
@Override
public void endDocument() throws SAXException {
log.info(MessageCatalog._00046_JOB_SIZE, jobId, howManyRecords);
final JobResource resource = jobRegistry.getJobResource(jobId);
if (resource != null) {
resource.setTotalRecordsCount(howManyRecords);
}
}
});
}
/**
* Test case to parse an XML file that not use namespaces.
*
* @param saxparser a SAXParser instance.
* @throws Exception If any errors occur.
*/
@Test(dataProvider = "parser-provider")
public void testParse30(SAXParser saxparser) throws Exception {
try (FileInputStream instream = new FileInputStream(
new File(XML_DIR, "correct.xml"))) {
saxparser.parse(new InputSource(instream), new DefaultHandler());
}
}
@Test
public void testMultithreadedSAX_CachingSAXInputSource ()
{
CommonsTestHelper.testInParallel (1000,
(IThrowingRunnable <SAXException>) () -> assertTrue (SAXReader.readXMLSAX (new CachingSAXInputSource (new ClassPathResource ("xml/buildinfo.xml")),
new SAXReaderSettings ().setContentHandler (new DefaultHandler ()))
.isSuccess ()));
}
public void load(final Properties p, InputStream in) throws IOException,
InvalidPropertiesFormatException {
if (in == null) {
throw new NullPointerException("in == null");
}
try {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(new DefaultHandler() {
private String key;
@Override
public void startElement(String uri, String localName,
String qName, Attributes attributes) throws SAXException {
key = null;
if (qName.equals("entry")) {
key = attributes.getValue("key");
}
}
@Override
public void characters(char[] ch, int start, int length)
throws SAXException {
if (key != null) {
String value = new String(ch, start, length);
p.put(key, value);
key = null;
}
}
});
reader.parse(new InputSource(in));
} catch (SAXException e) {
throw new InvalidPropertiesFormatException(e);
}
}
/**
* Cosntructor - pass in reference to a TransformerImpl object
*/
public TransformerHandlerImpl(TransformerImpl transformer) {
// Save the reference to the transformer
_transformer = transformer;
if (transformer.isIdentity()) {
// Set initial handler to the empty handler
_handler = new DefaultHandler();
_isIdentity = true;
}
else {
// Get a reference to the translet wrapped inside the transformer
_translet = _transformer.getTranslet();
}
}
public static void main(String args[]) throws Exception {
File testcases =
new File(System.getProperty("test.src", "."), "testcases");
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
DefaultHandler dh = new HostIdentifierTestHandler();
sp.parse(testcases, dh);
}
public void parse(DefaultHandler handler, InputStream is) throws ParserConfigurationException, SAXException, IOException {
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
XMLReader xmlReader = factory.newSAXParser().getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.parse(new InputSource(is));
}
@Override
public void endElement( String uri, String localName, String qName )
throws SAXException
{
super.endElement(uri, localName, qName);
for (DefaultHandler delegate : delegates) {
delegate.endElement(uri, localName, qName);
}
}
@Override
public void characters( char[] ch, int start, int length )
throws SAXException
{
super.characters(ch, start, length);
for (DefaultHandler delegate : delegates) {
delegate.characters(ch, start, length );
}
}
/**
* Loads a Configuration from an XMLFile...
*/
public void loadConfig( String XMLFile ){
try{
sectionHandling = new HashMap<String, EnumMap<SIT, EnumMap<CIT, Boolean>> >();
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser sp = factory.newSAXParser();
DefaultHandler handler = new ConfigLoader( this );
sp.parse( XMLFile, handler );
}
catch( Exception e ){
System.err.println( e );
loadConfig();
}
}
public void parse(InputSource is, DefaultHandler dh)
throws SAXException, IOException {
if (is == null) {
throw new IllegalArgumentException();
}
if (dh != null) {
xmlReader.setContentHandler(dh);
xmlReader.setEntityResolver(dh);
xmlReader.setErrorHandler(dh);
xmlReader.setDTDHandler(dh);
xmlReader.setDocumentHandler(null);
}
xmlReader.parse(is);
}