如何使用apache Camel Bindy将java pojo转换为具有列表属性的固定长度字符串?

问题描述 投票:0回答:1

我有一个如下的java pojo类?

@FixedLengthRecord
public class Request {
    @DataField(pos = 1, length = 15)
    private String string1;

    @DataField(pos = 16, length = 8)
    private String string2;

    @DataField(pos = 24)
    @ManytoOne(mappedTo="classpath:Record")
    private List<Record> records;
}

public class Record{
   
    @DataField(pos = 24, length = 10)
    private String string3;

    @DataField(pos = 34, length = 10)
    private String string4;

    @DataField(pos = 44, length = 8)
    private String string5;
}

我想使用 apache Camel 将 pojo 类转换为固定长度字符串?但列表属性永远不会转换为固定长度字符串。有没有办法只使用一条路线来做到这一点?

我尝试了以下方法:

public class CamelBindyUtility extends RouteBuilder {

    @Override
    public void configure() throws Exception {
 
        from("direct:marshal")
            .marshal().bindy(BindyFixedLengthDataFormat.class, Request.class)
            .to("mock:marshalled");
    }
}

它不会将List属性更改为必要的固定长度?

java apache-camel marshalling fixed-length-record
1个回答
0
投票

要使用 Apache Camel 将 POJO 类转换为固定长度字符串,特别是在处理 List 属性时,需要采取特殊措施,因为 Apache Camel 的 Bindy 组件本身不支持将 POJO 中的列表属性直接序列化或反序列化为固定长度格式。但是,您可以通过将 Camel 的功能与一些编程技术相结合来实现此要求。

示例:

创建自定义处理器: 首先,您需要创建一个自定义处理器(Processor),您将在其中编写逻辑来手动将 Request 对象及其包含的 List 转换为固定长度的字符串格式。

处理器逻辑: 在自定义处理器中,您需要迭代

List<Record>
中的
Request
,并为每个
Record
生成固定长度的字符串。然后这些字符串将与
Request
对象的其他字段组合以形成最终的固定长度字符串。

实现自定义处理器

稍后您可以通过使用反射来改进这一点,以实现更灵活的处理。

import org.apache.camel.Exchange;
import org.apache.camel.Processor;

public class FixedLengthProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
        Request request = exchange.getIn().getBody(Request.class);
        StringBuilder fixedLengthString = new StringBuilder();

        // Process the basic properties of Request
        fixedLengthString.append(formatString(request.getString1(), 15));
        fixedLengthString.append(formatString(request.getString2(), 8));

        // Iterate over List<Record> and process each Record
        for (Record record : request.getRecords()) {
            fixedLengthString.append(formatString(record.getString3(), 10));
            fixedLengthString.append(formatString(record.getString4(), 10));
            fixedLengthString.append(formatString(record.getString5(), 8));
        }

        // Set the processed fixed-length string as the message body
        exchange.getIn().setBody(fixedLengthString.toString());
    }

    private String formatString(String input, int length) {
        if (input == null) input = "";
        if (input.length() > length) {
            return input.substring(0, length);
        } else {
            return String.format("%1$-" + length + "s", input);
        }
    }
}

配置骆驼路线: 您可以创建一个路由,从端点接收消息,通过自定义处理器处理它们,然后将结果发送到另一个端点。

from("direct:start")
    .process(new FixedLengthProcessor())
    .to("file://output?fileName=fixedLengthOutput.txt")
© www.soinside.com 2019 - 2024. All rights reserved.