Camel and FTP tutorial

One of the components is the FTP component, which allows you to interact with FTP servers and transfer files. Camel provides simple and effective integration with ftp, sftp and ssh protocols. Let’s see some practical examples.

Firstly, let’s see an example of how you can write a Camel route to upload files using sftp:

package com.sample;

import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.main.Main;

public class FTPExample {
  public static void main(String[] args) throws Exception {
    Main main = new Main();
    main.enableHangupSupport();
    main.addRouteBuilder(new MyRouteFTP());
    main.run(args);
  }
}

class MyRouteFTP extends RouteBuilder {
  @Override
  public void configure() throws Exception {
    System.out.println("My Routing Started");
    from("file:/var/data/in?noop=true").to("sftp://user@myhost//home/data?password=secret");
    System.out.println("My Routing complete");
  }
}

In the above code, we are transferring the files from /var/data/in to the host “myhost” via sftp.

Please note that in order to run a Camel FTP component using sftp you will need the following dependencies:

<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-ftp</artifactId>
    <version>x.x.x</version>
    <!-- use the same version as your Camel core version -->
</dependency>

Besides, for sftp you also need to include the following dependency in your project:

<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

How to use Camel to download files using ftp

On the other hand, downloading the file via ftp means that the ftp component will be used in the “to” direction of the route:

class MyRouteFTP extends RouteBuilder {
  @Override
  public void configure() throws Exception {
    System.out.println("My Routing Started");
    from("ftp://user///opt/data/?password=secret").to("file:/var/data/out");
    System.out.println("My Routing complete");
  }
}

Using the ftp protocol requires that you use the common-net API instead of the jcraft API:

<dependency>
    <groupId>commons-net</groupId>
    <artifactId>commons-net</artifactId>
    <version>3.9.0</version>
</dependency>

Sending files via ftp using a regular expression

By using the include option you can choose which files you want to download via ftp. You can also use a regular expression to specify a pattern to download files. For example, to download all Java files:

@Override
public void configure() throws Exception {
   from("ftp://localhost:21721/?username=user&password=password&include=*.java&passiveMode=true")
       .routeId("ftpRoute")         
          .to("file:output/");
}

This article was a quick walk through Apache Camel ftp component and how to use it to download and upload files.

Found the article helpful? if so please follow us on Socials
Twitter Icon       Facebook Icon       LinkedIn Icon       Mastodon Icon