下面列出了怎么用javax.xml.bind.ValidationEventHandler的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 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 reportError( ValidationEvent ve ) throws SAXException {
ValidationEventHandler handler;
try {
handler = marshaller.getEventHandler();
} catch( JAXBException e ) {
throw new SAXException2(e);
}
if(!handler.handleEvent(ve)) {
if(ve.getLinkedException() instanceof Exception)
throw new SAXException2((Exception)ve.getLinkedException());
else
throw new SAXException2(ve.getMessage());
}
}
/**
* @param aClassLoader
* The class loader to be used for XML schema resolving. May be
* <code>null</code>.
* @return The JAXB unmarshaller to use. Never <code>null</code>.
* @throws JAXBException
* In case the creation fails.
*/
@Nonnull
private Unmarshaller _createUnmarshaller (@Nullable final ClassLoader aClassLoader) throws JAXBException
{
final JAXBContext aJAXBContext = getJAXBContext (aClassLoader);
// create an Unmarshaller
final Unmarshaller aUnmarshaller = aJAXBContext.createUnmarshaller ();
if (m_aVEHFactory != null)
{
// Create and set a new event handler
final ValidationEventHandler aEvHdl = m_aVEHFactory.apply (aUnmarshaller.getEventHandler ());
if (aEvHdl != null)
aUnmarshaller.setEventHandler (aEvHdl);
}
// Set XSD (if any)
final Schema aValidationSchema = createValidationSchema ();
if (aValidationSchema != null)
aUnmarshaller.setSchema (aValidationSchema);
return aUnmarshaller;
}
/**
* 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() ) );
}
@Nonnull
private static javax.xml.bind.Marshaller marshallerFor(@Nonnull TestSuites element) {
final javax.xml.bind.Marshaller marshaller;
try {
marshaller = JAXB_CONTEXT.createMarshaller();
marshaller.setProperty(JAXB_FORMATTED_OUTPUT, true);
marshaller.setEventHandler(new ValidationEventHandler() {
@Override
public boolean handleEvent(ValidationEvent event) {
return true;
}
});
} catch (final Exception e) {
throw new RuntimeException("Could not create marshaller to marshall " + element + ".", e);
}
return marshaller;
}
public <T> String writeXml(final T model, final Schema schema, final ValidationEventHandler handler) {
if (model == null) {
throw new ConversionExeption("Can not serialize null");
}
try ( final StringWriter w = new StringWriter() ) {
final JAXBIntrospector introspector = getJaxbContext().createJAXBIntrospector();
final Marshaller marshaller = getJaxbContext().createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
marshaller.setSchema(schema);
marshaller.setEventHandler(handler);
final XMLOutputFactory xof = XMLOutputFactory.newFactory();
final XMLStreamWriter xmlStreamWriter = xof.createXMLStreamWriter(w);
if (null == introspector.getElementName(model)) {
final JAXBElement jaxbElement = new JAXBElement(createQName(model), model.getClass(), model);
marshaller.marshal(jaxbElement, xmlStreamWriter);
} else {
marshaller.marshal(model, xmlStreamWriter);
}
xmlStreamWriter.flush();
return w.toString();
} catch (final JAXBException | IOException | XMLStreamException e) {
throw new ConversionExeption(String.format("Error serializing Object %s", model.getClass().getName()), e);
}
}
protected ValidationEventHandler getValidationEventHandler(String cn) {
try {
return (ValidationEventHandler)ClassLoaderUtils.loadClass(cn, getClass()).newInstance();
} catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) {
LOG.log(Level.INFO, "Could not create validation event handler", e);
}
return null;
}
public void setErrorHandler(ValidationEventHandler handler) {
try {
unmarshaller.setEventHandler(handler);
marshaller.setEventHandler(handler);
} catch (JAXBException e) {
// impossible
throw new Error(e);
}
}
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean logErrors) throws ParserConfigurationException, SAXException, JAXBException {
final InputSource inputSource = new InputSource(in);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
final SAXParser parser = factory.newSAXParser();
final JAXBContext ctx = getContext(type);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
if (logErrors) {
System.out.println(validationEvent);
}
return false;
}
});
unmarshaller.setListener(new Unmarshaller.Listener() {
public void afterUnmarshal(final Object object, final Object object1) {
super.afterUnmarshal(object, object1);
}
public void beforeUnmarshal(final Object target, final Object parent) {
super.beforeUnmarshal(target, parent);
}
});
final NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
final SAXSource source = new SAXSource(xmlFilter, inputSource);
return unmarshaller.unmarshal(source, type);
}
public void setErrorHandler(ValidationEventHandler handler) {
try {
unmarshaller.setEventHandler(handler);
marshaller.setEventHandler(handler);
} catch (JAXBException e) {
// impossible
throw new Error(e);
}
}
/**
* @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
*/
public void setEventHandler(ValidationEventHandler handler)
throws JAXBException {
if( handler == null ) {
eventHandler = new DefaultValidationEventHandler();
} else {
eventHandler = handler;
}
}
private DataWriterImpl<XMLStreamWriter> newDataWriter(ValidationEventHandler handler) throws Exception {
JAXBDataBinding db = getTestWriterFactory();
DataWriterImpl<XMLStreamWriter> dw = (DataWriterImpl<XMLStreamWriter>)db.createWriter(XMLStreamWriter.class);
assertNotNull(dw);
// Build message to set custom event handler
org.apache.cxf.message.Message message = new org.apache.cxf.message.MessageImpl();
message.put(JAXBDataBinding.WRITER_VALIDATION_EVENT_HANDLER, handler);
dw.setProperty("org.apache.cxf.message.Message", message);
return dw;
}
/**
* @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
*/
public void setEventHandler(ValidationEventHandler handler)
throws JAXBException {
if( handler == null ) {
eventHandler = new DefaultValidationEventHandler();
} else {
eventHandler = handler;
}
}
public void setErrorHandler(ValidationEventHandler handler) {
try {
unmarshaller.setEventHandler(handler);
marshaller.setEventHandler(handler);
} catch (JAXBException e) {
// impossible
throw new Error(e);
}
}
/**
* @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
*/
public void setEventHandler(ValidationEventHandler handler)
throws JAXBException {
if( handler == null ) {
eventHandler = new DefaultValidationEventHandler();
} else {
eventHandler = handler;
}
}
@Override
public final ValidationEventHandler getEventHandler() {
try {
return super.getEventHandler();
} catch (JAXBException e) {
// impossible
throw new AssertionError();
}
}
/**
* @see javax.xml.bind.Marshaller#setEventHandler(ValidationEventHandler)
*/
public void setEventHandler(ValidationEventHandler handler)
throws JAXBException {
if( handler == null ) {
eventHandler = new DefaultValidationEventHandler();
} else {
eventHandler = handler;
}
}
/**
* Read in a T from the input stream.
*
* @param type Class of object to be read in
* @param in input stream to read
* @param validate whether to validate the input.
* @param <T> class of object to be returned
* @return a T read from the input stream
* @throws ParserConfigurationException is the SAX parser can not be configured
* @throws SAXException if there is an xml problem
* @throws JAXBException if the xml cannot be marshalled into a T.
*/
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean validate) throws ParserConfigurationException, SAXException, JAXBException {
final InputSource inputSource = new InputSource(in);
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(validate);
final SAXParser parser = factory.newSAXParser();
final JAXBContext ctx = JaxbJavaee.getContext(type);
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
System.out.println(validationEvent);
return false;
}
});
final JaxbJavaee.NoSourceFilter xmlFilter = new JaxbJavaee.NoSourceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
final SAXSource source = new SAXSource(xmlFilter, inputSource);
currentPublicId.set(new TreeSet<String>());
try {
return unmarshaller.unmarshal(source);
} finally {
currentPublicId.set(null);
}
}
@Override
public final ValidationEventHandler getEventHandler() {
try {
return super.getEventHandler();
} catch (JAXBException e) {
// impossible
throw new AssertionError();
}
}
@Override
public final ValidationEventHandler getEventHandler() {
try {
return super.getEventHandler();
} catch (JAXBException e) {
// impossible
throw new AssertionError();
}
}
public <T> T readXml(final URI xml, final Class<T> type, final Schema schema, final ValidationEventHandler handler) {
checkInputEmpty(xml);
checkTypeEmpty(type);
CollectingErrorEventHandler defaultHandler = null;
ValidationEventHandler handler2Use = handler;
if (schema != null && handler == null) {
defaultHandler = new CollectingErrorEventHandler();
handler2Use = defaultHandler;
}
try {
final XMLInputFactory inputFactory = XMLInputFactory.newFactory();
inputFactory.setProperty(XMLInputFactory.IS_SUPPORTING_EXTERNAL_ENTITIES, false);
inputFactory.setProperty(XMLInputFactory.IS_REPLACING_ENTITY_REFERENCES, false);
inputFactory.setProperty(XMLInputFactory.SUPPORT_DTD, false);
final XMLStreamReader xsr = inputFactory.createXMLStreamReader(new StreamSource(xml.toASCIIString()));
final Unmarshaller u = getJaxbContext().createUnmarshaller();
u.setSchema(schema);
u.setEventHandler(handler2Use);
final T value = u.unmarshal(xsr, type).getValue();
if (defaultHandler != null && defaultHandler.hasErrors()) {
throw new ConversionExeption(
String.format("Schema errors while reading content from %s: %s", xml, defaultHandler.getErrorDescription()));
}
return value;
} catch (final JAXBException | XMLStreamException e) {
throw new ConversionExeption(String.format("Can not unmarshal to type %s from %s", type.getSimpleName(), xml.toString()), e);
}
}
public static <T> Object unmarshal(final Class<T> type, final InputStream in, final boolean logErrors) throws ParserConfigurationException, SAXException, JAXBException {
// create a parser with validation disabled
final SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
factory.setValidating(false);
final SAXParser parser = factory.newSAXParser();
// Get the JAXB context -- this should be cached
final JAXBContext ctx = JAXBContextFactory.newInstance(type);
// get the unmarshaller
final Unmarshaller unmarshaller = ctx.createUnmarshaller();
// log errors?
unmarshaller.setEventHandler(new ValidationEventHandler() {
public boolean handleEvent(final ValidationEvent validationEvent) {
if (logErrors) {
System.out.println(validationEvent);
}
return false;
}
});
// add our XMLFilter which disables dtd downloading
final NamespaceFilter xmlFilter = new NamespaceFilter(parser.getXMLReader());
xmlFilter.setContentHandler(unmarshaller.getUnmarshallerHandler());
// Wrap the input stream with our filter
final SAXSource source = new SAXSource(xmlFilter, new InputSource(in));
// unmarshal the document
return unmarshaller.unmarshal(source);
}
public ConstantValidationEventHandlerFactory (@Nullable final ValidationEventHandler aEventHandler)
{
m_aEventHandler = aEventHandler;
}
public ResultImpl createUnmarshaller(ValidationEventHandler errorHandler) {
return new ResultImpl();
}
/**
* Delegates to the wrapped marshaller. The initial state will be saved
* if it was not already done, for future restoration by {@link #reset(Pooled)}.
*/
@Override
public void setEventHandler(final ValidationEventHandler handler) throws JAXBException {
super.setEventHandler(handler);
marshaller.setEventHandler(handler);
}
public Source marshal(Element element, ValidationEventHandler errorHandler) {
return new DOMSource(element);
}
public void setEventHandler(ValidationEventHandler handler) throws JAXBException {
getUnmarshaller().setEventHandler(handler);
getMarshaller().setEventHandler(handler);
}
public Source marshal(Element element, ValidationEventHandler errorHandler) {
return new DOMSource(element);
}
public ResultImpl createUnmarshaller(ValidationEventHandler errorHandler) {
return new ResultImpl();
}