jaxb - 如何知道调用eventhandler的时间(验证期间)

时间:2014-08-04 15:53:03

标签: jaxb eventhandler

我正在使用JAXB解析XML并创建了一个事件处理程序,如果验证出现问题,它将显示错误。

调用事件处理程序并输出错误;如果调用事件处理程序(打印输出后?)

,如何抛出异常

在代码中,我不知道何时调用事件处理程序,只是在验证错误时调用它;我需要能够在事件处理程序返回后将文件移动到/ dir /。


我的事件处理程序如下所示:

import base.helper.HelperBase;
import org.springframework.stereotype.Component;

import javax.xml.bind.ValidationEvent;
import javax.xml.bind.ValidationEventHandler;
import java.util.logging.Level;

/**
 *
 */
@Component
public class MyValidationEventHandler extends HelperBase implements ValidationEventHandler {

    public boolean handleEvent(ValidationEvent event) {
        logger.log(Level.INFO, "\n---");
        System.out.println("EVENT");
        System.out.println("\nEVENT");
        System.out.println("SEVERITY:  " + event.getSeverity());
        System.out.println("MESSAGE:  " + event.getMessage());
        System.out.println("LINKED EXCEPTION:  " + event.getLinkedException());
        System.out.println("LOCATOR");
        System.out.println("    LINE NUMBER:  " + event.getLocator().getLineNumber());
        System.out.println("    COLUMN NUMBER:  " + event.getLocator().getColumnNumber());
        System.out.println("    OFFSET:  " + event.getLocator().getOffset());
        System.out.println("    OBJECT:  " + event.getLocator().getObject());
        System.out.println("    NODE:  " + event.getLocator().getNode());
        System.out.println("    URL:  " + event.getLocator().getURL());
        new Exception("fail");
        return true;
    }
}

处理时,我的代码如下所示:

    private void processXmlFile(String file) throws Exception {
        // todo: test for file existence, get size, print stats

        try {
            logger.log(Level.INFO, "Processing: " + file);
            SchemaFactory sf = null;
            Schema schema = null;

            JAXBContext jctx = JAXBContext.newInstance("mypackage.jaxb");
            Unmarshaller unmarshaller = jctx.createUnmarshaller();

            if (validate) {
                sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
                schema = sf.newSchema(new File(xsd));
                unmarshaller.setSchema(schema);
                eventHandler.setLogger(logger);
                unmarshaller.setEventHandler(eventHandler);
            }


            JAXBElement<MyType> mytype = unmarshaller.unmarshal(new StreamSource(new File(file)), MyType.class);
            MyType ct = mytype.getValue();

        } catch (Exception e) { // if find a problem file, just move it out of the way and keep processing
            // if the event handler is called, I want to throw an exception and do something here.
            // move file to failed
            fileUtils.moveFile(config.getErrorDir(), file);
            // on an unmarshall failure, this exception is not thrown/caught because the event handler handles things and returns true


        }
    }

1 个答案:

答案 0 :(得分:1)

请阅读How to Throw Exceptions

在您的事件处理程序中,您需要throw()Exception,或许需要:

throw new ValidationException();  //  throw exeption

而不是:

new Exception("fail");  //  create exception but do nothing with it?

您可以将ValidationException定义为:

public class ValidationException extends RuntimeException {

  public ValidationException(final String s) {
    super(s);
  }

变化:

public boolean handleEvent(ValidationEvent event) {

要:

public boolean handleEvent(ValidationEvent event) throws ValidationException {

processXmlFile()中,我们现在需要:

catch (ValidationException e) { 
  // catch more specific exception first
  fileUtils.moveFile(config.getErrorDir(), file);
catch (Exception e) {
  // deal with any other exceptions ...
}