在用Apache Camel Bindy解组CSV记录时,有没有一种方法可以跳过无效的记录

iswrvxsc  于 12个月前  发布在  Apache
关注(0)|答案(1)|浏览(95)

我有以下路线

from("file:" + baseInputPath + "/exchangerates" + "?noop=true")
                                .idempotentConsumer(header(CAMEL_FILE_NAME),
                                                FileIdempotentRepository.fileIdempotentRepository(new File(
                                                                baseInputPath + "/tracker/exchangeratefiles.txt")))
                                .log("Processing exchange rate file: ${header.CamelFileName}").unmarshal()
                                .bindy(BindyType.Csv, ExchangeRateBindy.class).process(exchange -> {
                                        ExchangeRateBindy exchangeRateBindy = exchange.getIn()
                                                        .getBody(ExchangeRateBindy.class);
                                        if (exchangeRateBindy != null) {
                                                exchangeRateService.save(exchangeRateBindy.toExchangeRate());
                                        } else {
                                                log.error("Invalid exchange rate: {}", exchange.getIn().getBody());
                                        }
                                });

和下面的bindy类

@Data
@CsvRecord(separator = "\\*", skipFirstLine = false)
public class ExchangeRateBindy {
    @DataField(pos = 1)
    private String currencyId;
    @DataField(pos = 2)
    private String currencyName;
    @DataField(pos = 3)
    private double buyRate;
    @DataField(pos = 4)
    private double midRate;
    @DataField(pos = 5, defaultValue = "0")
    private double sellRate;

    public ExchangeRate toExchangeRate() {
        return ExchangeRate.builder().currencyId(currencyId).currencyName(currencyName).buyRate(buyRate)
                .midRate(midRate).sellRate(sellRate).build();
    }
}

和csv数据

CAD*Canadian Dollar.*1.0332*1.0332*1.0332
AUD*Australian Dollars.*812.7459194*837.88239115*Test
BWP*BOTSWANA PULA*90.29159051*93.084113925*95.87663734

如何允许我的路由跳过第二个记录,该记录的最后一个字段的值为“Test”而不是数值?实际上,代码只是抛出一个NumberFormatException,并不处理任何记录。

nnsrf1az

nnsrf1az1#

可以有各种选项,如:

  • 实现custom data format, Package Bindy数据格式并处理分离异常,例如在无效记录上返回null
  • 使用filtervalidator在处理记录之前验证记录,例如在解组之前使用正则表达式。这看起来像是
from("file:...")
   .idempotentConsumer(...)
   .log(...)
   .split(body().tokenize("\n"))
      .filter().regex("[A-Z]{3}\\*[^*]+\\*[0-9.]+\\*[0-9.]+\\*[0-9.]+") // put the valid regex here
      .unmarshal().bindy(BindyType.Csv, ExchangeRateBindy.class)
      .process(...);

相关问题