下面列出了怎么用org.xml.sax.ErrorHandler的API类实例代码及写法,或者点击链接到github查看源代码。
public void parse( InputSource source, ContentHandler handler,
ErrorHandler errorHandler, EntityResolver entityResolver )
throws SAXException, IOException {
try {
XMLReader reader = factory.newSAXParser().getXMLReader();
reader = new XMLReaderEx(reader);
reader.setContentHandler(handler);
if(errorHandler!=null)
reader.setErrorHandler(errorHandler);
if(entityResolver!=null)
reader.setEntityResolver(entityResolver);
reader.parse(source);
} catch( ParserConfigurationException e ) {
// in practice this won't happen
SAXParseException spe = new SAXParseException(e.getMessage(),null,e);
errorHandler.fatalError(spe);
throw spe;
}
}
/**
* Allow an application to register an error event handler.
*
* <p>If the application does not register an error handler, all
* error events reported by the SAX parser will be silently
* ignored; however, normal processing may not continue. It is
* highly recommended that all SAX applications implement an
* error handler to avoid unexpected bugs.</p>
*
* <p>Applications may register a new or different handler in the
* middle of a parse, and the SAX parser must begin using the new
* handler immediately.</p>
*
* @param errorHandler The error handler.
* @see #getErrorHandler
*/
public void setErrorHandler(ErrorHandler errorHandler) {
try {
XMLErrorHandler xeh = (XMLErrorHandler) fConfiguration.getProperty(ERROR_HANDLER);
if (xeh instanceof ErrorHandlerWrapper) {
ErrorHandlerWrapper ehw = (ErrorHandlerWrapper) xeh;
ehw.setErrorHandler(errorHandler);
}
else {
fConfiguration.setProperty(ERROR_HANDLER,
new ErrorHandlerWrapper(errorHandler));
}
}
catch (XMLConfigurationException e) {
// do nothing
}
}
public boolean run(Outline model, Options opt, ErrorHandler errorHandler) {
for( ClassOutline co : model.getClasses() ) {
CPluginCustomization c = co.target.getCustomizations().find(Const.NS,"code");
if(c==null)
continue; // no customization --- nothing to inject here
c.markAsAcknowledged();
// TODO: ideally you should validate this DOM element to make sure
// that there's no typo/etc. JAXP 1.3 can do this very easily.
String codeFragment = DOMUtils.getElementText(c.element);
// inject the specified code fragment into the implementation class.
co.implClass.direct(codeFragment);
}
return true;
}
private void validate(final String xsdFile, final Source src, final Result result) throws Exception {
try {
SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
Schema schema = sf.newSchema(new File(ValidatorTest.class.getResource(xsdFile).toURI()));
// Get a Validator which can be used to validate instance document
// against this grammar.
Validator validator = schema.newValidator();
ErrorHandler eh = new ErrorHandlerImpl();
validator.setErrorHandler(eh);
// Validate this instance document against the
// Instance document supplied
validator.validate(src, result);
} catch (Exception ex) {
throw ex;
}
}
@Override
public boolean run(Outline outline, Options opt, ErrorHandler errorHandler) {
for (final PackageOutline packageOutline : outline
.getAllPackageContexts()) {
final StringBuilder sb = new StringBuilder();
for (final ClassOutline classOutline : packageOutline.getClasses()) {
sb.append(CodeModelUtils.getLocalClassName(classOutline.ref));
sb.append("\n");
}
final JTextFile indexFile = new JTextFile("jaxb.index");
indexFile.setContents(sb.toString());
packageOutline._package().addResourceFile(indexFile);
}
return true;
}
protected Schema getCompiledSchema(Source[] schemas,
LSResourceResolver lsResourceResolver,
ErrorHandler errorHandler) {
Schema schema = null;
// Create a compiled Schema object.
SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
schemaFactory.setResourceResolver(lsResourceResolver);
schemaFactory.setErrorHandler(errorHandler);
try {
schema = schemaFactory.newSchema(schemas);
} catch(SAXException ex) {
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "getCompiledSchema", ex);
}
return schema;
}
public boolean run(
Outline outline,
Options opt,
ErrorHandler errorHandler ) {
for( ClassOutline ci : outline.getClasses() ) {
JDefinedClass impl = ci.implClass;
if (ci.getSuperClass() == null) {
JVar $loc = impl.field(JMod.PROTECTED, Locator.class, fieldName);
$loc.annotate(XmlLocation.class);
$loc.annotate(XmlTransient.class);
impl._implements(Locatable.class);
impl.method(JMod.PUBLIC, Locator.class, "sourceLocation").body()._return($loc);
JMethod setter = impl.method(JMod.PUBLIC, Void.TYPE, "setSourceLocation");
JVar $newLoc = setter.param(Locator.class, "newLocator");
setter.body().assign($loc, $newLoc);
}
}
return true;
}
public void writeTo(ContentHandler h, ErrorHandler errorHandler) throws SAXException {
String nsUri = av.nsUri;
String ln = av.faultDetailTag.getLocalPart();
h.startPrefixMapping("",nsUri);
h.startElement(nsUri,ln,ln,EMPTY_ATTS);
h.startElement(nsUri,wrapper,wrapper,EMPTY_ATTS);
h.characters(problemValue.toCharArray(),0,problemValue.length());
h.endElement(nsUri,wrapper,wrapper);
h.endElement(nsUri,ln,ln);
}
/**
* Called for validating a single file.
*
* @param pResolver The resolver to use for loading external entities.
* @param pValidationSet The validators configuration.
* @param pFile The file to validate.
* @throws IOException An I/O error occurred.
* @throws SAXException Parsing the file failed.
* @throws ParserConfigurationException Creating an XML parser failed.
*/
private void parse( Resolver pResolver, ValidationSet pValidationSet, File pFile , ErrorHandler errorHandler)
throws IOException, SAXException, ParserConfigurationException
{
XMLReader xr = newSAXParserFactory( pValidationSet ).newSAXParser().getXMLReader();
if ( pResolver != null )
{
xr.setEntityResolver( pResolver );
}
xr.setErrorHandler( errorHandler );
xr.parse( pFile.toURI().toURL().toExternalForm() );
}
/**
* Create a JAXP DocumentBuilder that this bean definition reader
* will use for parsing XML documents. Can be overridden in subclasses,
* adding further initialization of the builder.
* @param factory the JAXP DocumentBuilderFactory that the DocumentBuilder
* should be created with
* @param entityResolver the SAX EntityResolver to use
* @param errorHandler the SAX ErrorHandler to use
* @return the JAXP DocumentBuilder
* @throws ParserConfigurationException if thrown by JAXP methods
*/
protected DocumentBuilder createDocumentBuilder(DocumentBuilderFactory factory,
@Nullable EntityResolver entityResolver, @Nullable ErrorHandler errorHandler)
throws ParserConfigurationException {
DocumentBuilder docBuilder = factory.newDocumentBuilder();
if (entityResolver != null) {
docBuilder.setEntityResolver(entityResolver);
}
if (errorHandler != null) {
docBuilder.setErrorHandler(errorHandler);
}
return docBuilder;
}
public void parse(InputSource source, ContentHandler handler,
ErrorHandler errorHandler, EntityResolver entityResolver ) throws SAXException, IOException {
// set up the chain of handlers.
handler = wrapBy( new ExtensionBindingChecker(XMLConstants.W3C_XML_SCHEMA_NS_URI,opt,errorReceiver), handler );
handler = wrapBy( new IncorrectNamespaceURIChecker(errorReceiver), handler );
handler = wrapBy( new CustomizationContextChecker(errorReceiver), handler );
// handler = wrapBy( new VersionChecker(controller), handler );
baseParser.parse( source, handler, errorHandler, entityResolver );
}
/**
*
* @param eh Error handler to receive errors while building the schema.
*/
public SchemaBuilderImpl(ErrorHandler eh) {
this(eh,
new CascadingDatatypeLibraryFactory(new DatatypeLibraryLoader(),
new BuiltinDatatypeLibraryFactory(new DatatypeLibraryLoader())),
new SchemaPatternBuilder());
}
/**
* @see org.xml.sax.ErrorHandler#fatalError(SAXParseException)
*/
public void fatalError(SAXParseException exc) throws SAXException {
super.fatalError(exc);
m_needToCallStartDocument = false;
if (m_saxHandler instanceof ErrorHandler) {
((ErrorHandler)m_saxHandler).fatalError(exc);
}
}
/**
*
* @param eh Error handler to receive errors while building the schema.
* @param datatypeLibraryFactory This is consulted to locate datatype
* libraries.
* @param pb Used to build patterns.
*/
public SchemaBuilderImpl(ErrorHandler eh,
DatatypeLibraryFactory datatypeLibraryFactory,
SchemaPatternBuilder pb) {
this.parent = null;
this.eh = eh;
this.datatypeLibraryFactory = datatypeLibraryFactory;
this.pb = pb;
this.inheritNs = "";
this.openIncludes = null;
}
/**
*
* @param eh Error handler to receive errors while building the schema.
*/
public SchemaBuilderImpl(ErrorHandler eh) {
this(eh,
new CascadingDatatypeLibraryFactory(new DatatypeLibraryLoader(),
new BuiltinDatatypeLibraryFactory(new DatatypeLibraryLoader())),
new SchemaPatternBuilder());
}
/**
* @see org.xml.sax.ErrorHandler#fatalError(SAXParseException)
*/
public void fatalError(SAXParseException exc) throws SAXException {
super.fatalError(exc);
m_needToCallStartDocument = false;
if (m_saxHandler instanceof ErrorHandler) {
((ErrorHandler)m_saxHandler).fatalError(exc);
}
}
public void testHandlerLeak() throws Exception {
ErrorHandler handler = new DefaultHandler();
EntityResolver resolver = new DefaultHandler();
Reference<?> handlerRef = new WeakReference<Object>(handler);
Reference<?> resolverRef = new WeakReference<Object>(resolver);
XMLUtil.parse(new InputSource(new StringReader("<hello/>")), false, false, handler, resolver);
handler = null;
resolver = null;
assertGC("can collect handler", handlerRef);
assertGC("can collect resolver", resolverRef);
}
public final void writeTo(ContentHandler handler, ErrorHandler errorHandler) throws SAXException {
writeTo(handler, errorHandler, isFragment());
}
public ErrorHandler getErrorHandler() {
return _errorHandler;
}
public void setErrorHandler(ErrorHandler handler) {
logger.add("setErrorHandler", handler);
}
@Override
@Nullable
public ErrorHandler getErrorHandler() {
return this.errorHandler;
}
public void writePayloadTo(ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment) throws SAXException {
// noop
}
public void writeTo(ContentHandler contentHandler, ErrorHandler errorHandler) throws SAXException {
epr.writeTo(localName,contentHandler,errorHandler,true);
}
public ErrorHandler getErrorHandler() {
return userErrorHandler;
}
public void setErrHandler(ErrorHandler handler)
{
clientErrorHandler=handler;
}
/** Wraps the specified SAX error handler. */
public ErrorHandlerWrapper(ErrorHandler errorHandler) {
setErrorHandler(errorHandler);
}
/**
* This class is only used internally so this method should never
* be called.
*/
public void setErrorHandler(ErrorHandler handler) throws
NullPointerException
{
}
protected void writePayloadTo(ContentHandler contentHandler, ErrorHandler errorHandler, boolean fragment) throws SAXException {
throw new UnsupportedOperationException();
}
public final void writeTo(ContentHandler handler, ErrorHandler errorHandler) throws SAXException {
writeTo(handler, errorHandler, isFragment());
}
public void writeTo(ContentHandler contentHandler, ErrorHandler errorHandler) throws SAXException {
sm.writeTo(contentHandler, errorHandler);
}