【问题标题】:jaxb - how to know when eventhandler is called (during validation)jaxb - 如何知道何时调用事件处理程序(在验证期间)
【发布时间】:2014-08-04 15:53:02
【问题描述】:

我正在使用 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


        }
    }

【问题讨论】:

    标签: jaxb eventhandler


    【解决方案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 ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-25
      • 1970-01-01
      • 1970-01-01
      • 2017-01-18
      • 2015-08-02
      • 1970-01-01
      • 1970-01-01
      • 2014-09-15
      • 2012-08-30
      相关资源
      最近更新 更多