下面列出了javax.xml.bind.helpers.ValidationEventLocatorImpl#javax.xml.bind.ValidationEvent 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
void reconcileID() throws SAXException {
// find objects that were not a part of the object graph
idReferencedObjects.removeAll(objectsWithId);
for( Object idObj : idReferencedObjects ) {
try {
String id = getIdFromObject(idObj);
reportError( new NotIdentifiableEventImpl(
ValidationEvent.ERROR,
Messages.DANGLING_IDREF.format(id),
new ValidationEventLocatorImpl(idObj) ) );
} catch (JAXBException e) {
// this error should have been reported already. just ignore here.
}
}
// clear the garbage
idReferencedObjects.clear();
objectsWithId.clear();
}
public boolean handleEvent( ValidationEvent event ) {
events.add(event);
boolean retVal = true;
switch( event.getSeverity() ) {
case ValidationEvent.WARNING:
retVal = true; // continue validation
break;
case ValidationEvent.ERROR:
retVal = true; // continue validation
break;
case ValidationEvent.FATAL_ERROR:
retVal = false; // halt validation
break;
default:
_assert( false,
Messages.format( Messages.UNRECOGNIZED_SEVERITY,
event.getSeverity() ) );
break;
}
return retVal;
}
/**
* Reports an error to the user, and asks if s/he wants
* to recover. If the canRecover flag is false, regardless
* of the client instruction, an exception will be thrown.
*
* Only if the flag is true and the user wants to recover from an error,
* the method returns normally.
*
* The thrown exception will be catched by the unmarshaller.
*/
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
ValidationEventHandler eventHandler = parent.getEventHandler();
boolean recover = eventHandler.handleEvent(event);
// if the handler says "abort", we will not return the object
// from the unmarshaller.getResult()
if(!recover) aborted = true;
if( !canRecover || !recover )
throw new SAXParseException2( event.getMessage(), locator,
new UnmarshalException(
event.getMessage(),
event.getLinkedException() ) );
}
/**
* Reports an error to the user, and asks if s/he wants
* to recover. If the canRecover flag is false, regardless
* of the client instruction, an exception will be thrown.
*
* Only if the flag is true and the user wants to recover from an error,
* the method returns normally.
*
* The thrown exception will be catched by the unmarshaller.
*/
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
ValidationEventHandler eventHandler = parent.getEventHandler();
boolean recover = eventHandler.handleEvent(event);
// if the handler says "abort", we will not return the object
// from the unmarshaller.getResult()
if(!recover) aborted = true;
if( !canRecover || !recover )
throw new SAXParseException2( event.getMessage(), locator,
new UnmarshalException(
event.getMessage(),
event.getLinkedException() ) );
}
public void serializeRoot(BeanT bean, XMLSerializer target) throws SAXException, IOException, XMLStreamException {
if(tagName==null) {
Class beanClass = bean.getClass();
String message;
if (beanClass.isAnnotationPresent(XmlRootElement.class)) {
message = Messages.UNABLE_TO_MARSHAL_UNBOUND_CLASS.format(beanClass.getName());
} else {
message = Messages.UNABLE_TO_MARSHAL_NON_ELEMENT.format(beanClass.getName());
}
target.reportError(new ValidationEventImpl(ValidationEvent.ERROR,message,null, null));
} else {
target.startElement(tagName,bean);
target.childAsSoleContent(bean,null);
target.endElement();
if (retainPropertyInfo) {
target.currentProperty.remove();
}
}
}
public String onIDREF( Object obj ) throws SAXException {
String id;
try {
id = getIdFromObject(obj);
} catch (JAXBException e) {
reportError(null,e);
return null; // recover by returning null
}
idReferencedObjects.add(obj);
if(id==null) {
reportError( new NotIdentifiableEventImpl(
ValidationEvent.ERROR,
Messages.NOT_IDENTIFIABLE.format(),
new ValidationEventLocatorImpl(obj) ) );
}
return id;
}
public String print(XMLGregorianCalendar cal) {
XMLSerializer xs = XMLSerializer.getInstance();
QName type = xs.getSchemaType();
if (type != null) {
try {
checkXmlGregorianCalendarFieldRef(type, cal);
String format = xmlGregorianCalendarFormatString.get(type);
if (format != null) {
return format(format, cal);
}
} catch (javax.xml.bind.MarshalException e) {
// see issue 649
xs.handleEvent(new ValidationEventImpl(ValidationEvent.WARNING, e.getMessage(),
xs.getCurrentLocation(null) ));
return "";
}
}
return cal.toXMLFormat();
}
public boolean handleEvent( ValidationEvent event ) {
events.add(event);
boolean retVal = true;
switch( event.getSeverity() ) {
case ValidationEvent.WARNING:
retVal = true; // continue validation
break;
case ValidationEvent.ERROR:
retVal = true; // continue validation
break;
case ValidationEvent.FATAL_ERROR:
retVal = false; // halt validation
break;
default:
_assert( false,
Messages.format( Messages.UNRECOGNIZED_SEVERITY,
event.getSeverity() ) );
break;
}
return retVal;
}
/**
* Reports an error to the user, and asks if s/he wants
* to recover. If the canRecover flag is false, regardless
* of the client instruction, an exception will be thrown.
*
* Only if the flag is true and the user wants to recover from an error,
* the method returns normally.
*
* The thrown exception will be catched by the unmarshaller.
*/
public void handleEvent(ValidationEvent event, boolean canRecover ) throws SAXException {
ValidationEventHandler eventHandler = parent.getEventHandler();
boolean recover = eventHandler.handleEvent(event);
// if the handler says "abort", we will not return the object
// from the unmarshaller.getResult()
if(!recover) aborted = true;
if( !canRecover || !recover )
throw new SAXParseException2( event.getMessage(), locator,
new UnmarshalException(
event.getMessage(),
event.getLinkedException() ) );
}
public String onIDREF( Object obj ) throws SAXException {
String id;
try {
id = getIdFromObject(obj);
} catch (JAXBException e) {
reportError(null,e);
return null; // recover by returning null
}
idReferencedObjects.add(obj);
if(id==null) {
reportError( new NotIdentifiableEventImpl(
ValidationEvent.ERROR,
Messages.NOT_IDENTIFIABLE.format(),
new ValidationEventLocatorImpl(obj) ) );
}
return id;
}
@Override
public boolean handleEvent(ValidationEvent event) {
StringBuilder msg = new StringBuilder();
LogLevel type;
switch (event.getSeverity()) {
case ValidationEvent.FATAL_ERROR:
case ValidationEvent.ERROR:
msg.append("Invalid content");
type = LogLevel.ERROR;
break;
case ValidationEvent.WARNING:
msg.append("Warning");
type = LogLevel.WARN;
break;
default:
return reportAllErrors;
}
msg.append(": ").append(event.getMessage());
log.log(type, msg.toString());
validationErrors++;
return reportAllErrors;
}
public String print(XMLGregorianCalendar cal) {
XMLSerializer xs = XMLSerializer.getInstance();
QName type = xs.getSchemaType();
if (type != null) {
try {
checkXmlGregorianCalendarFieldRef(type, cal);
String format = xmlGregorianCalendarFormatString.get(type);
if (format != null) {
return format(format, cal);
}
} catch (javax.xml.bind.MarshalException e) {
// see issue 649
xs.handleEvent(new ValidationEventImpl(ValidationEvent.WARNING, e.getMessage(),
xs.getCurrentLocation(null) ));
return "";
}
}
return cal.toXMLFormat();
}
public boolean handleEvent( ValidationEvent event ) {
if( event == null ) {
throw new IllegalArgumentException();
}
// calculate the severity prefix and return value
String severity = null;
boolean retVal = false;
switch ( event.getSeverity() ) {
case ValidationEvent.WARNING:
severity = Messages.format( Messages.WARNING );
retVal = true; // continue after warnings
break;
case ValidationEvent.ERROR:
severity = Messages.format( Messages.ERROR );
retVal = false; // terminate after errors
break;
case ValidationEvent.FATAL_ERROR:
severity = Messages.format( Messages.FATAL_ERROR );
retVal = false; // terminate after fatal errors
break;
default:
assert false :
Messages.format( Messages.UNRECOGNIZED_SEVERITY,
event.getSeverity() );
}
// calculate the location message
String location = getLocation( event );
System.out.println(
Messages.format( Messages.SEVERITY_MESSAGE,
severity,
event.getMessage(),
location ) );
// fail on the first error or fatal error
return retVal;
}
/**
* Set the severity field of this event.
*
* @param _severity Must be one of ValidationEvent.WARNING,
* ValidationEvent.ERROR, or ValidationEvent.FATAL_ERROR.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public void setSeverity( int _severity ) {
if( _severity != ValidationEvent.WARNING &&
_severity != ValidationEvent.ERROR &&
_severity != ValidationEvent.FATAL_ERROR ) {
throw new IllegalArgumentException(
Messages.format( Messages.ILLEGAL_SEVERITY ) );
}
this.severity = _severity;
}
public Base64Data print(Image v) {
ByteArrayOutputStreamEx imageData = new ByteArrayOutputStreamEx();
XMLSerializer xs = XMLSerializer.getInstance();
String mimeType = xs.getXMIMEContentType();
if(mimeType==null || mimeType.startsWith("image/*"))
// because PNG is lossless, it's a good default
//
// mime type can be a range, in which case we can't just pass that
// to ImageIO.getImageWritersByMIMEType, so here I'm just assuming
// the default of PNG. Not sure if this is complete.
mimeType = "image/png";
try {
Iterator<ImageWriter> itr = ImageIO.getImageWritersByMIMEType(mimeType);
if(itr.hasNext()) {
ImageWriter w = itr.next();
ImageOutputStream os = ImageIO.createImageOutputStream(imageData);
w.setOutput(os);
w.write(convertToBufferedImage(v));
os.close();
w.dispose();
} else {
// no encoder
xs.handleEvent(new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.NO_IMAGE_WRITER.format(mimeType),
xs.getCurrentLocation(null) ));
// TODO: proper error reporting
throw new RuntimeException("no encoder for MIME type "+mimeType);
}
} catch (IOException e) {
xs.handleError(e);
// TODO: proper error reporting
throw new RuntimeException(e);
}
Base64Data bd = new Base64Data();
imageData.set(bd,mimeType);
return bd;
}
public boolean handleEvent(ValidationEvent event) {
try {
return marshaller.getEventHandler().handleEvent(event);
} catch (JAXBException e) {
// impossible
throw new Error(e);
}
}
public boolean handleEvent( ValidationEvent event ) {
if( event == null ) {
throw new IllegalArgumentException();
}
// calculate the severity prefix and return value
String severity = null;
boolean retVal = false;
switch ( event.getSeverity() ) {
case ValidationEvent.WARNING:
severity = Messages.format( Messages.WARNING );
retVal = true; // continue after warnings
break;
case ValidationEvent.ERROR:
severity = Messages.format( Messages.ERROR );
retVal = false; // terminate after errors
break;
case ValidationEvent.FATAL_ERROR:
severity = Messages.format( Messages.FATAL_ERROR );
retVal = false; // terminate after fatal errors
break;
default:
assert false :
Messages.format( Messages.UNRECOGNIZED_SEVERITY,
event.getSeverity() );
}
// calculate the location message
String location = getLocation( event );
System.out.println(
Messages.format( Messages.SEVERITY_MESSAGE,
severity,
event.getMessage(),
location ) );
// fail on the first error or fatal error
return retVal;
}
public static void reportError(String msg, Exception nested, boolean canRecover) throws SAXException {
UnmarshallingContext context = UnmarshallingContext.getInstance();
context.handleEvent( new ValidationEventImpl(
canRecover? ValidationEvent.ERROR : ValidationEvent.FATAL_ERROR,
msg,
context.getLocator().getLocation(),
nested ), canRecover );
}
@Override
public boolean handleEvent(final ValidationEvent event) {
errorStream.print(String.format("%s line %d col %d %s", severityToString(event.getSeverity()),
event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
event.getMessage()));
return event.getSeverity() == ValidationEvent.WARNING;
}
@Override
public boolean handleEvent(final ValidationEvent event) {
errorStream.print(String.format("%s line %d col %d %s", severityToString(event.getSeverity()),
event.getLocator().getLineNumber(), event.getLocator().getColumnNumber(),
event.getMessage()));
return event.getSeverity() == ValidationEvent.WARNING;
}
public final boolean handleEvent (@Nonnull final ValidationEvent aEvent)
{
final IErrorLevel aErrorLevel = getErrorLevel (aEvent.getSeverity ());
final SingleErrorBuilder aErrBuilder = SingleError.builder ().setErrorLevel (aErrorLevel);
final ValidationEventLocator aLocator = aEvent.getLocator ();
aErrBuilder.setErrorLocation (new SimpleLocation (getLocationResourceID (aLocator),
aLocator != null ? aLocator.getLineNumber ()
: ILocation.ILLEGAL_NUMBER,
aLocator != null ? aLocator.getColumnNumber ()
: ILocation.ILLEGAL_NUMBER))
.setErrorFieldName (getErrorFieldName (aLocator));
// Message may be null in some cases (e.g. when a linked exception is
// present), but is not allowed to be null!
String sMsg = aEvent.getMessage ();
if (sMsg == null)
{
if (aEvent.getLinkedException () != null)
{
sMsg = aEvent.getLinkedException ().getMessage ();
if (sMsg == null)
sMsg = "Exception";
}
else
{
// Does this ever happen????
sMsg = "Validation event";
}
}
aErrBuilder.setErrorText (sMsg).setLinkedException (aEvent.getLinkedException ());
// call our callback
onEvent (aErrBuilder.build ());
// Continue processing?
return continueProcessing (aErrorLevel);
}
/**
* Pushes the object to {@link #cycleDetectionStack} and also
* detect any cycles.
*
* When a cycle is found, this method tries to recover from it.
*
* @return
* the object that should be marshalled instead of the given <tt>obj</tt>,
* or null if the error is found and we need to avoid marshalling this object
* to prevent infinite recursion. When this method returns null, the error
* has already been reported.
*/
private Object pushObject(Object obj, String fieldName) throws SAXException {
if(!cycleDetectionStack.push(obj))
return obj;
// allow the object to nominate its replacement
if(obj instanceof CycleRecoverable) {
obj = ((CycleRecoverable)obj).onCycleDetected(new CycleRecoverable.Context(){
public Marshaller getMarshaller() {
return marshaller;
}
});
if(obj!=null) {
// object nominated its replacement.
// we still need to make sure that the nominated.
// this may cause inifinite recursion on its own.
cycleDetectionStack.pop();
return pushObject(obj,fieldName);
} else
return null;
}
// cycle detected and no one is catching the error.
reportError(new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.CYCLE_IN_MARSHALLER.format(cycleDetectionStack.getCycleString()),
getCurrentLocation(fieldName),
null));
return null;
}
/**
* Called when there's no corresponding ID value.
*/
public void errorUnresolvedIDREF(Object bean, String idref, LocatorEx loc) throws SAXException {
handleEvent( new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.UNRESOLVED_IDREF.format(idref),
loc.getLocation()), true );
}
public boolean handleError(Exception e,Object source,String fieldName) {
return handleEvent(
new ValidationEventImpl(
ValidationEvent.ERROR,
e.getMessage(),
new ValidationEventLocatorExImpl(source,fieldName),
e));
}
public boolean handleEvent(ValidationEvent event) {
try {
return marshaller.getEventHandler().handleEvent(event);
} catch (JAXBException e) {
// impossible
throw new Error(e);
}
}
private void reportMissingObjectError(String fieldName) throws SAXException {
reportError(new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.MISSING_OBJECT.format(fieldName),
getCurrentLocation(fieldName),
new NullPointerException() ));
}
/**
* Set the severity field of this event.
*
* @param _severity Must be one of ValidationEvent.WARNING,
* ValidationEvent.ERROR, or ValidationEvent.FATAL_ERROR.
* @throws IllegalArgumentException if an illegal severity field is supplied
*/
public void setSeverity( int _severity ) {
if( _severity != ValidationEvent.WARNING &&
_severity != ValidationEvent.ERROR &&
_severity != ValidationEvent.FATAL_ERROR ) {
throw new IllegalArgumentException(
Messages.format( Messages.ILLEGAL_SEVERITY ) );
}
this.severity = _severity;
}
public final void serializeRoot(BeanT bean, XMLSerializer target) throws SAXException, IOException, XMLStreamException {
if(tagName==null) {
target.reportError(
new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.UNABLE_TO_MARSHAL_NON_ELEMENT.format(bean.getClass().getName()),
null,
null));
}
else {
target.startElement(tagName,bean);
target.childAsSoleContent(bean,null);
target.endElement();
}
}
/**
* Pushes the object to {@link #cycleDetectionStack} and also
* detect any cycles.
*
* When a cycle is found, this method tries to recover from it.
*
* @return
* the object that should be marshalled instead of the given <tt>obj</tt>,
* or null if the error is found and we need to avoid marshalling this object
* to prevent infinite recursion. When this method returns null, the error
* has already been reported.
*/
private Object pushObject(Object obj, String fieldName) throws SAXException {
if(!cycleDetectionStack.push(obj))
return obj;
// allow the object to nominate its replacement
if(obj instanceof CycleRecoverable) {
obj = ((CycleRecoverable)obj).onCycleDetected(new CycleRecoverable.Context(){
public Marshaller getMarshaller() {
return marshaller;
}
});
if(obj!=null) {
// object nominated its replacement.
// we still need to make sure that the nominated.
// this may cause inifinite recursion on its own.
cycleDetectionStack.pop();
return pushObject(obj,fieldName);
} else
return null;
}
// cycle detected and no one is catching the error.
reportError(new ValidationEventImpl(
ValidationEvent.ERROR,
Messages.CYCLE_IN_MARSHALLER.format(cycleDetectionStack.getCycleString()),
getCurrentLocation(fieldName),
null));
return null;
}
/**
* Calculate a location message for the event
*
*/
private String getLocation(ValidationEvent event) {
StringBuffer msg = new StringBuffer();
ValidationEventLocator locator = event.getLocator();
if( locator != null ) {
URL url = locator.getURL();
Object obj = locator.getObject();
Node node = locator.getNode();
int line = locator.getLineNumber();
if( url!=null || line!=-1 ) {
msg.append( "line " + line );
if( url!=null )
msg.append( " of " + url );
} else if( obj != null ) {
msg.append( " obj: " + obj.toString() );
} else if( node != null ) {
msg.append( " node: " + node.toString() );
}
} else {
msg.append( Messages.format( Messages.LOCATION_UNAVAILABLE ) );
}
return msg.toString();
}