gpt4 book ai didi

java - Camel Bindy 不适本地转换 BigDecimal

转载 作者:行者123 更新时间:2023-12-01 12:18:51 26 4
gpt4 key购买 nike

我有以下使用Camels Bindy的示例,但最终它会引发断言错误,因为bindy以错误的方式转换BigDecimal(使用逗号而不是点作为数字分隔符)。

这段代码有什么问题?

public class PurchaseOrderBindyTest extends TestCase {

@Test
public void testBindy() throws Exception {
CamelContext context = new DefaultCamelContext();
context.addRoutes(createRoute());
context.start();

MockEndpoint mock = context.getEndpoint("mock:result", MockEndpoint.class);
mock.expectedBodiesReceived("Camel in Action,39.95,1\n");

PurchaseOrder order = new PurchaseOrder();
order.setAmount(1);
order.setPrice(new BigDecimal("39.95"));
order.setName("Camel in Action");

ProducerTemplate template = context.createProducerTemplate();
template.sendBody("direct:toCsv", order);

mock.assertIsSatisfied();
}

public RouteBuilder createRoute() {
return new RouteBuilder() {
public void configure() throws Exception {
from("direct:toCsv")
.marshal().bindy(BindyType.Csv, "camelinaction.bindy")
.to("mock:result");
}
};
}
}

型号

@CsvRecord(separator = ",", crlf = "UNIX")
public class PurchaseOrder {

@DataField(pos = 1)
private String name;

@DataField(pos = 2, precision = 2)
private BigDecimal price;

@DataField(pos = 3)
private int amount;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public BigDecimal getPrice() {
return price;
}

public void setPrice(BigDecimal price) {
this.price = price;
}

public int getAmount() {
return amount;
}

public void setAmount(int amount) {
this.amount = amount;
}
}

断言错误

java.lang.AssertionError: mock://result Body of message: 0. Expected: <Camel in Action,39.95,1
> but was: <Camel in Action.39,95.1
>

最佳答案

我的测试通过了,没有任何问题。有趣的是,在你的例子中,“.”和“,”似乎颠倒了。

Camel 使用 java.text.DecimalFormat 类来确定区域设置,如下所示:

Locale def = Locale.getDefault(Locale.Category.FORMAT);

您可以按如下方式重置区域设置默认值:

Locale.setDefault(new Locale ("en", "US"));

如果您不想重置默认区域设置,可以按如下方式设置区域设置:

BindyCsvDataFormat bindy = new BindyCsvDataFormat(PurchaseOrder.class);
bindy.setLocale(Locale.US.getCountry());

from("direct:toCsv")
.marshal(bindy)
...

在这种情况下,Camel 会重置 AbstractNumberFormat 中的十进制格式符号,如下所示:

if (locale != null) {
this.format.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(locale));
}

关于java - Camel Bindy 不适本地转换 BigDecimal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26828777/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com