BeanIO InvalidRecordGroupException给出错误的行号

时间:2017-09-07 22:03:24

标签: java parsing bean-io

我正在使用BeanIO来解析固定宽度的文本文件。例如,进入我的项目的文件看起来像以下固定宽度文本:

 CD DummyValue3
 EF DummyValue4 DummyValue5 DummyValue6
 AB DummyValue1 DummyValue2
 ...

在我的映射文件中,我为每个recordID声明了record(即AB,CD,EF)

<record name="dummyRecord" template="AB"
class="com.company.project.DummyRecordClass" minOccurs="0"
maxOccurs="1" />

然后,每个记录都有一个template

<template name="AB">
    <field name="recordID" length="3" rid="true" literal="AB"
           lenientPadding="true" minOccurs="0" />
    <field name="value1" length="12" lenientPadding="true"
           minOccurs="1" required="true"/>
    <field name="value2" length="12" lenientPadding="true"
           minOccurs="1" required="true"/>
</template>

因为value1value2minOccurs = 1以及required="true"(是的,我知道这是多余的,但它已经在代码中,我们有数千个如果我有一个AB段,它们必须存在。

所以,如果我要将以下文件传递给我的程序:

 CD DummyValue3
 EF DummyValue4 DummyValue5 DummyValue6
 AB DummyValue1

我收到以下InvalidRecordGroupException:

org.beanio.InvalidRecordGroupException: Invalid 'ediMessage' record group at line 1

但是,由于缺少的字段实际上在第3行,因此当您有500-600行数据进入应用程序时,调试可能会非常麻烦。

当缺少必填字段时,有没有办法让beanIO输出正确的行号,甚至是templatefield值?

1 个答案:

答案 0 :(得分:1)

我通过扩展org.beanio.BeanReaderErrorHandler来创建org.beanio.BeanReaderErrorHandlerSupport来使用LoggingErrorHandler的自定义实现。

import org.beanio.BeanReaderErrorHandlerSupport;
import org.beanio.BeanReaderException;
import org.beanio.InvalidRecordException;
import org.beanio.MalformedRecordException;
import org.beanio.RecordContext;
import org.beanio.UnexpectedRecordException;
import org.beanio.UnidentifiedRecordException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * A BeanIO {@code BeanReaderErrorHandler} that logs the error messages.
 *
 * @author Nico Schlebusch
 */
public class LoggingBeanReaderErrorHandler extends BeanReaderErrorHandlerSupport {

  private static final Logger LOGGER = LoggerFactory.getLogger(LoggingBeanReaderErrorHandler.class);

  /**
   * Creates a new instance of {@code LoggingBeanReaderErrorHandler}.
   */
  public LoggingBeanReaderErrorHandler() {
  }

  /**
   * {@inheritDoc}
   *
   * @see org.beanio.BeanReaderErrorHandlerSupport#invalidRecord(org.beanio.InvalidRecordException)
   */
  @Override
  public void invalidRecord(final InvalidRecordException ex) throws BeanReaderException {

    LOGGER.error("{}", createErrorMessage(ex));
  }

  /**
   * {@inheritDoc}
   *
   * @see org.beanio.BeanReaderErrorHandlerSupport#unexpectedRecord(org.beanio.UnexpectedRecordException)
   */
  @Override
  public void unexpectedRecord(final UnexpectedRecordException ex) throws BeanReaderException {

    LOGGER.error("{}", createErrorMessage(ex));
  }

  /**
   * {@inheritDoc}
   *
   * @see org.beanio.BeanReaderErrorHandlerSupport#unidentifiedRecord(org.beanio.UnidentifiedRecordException)
   */
  @Override
  public void unidentifiedRecord(final UnidentifiedRecordException ex) throws BeanReaderException {

    LOGGER.error("{}", createErrorMessage(ex));
  }

  /**
   * {@inheritDoc}
   *
   * @see org.beanio.BeanReaderErrorHandlerSupport#malformedRecord(org.beanio.MalformedRecordException)
   */
  @Override
  public void malformedRecord(final MalformedRecordException ex) throws BeanReaderException {

    LOGGER.error("{}", createErrorMessage(ex));
  }

  /**
   * {@inheritDoc}
   *
   * @see org.beanio.BeanReaderErrorHandlerSupport#fatalError(org.beanio.BeanReaderException)
   */
  @Override
  public void fatalError(final BeanReaderException ex) throws BeanReaderException {

    LOGGER.error("{}", createErrorMessage(ex));
  }

  /**
   * Creates an error message using the exception to get the RecordContext from which a meaningful error
   * message can be constructed.
   *
   * @param ex the exception containing the error information.
   *
   * @return a string describing the error(s).
   */
  protected String createErrorMessage(final BeanReaderException ex) {

    final String message = ex.getMessage();
    final StringBuilder errorMessage = new StringBuilder(message.length() * 5);

    // if a bean object is mapped to a record group,
    // the exception may contain more than one record
    for (int i = 0, j = ex.getRecordCount(); i < j; i++) {
      final RecordContext recordContext = ex.getRecordContext(i);
      final String recordName = recordContext.getRecordName();
      final String text = recordContext.getRecordText();
      errorMessage.append(String.format("%s: %s%n", message, text));

      if (recordContext.hasRecordErrors()) {
        for (final String error : recordContext.getRecordErrors()) {
          errorMessage.append(String.format("Record '%s' - %s%n", recordName, error));
        }
      }
      if (recordContext.hasFieldErrors()) {
        for (final String field : recordContext.getFieldErrors().keySet()) {
          for (final String error : recordContext.getFieldErrors(field)) {
            errorMessage.append(String.format("Field '%s' - %s%n", field, error));
          }
        }
      }
    }

    return errorMessage.toString();
  }

}

您可以修改createErrorMessage()方法,仅保留您要查找的信息。

当然,您可以使用这些信息执行许多其他操作,例如将其写入文件,通过电子邮件发送等。有关替代方法,请参阅文档的BeanReaderErrorHandler部分。

然后,您必须使用BeanReader实例注册错误处理程序:

BeanReader beanReader = ....
beanReader.setErrorHandler(errorHandler);

然后应输出有关错误所在位置的更多信息。