Как вы маршалируете с несколькими моделями BindyFixedLengthDataFormat (camel-bindy-2.16)

В настоящее время я пытаюсь перейти с camel-bindy-2.12.1 на camel-bindy-2.16.2 и столкнулся с проблемой при попытке применить модель, состоящую из несколько классов в набор данных, в результате чего получается один текстовый файл.

У меня было несколько классов в пакете (com.sample.package), которые я мог использовать для маршалинга, используя следующий код (Camel Spring DSL):

<bean id="bindyFixedLengthDataformat"  class="org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat">
    <constructor-arg value="com.sample.package" />
</bean>

а затем ссылаться на bean-компонент при маршалинге:

<marshal ref="bindyFixedLengthDataformat" />

Этот вызов bean-компонента применит все классы в пакете к маршалируемым данным, что приведет к созданию одного файла.

Он прекрасно работал с camel-bindy-2.12.1, но приведенный выше конструктор больше недоступен с camel-bindy-2.16.2.

Мне не удалось найти примеров, которые бы обеспечивали ту же функциональность с удаленным конструктором.

Кто-нибудь сталкивался с этой ситуацией? Если это так, любые предложения/примеры будут очень признательны.

Спасибо


person user1803311    schedule 02.03.2016    source источник
comment
у вас нет корневого объекта, аннотированного @CsvRecord?   -  person Jérémie B    schedule 03.03.2016
comment
Аннотированные классы имеют: @FixedLengthRecord(length=94, paddingChar=' ',crlf="\n" )   -  person user1803311    schedule 03.03.2016


Ответы (1)


Это старый пост, но я нашел решение. Идея состоит в том, что вам нужно создать отдельный модуль форматирования для каждого класса... затем применить каждый из модулей форматирования к телу сообщения верблюда:

/* BEGIN Spring Boot Bean Config */

import org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat;

@Autowired
CamelContext camelContext;

@Bean (name="bindyFixedLengthDataformat_Part1")
public BindyFixedLengthDataFormat bindyFixedLengthDataformat_Part1 () {

    BindyFixedLengthDataFormat bindy = new BindyFixedLengthDataFormat (com.xyz.Part1.class);

    bindy.setCamelContext(camelContext);

    return bindy;
}

@Bean (name="bindyFixedLengthDataformat_Part2")
public BindyFixedLengthDataFormat bindyFixedLengthDataformat_Part2 () {

    BindyFixedLengthDataFormat bindy = new BindyFixedLengthDataFormat (com.xyz.Part2.class);

    bindy.setCamelContext(camelContext);

    return bindy;
}
...
@Bean (name="bindyFixedLengthDataformat_PartN")
public BindyFixedLengthDataFormat bindyFixedLengthDataformat_PartN () {

    BindyFixedLengthDataFormat bindy = new BindyFixedLengthDataFormat (com.xyz.PartN.class);

    bindy.setCamelContext(camelContext);

    return bindy;
}

@Bean (name="bindyConverter")
BindyConverterUtil bindyConverter () {

    BindyConverterUtil bindyConverter = new BindyConverterUtil () ;             //This is a custom bean containing all the converters you need. Implements method process (Exchange)

    bindyConverter.setBindyFixedLengthDataformat_Part1(bindyFixedLengthDataformat_Part1());
    bindyConverter.setBindyFixedLengthDataformat_Part2(bindyFixedLengthDataformat_Part2());

...

bindyConverter.setBindyFixedLengthDataformat_Part5(bindyFixedLengthDataformat_PartN());

    return bindyConverter;
}

@Bean (name="createObjectArrayListWithDataClasses")
public ListWithDifferentDataClasses createObjectArrayListWithDataClasses () {

    ListWithDifferentDataClasses lineValues = new ListWithDifferentDataClasses();           // This is a custom bean that basically creates an array list of classes containing the data you want to marshal 
                                                                                                // Implements method process(Exchange). 
                                                                                                // Adds classes using: exchange.getIn().setBody(<ArrayList of classes>);

    return lineValues;
}

/* END Spring Boot Bean Config */ 

/* Bindy Converter Util */

package com.xyz;

import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import org.apache.camel.dataformat.bindy.fixed.BindyFixedLengthDataFormat;


public class BindyConverterUtil implements Processor {

    /* (non-Javadoc)
     * @see org.apache.camel.Processor#process(org.apache.camel.Exchange)
     */
    private BindyFixedLengthDataFormat bindyFixedLengthDataformat_Part1;
    private BindyFixedLengthDataFormat bindyFixedLengthDataformat_Part2;

    private BindyFixedLengthDataFormat bindyFixedLengthDataformat_PartN;

    public void setBindyFixedLengthDataformat_Part1 (BindyFixedLengthDataFormat bindyFormatter) {

        this.bindyFixedLengthDataformat_Part1 = bindyFormatter;
    }

    public void setBindyFixedLengthDataformat_Part2 (BindyFixedLengthDataFormat bindyFormatter) {

        this.bindyFixedLengthDataformat_Part2 = bindyFormatter;
    }

    public void setBindyFixedLengthDataformat_PartN (BindyFixedLengthDataFormat bindyFormatter) {

        this.bindyFixedLengthDataformat_PartN = bindyFormatter;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    @Override
    public void process(Exchange exchange) throws Exception {
        // TODO Auto-generated method stub

        ArrayList <HashMap> contents = (ArrayList <HashMap>) exchange.getIn().getBody();        //From the createObjectArrayListWithDataClasses bean.

        OutputStream outputStream = new ByteArrayOutputStream();

        for (HashMap item: contents) {

            if ( null != item.get(Part1.class.getName()) ) {

                bindyFixedLengthDataformat_Part1.marshal(exchange, item.get(Part1.class.getName()), outputStream);
            }
            else if ( null != item.get(Part2.class.getName()) ) {

                bindyFixedLengthDataformat_Part2.marshal(exchange, item.get(Part2.class.getName()), outputStream);
            }
...
            else if ( null != item.get(PartN.class.getName()) ) {

                bindyFixedLengthDataformat_PartN.marshal(exchange, item.get(PartN.class.getName()), outputStream);
            }
            else {
                throw new Exception ("Bindy Converter - Cannot marshal record. Format is not recognized. ");
            }
        }

        exchange.getIn().setBody(outputStream);
    }
}

/* End Bindy Converter Util */


/* Camel Route (XML) */

<route id="xyxz" >
    <from uri="timer...or whatever" />

    <to uri="createObjectArrayListWithDataClasses" />

    <to uri="bindyConverter" />

    <to uri="file://somepath/?fileName=outputfileName_${date:now:yyyyMMddhhmmss}.txt" />
</route>

/* End Camel Route (XML) */
person user1803311    schedule 02.01.2019