Динамические конечные точки Apache Camel

Я начинаю изучать Apache Camel и столкнулся с проблемой.

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


Это пример XML, расположенного в «C:/Users/JuISe/Desktop/jms».

<file>
    <from>C:/Users/JuISe/Desktop/from</from>
    <to>C:/Users/JuISe/Desktop/to</to>
</file>

Это означает перенос всех файлов из каталога «C:/Users/JuISe/Desktop/from» в «C:/Users/JuISe/Desktop/to».

Вот мой код:

public class FileShifter {
    public static void main(String args[]) {
        CamelContext context = new DefaultCamelContext();
        try {
            context.addRoutes(new MyRouteBuilder());
            context.start();
            Thread.sleep(10000);
            context.stop();
        }catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

class MyRouteBuilder extends RouteBuilder {
    private String from;
    private String to;
    public void configure(){
        from("file:C:/Users/JuISe/Desktop/jms?noop=true")
                .setHeader("from", xpath("file/from/text()").stringResult())
                .setHeader("to", xpath("file/to/text()").stringResult())
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        from = exchange.getIn().getHeader("from").toString();
                        to = exchange.getIn().getHeader("to").toString();
                    }
                })
                .pollEnrich("file:" + from)
                .to("file:" + to);
    }
}

Это не работает. Вот логи:

[main] INFO org.apache.camel.impl.converter.DefaultTypeConverter - Loaded 216 type converters
[main] INFO org.apache.camel.impl.DefaultRuntimeEndpointRegistry - Runtime endpoint registry is in extended mode gathering usage statistics of all incoming and outgoing endpoints (cache limit: 1000)
[main] INFO org.apache.camel.impl.DefaultCamelContext - AllowUseOriginalMessage is enabled. If access to the original message is not needed, then its recommended to turn this option off as it may improve performance.
[main] INFO org.apache.camel.impl.DefaultCamelContext - StreamCaching is not in use. If using streams then its recommended to enable stream caching. See more details at http://camel.apache.org/stream-caching.html
[main] INFO org.apache.camel.component.file.FileEndpoint - Endpoint is configured with noop=true so forcing endpoint to be idempotent as well
[main] INFO org.apache.camel.component.file.FileEndpoint - Using default memory based idempotent repository with cache max size: 1000
[main] INFO org.apache.camel.impl.DefaultCamelContext - Route: route1 started and consuming from: Endpoint[file://C:/Users/JuISe/Desktop/jms?noop=true]
[main] INFO org.apache.camel.impl.DefaultCamelContext - Total 1 routes, of which 1 is started.
[main] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.16.1 (CamelContext: camel-1) started in 1.033 seconds
[Camel (camel-1) thread #0 - file://C:/Users/JuISe/Desktop/jms] WARN org.apache.camel.component.file.strategy.MarkerFileExclusiveReadLockStrategy - Deleting orphaned lock file: C:\Users\JuISe\Desktop\jms\message.xml.camelLock
[Camel (camel-1) thread #0 - file://C:/Users/JuISe/Desktop/jms] INFO org.apache.camel.builder.xml.XPathBuilder - Created default XPathFactory com.sun.org.apache.xpath.internal.jaxp.XPathFactoryImpl@2308d4c8
[main] INFO org.apache.camel.impl.DefaultCamelContext - Apache Camel 2.16.1 (CamelContext: camel-1) is shutting down
[main] INFO org.apache.camel.impl.DefaultShutdownStrategy - Starting to graceful shutdown 1 routes (timeout 300 seconds)
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 300 seconds. Inflights per route: [route1 = 2]
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 299 seconds. Inflights per route: [route1 = 2]
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 298 seconds. Inflights per route: [route1 = 2]
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 297 seconds. Inflights per route: [route1 = 2]
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 296 seconds. Inflights per route: [route1 = 2]
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 295 seconds. Inflights per route: [route1 = 2]
[Camel (camel-1) thread #2 - ShutdownTask] INFO org.apache.camel.impl.DefaultShutdownStrategy - Waiting as there are still 2 inflight and pending exchanges to complete, timeout in 294 seconds. Inflights per route: [route1 = 2]

Спасибо за помощь!


person JuISe    schedule 29.01.2016    source источник
comment
Что в нем не работает? Файлы не перемещаются, как вы ожидаете?   -  person rmlan    schedule 29.01.2016
comment
Да, файлы абсолютно не перемещались   -  person JuISe    schedule 29.01.2016
comment
Хорошо, насколько я знаю, pollEnrich просто вставляет содержимое рассматриваемого файла, но ничего не делает с физическим файлом. Я не уверен, что этот маршрут когда-либо достигнет того, чего вы хотите.   -  person rmlan    schedule 29.01.2016
comment
На самом деле я хочу взять XML, прочитать из него и в поля из этого. И замените этот XML целевым файлом взамен.   -  person JuISe    schedule 29.01.2016
comment
Хорошо, я понимаю, что вы пытаетесь сделать. Просто любопытно, создается ли файл to, как вы ожидаете?   -  person rmlan    schedule 29.01.2016
comment
Нет, чтобы папка оставалась пустой   -  person JuISe    schedule 29.01.2016
comment
Вы не можете установить значения String внутри процессора и использовать их в маршруте снаружи, установить их в свойствах обмена или в заголовке вывода, чтобы получить к ним доступ вне процессора.   -  person Sundar    schedule 30.01.2016


Ответы (1)


Попробуйте использовать bean-компонент с шаблоном производителя и потребителя, каталог конечных точек файла не может быть динамическим

from("file:/Users/smunirat/apps/destination/jms?noop=true")
            .setHeader("from", xpath("file/from/text()").stringResult())
            .setHeader("to", xpath("file/to/text()").stringResult())
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    from = exchange.getIn().getHeader("from").toString();
                    to = exchange.getIn().getHeader("to").toString();

                    exchange.getOut().setHeader("from", from);
                    exchange.getOut().setHeader("to", to);

                }
            })

            .to("log:Sundar?showAll=true&multiline=true")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    ConsumerTemplate createConsumerTemplate = exchange.getContext().createConsumerTemplate();
                    ProducerTemplate createProducerTemplate = exchange.getContext().createProducerTemplate();
                    Exchange receive = createConsumerTemplate.receive("file://"+exchange.getIn().getHeader("from"));
                    createProducerTemplate.sendBody("file://"+exchange.getIn().getHeader("to"),receive.getIn().getMandatoryBody());

                }
            })
            .log("Message");

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

person Sundar    schedule 30.01.2016
comment
Кажется, работает. Не могли бы вы объяснить, что означает .to(log:Sundar?showAll=true&multiline=true)? Большое спасибо! - person JuISe; 30.01.2016