Search code examples
apache-cameljbossfuse

Download the file using Camel ConsumerTemplate multiple times


I am trying to download the same file multiple times using Camel ConsumerTemplate. It's not getting downloaded multiple times, but I am getting it done while using camel route. I want to download the file using ConsumerTemplate multiple times.

Here is the code that I am trying with ConsumerTemplate:

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

    public class DynamicConsumer implements Processor {

        @Override
        public void process(Exchange inExchange) throws Exception {
            CamelContext camelContext = inExchange.getContext();
            ConsumerTemplate consumerTemplate = camelContext.createConsumerTemplate();
            String resource = "sftp://tester@localhost:22/myfiles?password=password&noop=true&idempotent=false&readLockMarkerFile=false&readLock=none&filter=#myFileFilter";
            consumerTemplate.start();
            Exchange resourceExchange = consumerTemplate.receive(resource,20000);
            consumerTemplate.stop();
            if(resourceExchange != null) {
                inExchange.getOut().setBody(resourceExchange.getIn().getBody());
                inExchange.getProperties().putAll(resourceExchange.getProperties());
                inExchange.getOut().getHeaders().putAll(resourceExchange.getIn().getHeaders());
            } else {
                inExchange.getOut().setBody(null);
            }
        }
    }

This dynamic consumer is getting called from the camel routes multiple times. So, each time, I expect to download the file present in given location. But it is not happening.

Here the code that I tried with camel route.

<from uri="sftp://tester@localhost:22/myfiles?password=password&amp;noop=true&amp;idempotent=false&amp;readLockMarkerFile=false&amp;readLock=none&amp;filter=#myFileFilter"/>

Solution

  • As the documentation states you should call the ConsumerTemplate's –doneUoW(Exchange) function:

    If you have used any of the receive methods which returns a Exchange type then you need to invoke this method when you are done using the returned Exchange.

    -- ConsumerTemplate documentation

    Try to add the following before consumerTemplate.stop():

    consumerTemplate.doneUoW(resourceExchange);