How to use a dynamic URI in From()

Siddheshwar Bhosale picture Siddheshwar Bhosale · Sep 3, 2015 · Viewed 7.4k times · Source

As mentioned in Apache Camel, it allows to write dynamic URI in To(), does it allows to write dynamic URI in From(). Cause I need to call the multiple FTP locations to download the files on the basis of configuration which I am going to store it in database.

(FTPHost, FTPUser, FTPPassword, FTPSourceDir, FTPDestDir)

I will read these configuration from the DB and will pass it to the Camel route dynamically at runtime.

Example: This is the camel route example that I have to write dynamically

<Route>
    <from uri="ftp://${ftpUser}@${ftpHost}:${ftpPort}/${FTPSourceDir}?password=${ftpPassword}&delete=true"/>
    <to uri="${ftpDestinationDir}"/>
</Route>

As you see in example, I need to pass these mentioned parameters dynamically. So how to use dynamic uri in From()

Answer

Gnana Guru picture Gnana Guru · Sep 3, 2015

You can read it from property file as follows,

<bean id="bridgePropertyPlaceholder" class="org.apache.camel.spring.spi.BridgePropertyPlaceholderConfigurer">
    <property name="location" value="classpath:/config/Test.properties"/>
  </bean> 

<Route>
    <from uri="ftp://{{ftpUser})@${{ftpHost}}:{{ftpPort}}/${{FTPSourceDir}}?password={{ftpPassword}}&delete=true"/>
    <to uri="{{ftpDestinationDir}}"/>
</Route>

ftpUser, ftpHost.... - all are keys declared in Test.properties

If you want to get those variables from your exchange dynamically, you cannot do it in regular way as you mentioned in your example. You have to use consumer template as follows,

Exchange exchange = consumerTemplate.receive("ftp:"+url);
producerTemplate.send("direct:uploadFileFTP",exchange );

You have to do that from a spring bean or camel producer. Consumer template will consume from given component, and that producer template will invoke direct component declared in your camel-context.xml

Note: Consumer and Producer templates are bit costly. you can inject both in spring container and let the spring handle the life cycle.