Camel Components

FTP

Since Camel 1.1

Both producer and consumer are supported

This component provides access to remote file systems over the FTP and SFTP protocols.

When consuming from remote FTP server, make sure you read the section Default when consuming files further below for details related to consuming files.

Maven users will need to add the following dependency to their pom.xml for this component:

<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>

URI format

ftp://[username@]hostname[:port]/directoryname[?options]
sftp://[username@]hostname[:port]/directoryname[?options]
ftps://[username@]hostname[:port]/directoryname[?options]

Where directoryname represents the underlying directory. The directory name is a path relative to the directory the user logs in to, usually its home directory. Absolute path is not supported. The relative path can contain nested folders, such as /inbox/us.

Camel translates the absolute path to relative by trimming all leading slashes from directoryname. There’ll be a warning (WARN level) message printed in the logs.

When the server refuses the change to a directory, the GenericFileOperationFailedException holds the reply code (getCode()) and the reply of the server, and for a relative path its message gives the current directory, which the path starts from, such as Cannot change directory to: inbox. The path is relative to the current directory: /home/admin.

The autoCreate option is supported. When consumer starts, before polling is scheduled, there’s additional FTP operation performed to create the directory configured for endpoint. The default value for autoCreate is true.

If no username is provided, then anonymous login is attempted using no password.
If no port number is provided, Camel will provide default values according to the protocol (ftp = 21, sftp = 22, ftps = 2222).

You can append query options to the URI in the following format, ?option=value&option=value&…​

This component uses two different libraries for the actual FTP work. FTP and FTPS use Apache Commons Net while SFTP uses JCraft JSCH.

FTPS, also known as FTP Secure, is an extension to FTP that adds support for the Transport Layer Security (TLS) and the Secure Sockets Layer (SSL) cryptographic protocols.

Configuring Options

Camel components are configured on two separate levels:

  • component level

  • endpoint level

Configuring Component Options

At the component level, you set general and shared configurations that are, then, inherited by the endpoints. It is the highest configuration level.

For example, a component may have security settings, credentials for authentication, urls for network connection and so forth.

Some components only have a few options, and others may have many. Because components typically have pre-configured defaults that are commonly used, then you may often only need to configure a few options on a component; or none at all.

You can configure components using:

  • the Component DSL.

  • in a configuration file (application.properties, *.yaml files, etc).

  • directly in the Java code.

Configuring Endpoint Options

You usually spend more time setting up endpoints because they have many options. These options help you customize what you want the endpoint to do. The options are also categorized into whether the endpoint is used as a consumer (from), as a producer (to), or both.

Configuring endpoints is most often done directly in the endpoint URI as path and query parameters. You can also use the Endpoint DSL and DataFormat DSL as a type safe way of configuring endpoints and data formats in Java.

A good practice when configuring options is to use Property Placeholders.

Property placeholders provide a few benefits:

  • They help prevent using hardcoded urls, port numbers, sensitive information, and other settings.

  • They allow externalizing the configuration from the code.

  • They help the code to become more flexible and reusable.

The following two sections list all the options, firstly for the component followed by the endpoint.

Component Options

The FTP component supports the following options which are listed below.

Name Description Default Type

bridgeErrorHandler (consumer)

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

lazyStartProducer (producer)

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

autowiredEnabled (advanced)

Whether autowiring is enabled. This is used for automatic autowiring options (the option must be marked as autowired) by looking up in the registry to find if there is a single instance of matching type, which then gets configured on the component. This can be used for automatic configuring JDBC data sources, JMS connection factories, AWS Clients, etc.

true

boolean

healthCheckConsumerEnabled (health)

Used for enabling or disabling all consumer based health checks from this component.

true

boolean

healthCheckProducerEnabled (health)

Used for enabling or disabling all producer based health checks from this component. Notice: Camel has by default disabled all producer based health-checks. You can turn on producer checks globally by setting camel.health.producersEnabled=true.

true

boolean

Endpoint Options

The FTP endpoint is configured using URI syntax:

ftp:host:port/directoryName

With the following path and query parameters:

Path Parameters

Name Description Default Type

host (common)

Required The host name or IP address of the remote server.

String

port (common)

The port of the remote server. When not set, the default port of the protocol is used.

int

directoryName (common)

The starting directory.

String

Query Parameters

Name Description Default Type

binary (common)

Whether to transfer files in binary mode (true) or in ASCII mode (false). Only ftp and ftps use it: sftp and mina-sftp transfer the bytes of the file as they are.

false

boolean

charset (common)

The charset (encoding) of the file content, such as UTF-8. The consumer uses it when the file content is read as text, and the producer writes text with this charset. When writing, Camel may have to read the whole message into memory to convert it to the charset, so do not use it with big messages.

String

disconnect (common)

Whether to disconnect from the remote server right after use: the consumer disconnects after each poll, and the producer after each message it writes. This only closes the current connection: to stop a consumer, stop the consumer or the route instead.

false

boolean

doneFileName (common)

The name of the done file, an empty file that marks a file as complete. Producer: after the file is written, the done file is written in the same directory. Consumer: a file is only consumed when its done file exists in the same directory, and the done file is deleted once the file is consumed (unless noop=true). The name is either a fixed name, or uses the placeholders $\{file:name} and $\{file:name.noext}, which are the only ones supported; the consumer supports the fixed part of the name either as a prefix or as a suffix, not both.

String

fileName (common)

The file name, as an expression such as the File Language. Consumer: only the file with exactly this name is consumed, as the name is not a pattern (use antInclude or include to consume the files that match a pattern); for example consume the file of today with mydata-$\{date:now:yyyyMMdd}.txt. Producer: the name of the file to write; when set, it is used instead of the CamelFileName header, unless that header holds an org.apache.camel.Expression (a String header is used as it is, not evaluated). A String value of this option is evaluated with the File Language, and an Expression object as it is. The producer also supports the CamelOverruleFileName header, which takes precedence over the CamelFileName header and is used only once, so CamelFileName does not have to be stored and restored around the producer.

String

jailStartingDirectory (common)

Used for jailing (restricting) writing files to the starting directory (and sub) only. This is enabled by default to not allow Camel to write files to outside directories (to be more secured out of the box). You can turn this off to allow writing files to directories outside the starting directory, such as parent or root folders. For consumers that use a localWorkDirectory, this also restricts the downloaded files to stay within the configured localWorkDirectory.

true

boolean

passiveMode (common)

Whether to use passive mode for the data connections, in which the client connects to the server, instead of active mode (the default), in which the server connects to the client. Only ftp and ftps use it.

false

boolean

separator (common)

The path separator to use in the paths that Camel sends to the server: UNIX replaces each backslash with a slash, Windows replaces each slash with a backslash, and Auto leaves the separators of the path as they are.

Enum values:

  • UNIX

  • Windows

  • Auto

UNIX

PathSeparator

transferLoggingIntervalSeconds (common)

The interval in seconds between two log messages about the progress of an upload or download that is in progress, so that a long transfer shows its progress.

5

int

transferLoggingLevel (common)

The logging level for the progress of uploads and downloads: their start and end, and the progress of a transfer every transferLoggingIntervalSeconds.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

DEBUG

LoggingLevel

transferLoggingVerbose (common)

Whether to also log each chunk of data that is uploaded or downloaded, and the steps of the connection (connect, login, scanning for files, disconnect), at the transferLoggingLevel.

false

boolean

fastExistsCheck (common (advanced))

Whether ftp and ftps check that a file exists by listing only that file (true), instead of listing its directory and looking for the file name (false). Some FTP servers do not support listing a file directly. The changed read lock (readLock=changed) also uses this option to get the file information. Enabling it speeds up the check when the directory holds many files. The sftp and mina-sftp components check whether a file exists, also for readLock=changed, with a single request whatever the number of files, so this option makes no difference for them.

false

boolean

sendNoop (common (advanced))

Whether to send a noop command to check that the connection is still valid, as a pre-write check before uploading files (producer) and before each poll (consumer), and for ftp and ftps also before renaming or deleting a file on the server, such as when the consumer moves or deletes a processed file. This is enabled by default, which allows to silently re-connect if the connection was lost. However if this causes problems, you can turn this option off, and then a lost connection may only be found when the next operation fails. For example a rename or delete after a long-running route then fails if the server closed the idle connection meanwhile, so the file stays and is polled again, unless an idempotent repository prevents that.

true

boolean

delete (consumer)

If true, the file is deleted after it is processed successfully. Cannot be combined with move.

false

boolean

moveFailed (consumer)

Sets the move failure expression based on Simple language. For example, to move files into a .error subdirectory use: .error. Note: When moving the files to the fail location Camel will handle the error and will not pick up the file again.

String

noop (consumer)

If true, the consumer leaves the file in place: it does not move or delete the file after it is processed (preMove and moveFailed still apply, and delete=true takes precedence over noop). Good for read-only data or ETL. noop=true also turns on idempotent (unless idempotent is set), so the same files are not consumed over and over again.

false

boolean

preMove (consumer)

Expression (such as File Language) used to dynamically set the filename when moving it before processing. For example to move in-progress files into the order directory set this value to order.

String

preSort (consumer)

When pre-sort is enabled then the consumer will sort the file and directory names during polling, that was retrieved from the file system. You may want to do this in case you need to operate on the files in a sorted order. The pre-sort is executed before the consumer starts to filter, and accept files to process by Camel. This option is default=false meaning disabled. The following values are supported: name (sort by file name), modified (sort by last-modified timestamp), size (sort by file size). To sort in descending (reverse) order, prefix the value with a minus sign (e.g., -modified to sort newest first). The value true is an alias for name (backward compatible).

Enum values:

  • true

  • false

  • name

  • -name

  • modified

  • -modified

  • size

  • -size

String

recursive (consumer)

Whether to also consume the files in all the subdirectories of the starting directory (see minDepth and maxDepth).

false

boolean

resumeDownload (consumer)

Whether to resume a download that stopped before the end. The consumer keeps the part already downloaded in the local work directory, and asks the server to restart the transfer from there (the REST command), which the server must support. Requires localWorkDirectory and binary=true.

false

boolean

sendEmptyMessageWhenIdle (consumer)

If the polling consumer did not poll any files, you can enable this option to send an empty message (no body) instead.

false

boolean

streamDownload (consumer)

How the consumer downloads a file when no localWorkDirectory is set. When true, the message body is the stream of the remote file, which the route reads as the file is downloaded. When false, the whole file is loaded into memory before it is sent to the route. For ftp and ftps, stepwise must then be set to false, as both cannot be enabled at the same time.

false

boolean

bridgeErrorHandler (consumer (advanced))

Allows for bridging the consumer to the Camel routing Error Handler, which mean any exceptions (if possible) occurred while the Camel consumer is trying to pickup incoming messages, or the likes, will now be processed as a message and handled by the routing Error Handler. Important: This is only possible if the 3rd party component allows Camel to be alerted if an exception was thrown. Some components handle this internally only, and therefore bridgeErrorHandler is not possible. In other situations we may improve the Camel component to hook into the 3rd party component and make this possible for future releases. By default the consumer will use the org.apache.camel.spi.ExceptionHandler to deal with exceptions, that will be logged at WARN or ERROR level and ignored.

false

boolean

download (consumer (advanced))

Whether the consumer downloads the file. When false, the message body is null, but the consumer still creates an exchange with the details of the file, such as its name and size, in the headers.

true

boolean

exceptionHandler (consumer (advanced))

To let the consumer use a custom ExceptionHandler. Notice if the option bridgeErrorHandler is enabled then this option is not in use. By default the consumer will deal with exceptions, that will be logged at WARN or ERROR level and ignored.

ExceptionHandler

exchangePattern (consumer (advanced))

Sets the exchange pattern when the consumer creates an exchange.

Enum values:

  • InOnly

  • InOut

ExchangePattern

handleDirectoryParserAbsoluteResult (consumer (advanced))

Whether the FTP server lists the entries of a directory with their absolute paths instead of their names. Some FTP servers do so: enable this option for them, and the consumer uses the last segment of each path as the name of the file or directory.

false

boolean

ignoreFileNotFoundOrPermissionError (consumer (advanced))

Whether the consumer ignores a directory or file that does not exist, or that it has no permission for, when it lists a directory or downloads a file. By default, an exception is thrown.

false

boolean

inProgressRepository (consumer (advanced))

A custom org.apache.camel.spi.IdempotentRepository that keeps track of the files being consumed, so that a later poll does not pick up a file that is still in progress. By default, a memory based repository (of up to 50000 entries) is used.

IdempotentRepository

localWorkDirectory (consumer (advanced))

A local directory to download the remote files into, so their content is stored in local files instead of in memory. Useful to save memory when consuming very big files. Not used by the file component.

String

onCompletionExceptionHandler (consumer (advanced))

A custom org.apache.camel.spi.ExceptionHandler that handles the exceptions thrown when the consumer completes a file, by a commit or a rollback (such as moving or deleting the file). By default, the exceptions are logged at WARN level and ignored.

ExceptionHandler

pollStrategy (consumer (advanced))

A pluggable org.apache.camel.PollingConsumerPollingStrategy allowing you to provide your custom implementation to control error handling usually occurred during the poll operation before an Exchange have been created and being routed in Camel.

PollingConsumerPollStrategy

processStrategy (consumer (advanced))

A pluggable org.apache.camel.component.file.GenericFileProcessStrategy allowing you to implement your own readLock option or similar. Can also be used when special conditions must be met before a file can be consumed, such as a special ready file exists. If this option is set then the readLock option does not apply.

GenericFileProcessStrategy

throwExceptionOnConnectFailed (consumer (advanced))

Whether the consumer throws an exception when it cannot connect or log in to the server, or cannot create the starting directory. By default, the consumer logs a WARN and skips the poll. When enabled, the exception goes to the rollback method of the poll strategy (the pollStrategy option), which can handle it.

false

boolean

useList (consumer (advanced))

Whether the consumer lists the directory on the server to find the files to download (the LIST command for ftp and ftps). Set it to false when the server does not allow listing: the consumer then only downloads the file named by the fileName option, which must be set, and the file has no meta-data such as size, timestamp and permissions, as only a listing gives them.

true

boolean

checksumFileAlgorithm (producer)

The algorithm of a checksum to calculate from the content of the written file. The checksum is set in the CamelFileChecksum header (and written to a checksum file, see checksumWriteFile). The name is passed to java.security.MessageDigest, which accepts names such as MD5, SHA-1, SHA-256 or SHA3-256.

Enum values:

  • MD2

  • MD5

  • SHA_1

  • SHA_224

  • SHA_256

  • SHA_384

  • SHA_512

  • SHA_512_224

  • SHA_512_256

  • SHA3_224

  • SHA3_256

  • SHA3_384

  • SHA3_512

String

checksumWriteFile (producer)

Whether to also write the checksum to a file, when checksumFileAlgorithm is set. The checksum file is written in the same directory as the file, with the algorithm as extension (for example hello.txt.MD5 with checksumFileAlgorithm=MD5).

true

boolean

fileExist (producer)

What to do when a file with the same name already exists: - Override - replaces the existing file (the default). - Append - adds the content to the existing file. - Fail - fails with a GenericFileOperationFailedException. - Ignore - keeps the existing file and writes nothing, without failing. - Move - moves the existing file to the name given by the moveExisting option (which must be set) before writing the file. The eagerDeleteTargetFile option controls what happens when a file already exists at that name. - TryRename - only used with tempFileName or tempPrefix: renames the temporary file to the real name without checking whether a file exists, which can be faster on some file systems and FTP servers.

Enum values:

  • Override

  • Append

  • Fail

  • Ignore

  • Move

  • TryRename

Override

GenericFileExist

flatten (producer)

Whether to strip the leading paths from the file name, so only the name of the file is left. The consumer then sets the CamelFileName header to the name only, and the producer strips the paths from the name it writes (from the fileName option or the CamelFileName header). For example, files consumed recursively from subdirectories are then all written in a single directory.

false

boolean

moveExisting (producer)

Expression (such as File Language) used to compute file name to use when fileExist=Move is configured. To move files into a backup subdirectory just enter backup. This option only supports the following File Language tokens: file:name, file:name.ext, file:name.noext, file:onlyname, file:onlyname.noext, file:ext, and file:parent. Notice the file:parent is not supported by the FTP component, as the FTP component can only move any existing files to a relative directory based on current dir as base.

String

tempFileName (producer)

The same as tempPrefix option but offering a more fine grained control on the naming of the temporary filename as it uses the File Language. The location for tempFilename is relative to the final file location in the option 'fileName', not the target directory in the base uri. For example if option fileName includes a directory prefix: dir/finalFilename then tempFileName is relative to that subdirectory dir.

String

tempPrefix (producer)

This option is used to write the file using a temporary name and then, after the write is complete, rename it to the real name. Can be used to identify files being written and also avoid consumers (not using exclusive read locks) reading in progress files. Is often used by FTP when uploading big files.

String

allowNullBody (producer (advanced))

Whether a message with a null body can be written. If true, an empty file is written: an existing file is truncated with fileExist=Override, and left unchanged with fileExist=Append. If false, a null body fails with a GenericFileOperationFailedException.

false

boolean

chmod (producer (advanced))

The permissions to set on each uploaded file, such as 640. Camel sends the command SITE CHMOD with this value after the upload, and does not check the reply of the server.

String

disconnectOnBatchComplete (producer (advanced))

Whether the producer disconnects from the remote server after the last message of a batch, which is a message whose exchange property CamelBatchComplete is true, such as the last file of a poll of a file consumer. This only closes the current connection.

false

boolean

eagerDeleteTargetFile (producer (advanced))

Whether to delete an existing target file before the temporary file is written, when fileExist=Override is used with tempFileName or tempPrefix. Set it to false to keep the existing target file while the temporary file is written, for example when writing big files: the target file is then deleted just before the temporary file is renamed to it. With fileExist=Move, it also controls what happens when a file already exists at the name given by moveExisting: true deletes that file before the move, false fails the move with an exception.

true

boolean

keepLastModified (producer (advanced))

Whether to set the last modified timestamp of the written file to the value of the CamelFileLastModified header (a java.util.Date or a long), for example to keep the timestamp of the source file. Nothing is set when the header is missing. Only used by the file component.

false

boolean

lazyStartProducer (producer (advanced))

Whether the producer should be started lazy (on the first message). By starting lazy you can use this to allow CamelContext and routes to startup in situations where a producer may otherwise fail during starting and cause the route to fail being started. By deferring this startup to be lazy then the startup failure can be handled during routing messages via Camel’s routing error handlers. Beware that when the first message is processed then creating and starting the producer may take a little time and prolong the total processing time of the processing.

false

boolean

moveExistingFileStrategy (producer (advanced))

A custom FileMoveExistingStrategy that moves the existing file when fileExist=Move is used. By default, the component uses its own implementation, which moves the file to the name computed by moveExisting.

FileMoveExistingStrategy

activePortRange (advanced)

The range of local ports that the client listens on for data connections in active mode, as minPort-maxPort with both ports included, for example 10000-19999. Each data connection uses a random port of the range. Not used in passive mode.

String

autoCreate (advanced)

Automatically create missing directories in the file’s pathname. For the file consumer, that means creating the starting directory. For the file producer, it means the directory the files should be written to.

true

boolean

browseLimit (advanced)

Maximum number of messages to keep in memory available for browsing. Use 0 for unlimited.

100

int

bufferSize (advanced)

Buffer size in bytes used for writing files (or in case of FTP for downloading and uploading files).

131072

int

connectTimeout (advanced)

The timeout in milliseconds for establishing the connection to the server. For sftp, mina-sftp and scp, it also applies to the SSH handshake and the login. 0 means no timeout.

10000

int

ftpClient (advanced)

A custom FTPClient (Apache Commons Net) to use instead of the client that Camel creates; for ftps an FTPSClient. Every consumer and producer of the endpoint uses this same instance.

FTPClient

ftpClientConfig (advanced)

A custom FTPClientConfig (Apache Commons Net) for the FTP client, which configures how the client parses directory listings, such as the system type, the date formats, the time zone and the language of the server.

FTPClientConfig

ftpClientConfigParameters (advanced)

Properties to set on the FTPClientConfig, by the names of its setters, such as ftpClientConfig.serverLanguageCode=fr or ftpClientConfig.serverTimeZoneId=Europe/Paris. Without ftpClientConfig, Camel creates an FTPClientConfig for the UNIX system type. This is a multi-value option with prefix: ftpClientConfig.

Map

ftpClientParameters (advanced)

Properties to set on the FTPClient, by the names of its setters, such as ftpClient.controlEncoding=UTF-8. The timeouts ftpClient.soTimeout and ftpClient.dataTimeout, in milliseconds, take precedence over the options soTimeout and timeout. This is a multi-value option with prefix: ftpClient.

Map

maximumReconnectAttempts (advanced)

The maximum number of attempts to connect to the remote server each time a connection is needed, reconnectDelay apart. Default is 3. 0 or less means a single attempt. A login that the server rejects is not retried.

int

reconnectDelay (advanced)

The delay in milliseconds between two attempts to connect to the remote server.

1000

long

siteCommand (advanced)

The SITE commands to send to the FTP server after login. Separate several commands with a new line character. If the server does not accept a command, the connection fails.

String

soTimeout (advanced)

The socket timeout (SO_TIMEOUT) in milliseconds, so that a connection whose server no longer answers does not hang. For ftp and ftps, it is the read timeout of the control connection: a command whose reply does not come within this time fails. For sftp, it is the timeout of the JSch session: when the server sends nothing for this time, JSch sends a keep-alive message, and closes the connection after serverAliveCountMax such messages; it is not used when serverAliveInterval is set. The mina-sftp and scp components do not use it. 0 means no timeout.

300000

int

stepwise (advanced)

Whether to change directory one level at a time when traversing directories to download files, and when uploading a file to a directory. When disabled, the file operations use the full path instead, for example when the server does not allow changing directory. For ftp and ftps, stepwise cannot be used together with streamDownload.

true

boolean

timeout (advanced)

The data timeout in milliseconds. For ftp and ftps, it is the read timeout of the data connection (the data timeout of the Apache Commons Net FTPClient), and 0 means no timeout. For scp, it is the timeout of the JSch session. The sftp and mina-sftp components do not use it.

30000

int

antExclude (filter)

Excludes the files whose path, relative to the starting directory, matches one of these Ant style patterns, such as */.bak. Separate several patterns with a comma. Takes precedence over antInclude.

String

antFilterCaseSensitive (filter)

Whether the antInclude and antExclude patterns are matched case sensitive.

true

boolean

antInclude (filter)

Includes only the files whose path, relative to the starting directory, matches one of these Ant style patterns, such as */.txt. Separate several patterns with a comma.

String

eagerMaxMessagesPerPoll (filter)

Allows for controlling whether the limit from maxMessagesPerPoll is eager or not. If eager then the limit is during the scanning of files, and the file, sftp, mina-sftp and smb consumers stop reading the directory once the limit is hit, unless preSort or doneFileName is used, as they need the whole directory. Where as false would scan all files, and then perform sorting. Setting this option to false allows for sorting all files first, and then limit the poll. Mind that this requires a higher memory usage as all file details are in memory to perform the sorting.

true

boolean

exclude (filter)

Excludes the files whose name matches this regular expression (matched ignoring the case). Takes precedence over include. It is a regular expression, not a wildcard: use antExclude for wildcards, or excludeExt to exclude files by extension. When the expression has characters such as the plus sign, set it with RAW() in an endpoint URI.

String

excludeExt (filter)

Excludes the files with one of these extensions (ignoring the case), separated by comma, for example excludeExt=bak,dat. A file matches when its name ends with a dot and the extension, so both excludeExt=gz and excludeExt=tar.gz match mydata.tar.gz. For more flexibility use the include and exclude options.

String

filter (filter)

Pluggable filter as a org.apache.camel.component.file.GenericFileFilter class. Will skip files if filter returns false in its accept() method.

GenericFileFilter

filterDirectory (filter)

A File Language predicate that filters the subdirectories to scan with recursive=true: only the directories for which it is true are scanned. For example, to scan only the directory of today: $\{file:onlyname} == $\{date:now:yyyyMMdd}.

String

filterFile (filter)

A File Language predicate that filters the files: only the files for which it is true are consumed. For example, to filter on the file extension: $\{file:ext} == 'txt'.

String

idempotent (filter)

Option to use the Idempotent Consumer EIP pattern to let Camel skip already processed files. Will by default use a memory based LRUCache that holds 1000 entries. If noop=true then idempotent will be enabled as well to avoid consuming the same files over and over again. Setting only idempotentRepository or idempotentKey does not turn it on.

false

Boolean

idempotentEager (filter)

Sets whether to eagerly add the filename to the idempotent repository or wait until the exchange is complete. Does not apply with an idempotent read lock (readLock=idempotent, idempotent-changed or idempotent-rename), which adds the filename when it acquires the lock.

true

Boolean

idempotentKey (filter)

To use a custom idempotent key. By default the absolute path of the file is used. You can use the File Language, for example to use the file name and file size, you can do: idempotentKey=$\{file:name}-$\{file:size}. It is used only with idempotent=true (noop=true turns it on), or by an idempotent read lock (readLock=idempotent, idempotent-changed or idempotent-rename) of the file component.

String

idempotentRepository (filter)

A pluggable repository org.apache.camel.spi.IdempotentRepository which by default use MemoryIdempotentRepository if none is specified and idempotent is true. It is used only with idempotent=true (noop=true turns it on), or by an idempotent read lock (readLock=idempotent, idempotent-changed or idempotent-rename) of the file component. Set without them, it does not skip any file.

IdempotentRepository

include (filter)

Includes only the files whose name matches this regular expression (matched ignoring the case). It is a regular expression, not a wildcard: use antInclude for wildcards, or includeExt to include files by extension. When the expression has characters such as the plus sign, set it with RAW() in an endpoint URI.

String

includeExt (filter)

Includes only the files with one of these extensions (ignoring the case), separated by comma, for example includeExt=txt,xml. A file matches when its name ends with a dot and the extension, so both includeExt=gz and includeExt=tar.gz match mydata.tar.gz. For more flexibility use the include and exclude options.

String

maxDepth (filter)

The maximum depth to traverse when recursively processing a directory. maxDepth=1 means only the starting directory.

2147483647

int

maxMessagesPerPoll (filter)

The maximum number of files to consume in one poll. 0 or negative (the default) means no limit. Can be used, for example, to avoid picking up thousands of files at once when the server starts. With eagerMaxMessagesPerPoll=true (the default) the limit applies while the files are scanned, before any sorting: with 100000 files and maxMessagesPerPoll=500, the first 500 files found are taken and then sorted. Set eagerMaxMessagesPerPoll=false to scan and sort all the files first, and then take the limit.

int

minDepth (filter)

The minimum depth to start processing when recursively processing a directory. Using minDepth=1 means the base directory. Using minDepth=2 means the first sub directory.

int

move (filter)

Expression (such as Simple Language) used to dynamically set the filename when moving it after processing. To move files into a .done subdirectory just enter .done.

String

exclusiveReadLockStrategy (lock)

A custom org.apache.camel.component.file.GenericFileExclusiveReadLockStrategy to use as the read lock. When set, the readLock option is not used.

GenericFileExclusiveReadLockStrategy

readLock (lock)

The read lock strategy, so that the consumer only picks up a file that is not being written (in progress). The consumer waits for the read lock up to readLockTimeout. The strategies are: - none - no read lock is used. - changed - uses the length and the modification timestamp of the file to detect whether it is still being written, so files cannot be consumed as fast as with the others. The option readLockCheckInterval sets the time between two checks. - rename - tries to rename the file, to test whether the consumer can get an exclusive read lock. The other read locks of the file component (markerFile, fileLock and the idempotent read locks) are not supported, and fail when the consumer is created.

Enum values:

  • none

  • rename

  • changed

none

String

readLockCheckInterval (lock)

The interval in millis between the attempts to acquire the read lock, for the read locks that retry (changed, fileLock and rename, and also idempotent-changed and idempotent-rename of the file component). For example, set a higher interval with readLock=changed to cater for slow writes. The ftp, ftps, sftp, mina-sftp and azure-files components use 5000 by default. readLockTimeout must be higher than readLockCheckInterval; as a rule of thumb, make the timeout at least 2 or 3 times the interval, so the read lock has enough time to be acquired before the timeout.

1000

long

readLockLoggingLevel (lock)

The logging level of the message logged when a read lock cannot be acquired, for example OFF for no logging. Used by the read locks changed, fileLock, idempotent, idempotent-changed, idempotent-rename and rename.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

DEBUG

LoggingLevel

readLockMarkerFile (lock)

Whether the changed, fileLock and rename read locks also create a marker file, to keep other processes from picking up the same files. Set it to false, for example, to not write marker files to the file system. Only used by the file component.

true

boolean

readLockMinAge (lock)

The minimum age in millis a file must have before the changed read lock (readLock=changed or idempotent-changed) acquires it, for example readLockMinAge=300s for 5 minutes. When set, the read lock acquires a file as soon as it is older than this, without waiting for its length and timestamp to stay the same, which can make it faster.

0

long

readLockMinLength (lock)

The minimum length in bytes a file must have before the changed read lock (readLock=changed or idempotent-changed) acquires it. The default 1 means an empty file is not consumed; set 0 to consume empty files.

1

long

readLockTimeout (lock)

The timeout in millis to acquire the read lock. When the lock is not granted within the timeout, the file is skipped and tried again on the next poll. 0 or lower waits forever. Used by the changed, fileLock and rename read locks (and also idempotent-changed and idempotent-rename of the file component). The ftp, ftps, sftp, mina-sftp and azure-files components use 20000 by default. readLockTimeout must be higher than readLockCheckInterval; as a rule of thumb, make the timeout at least 2 or 3 times the interval, so the read lock has enough time to be acquired before the timeout.

10000

long

backoffErrorThreshold (scheduler)

The number of subsequent error polls (failed due some error) that should happen before the backoffMultipler should kick-in.

int

backoffIdleThreshold (scheduler)

The number of subsequent idle polls that should happen before the backoffMultipler should kick-in.

int

backoffMultiplier (scheduler)

To let the scheduled polling consumer backoff if there has been a number of subsequent idles/errors in a row. The multiplier is then the number of polls that will be skipped before the next actual attempt is happening again. When this option is in use then backoffIdleThreshold and/or backoffErrorThreshold must also be configured.

int

delay (scheduler)

Milliseconds before the next poll.

500

long

greedy (scheduler)

If greedy is enabled, then the ScheduledPollConsumer will run immediately again, if the previous run polled 1 or more messages.

false

boolean

healthCheckMaxPollDuration (scheduler)

How long a poll may run before the health check of the consumer reports DOWN. The health check is otherwise based on the polls that are done, so it stays UP while a poll hangs, for example on a read without timeout from a connection that went silent. A poll includes routing the messages it polled, so set this above the longest poll you expect. The poll is not interrupted. The value is in millis (not affected by timeUnit). The default 0 turns this off.

0

long

initialDelay (scheduler)

Milliseconds before the first poll starts.

1000

long

repeatCount (scheduler)

Specifies a maximum limit of number of fires. So if you set it to 1, the scheduler will only fire once. If you set it to 5, it will only fire five times. A value of zero or negative means fire forever.

0

long

runLoggingLevel (scheduler)

The consumer logs a start/complete log line when it polls. This option allows you to configure the logging level for that.

Enum values:

  • TRACE

  • DEBUG

  • INFO

  • WARN

  • ERROR

  • OFF

TRACE

LoggingLevel

scheduledExecutorService (scheduler)

Allows for configuring a custom/shared thread pool to use for the consumer. By default each consumer has its own single threaded thread pool.

ScheduledExecutorService

scheduler (scheduler)

To use a cron scheduler from either camel-spring or camel-quartz component. Use value spring or quartz for built in scheduler.

none

Object

schedulerProperties (scheduler)

To configure additional properties when using a custom scheduler or any of the Quartz, Spring based scheduler. This is a multi-value option with prefix: scheduler.

Map

startScheduler (scheduler)

Whether the scheduler should be auto started.

true

boolean

timeUnit (scheduler)

Time unit for initialDelay and delay options.

Enum values:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

MILLISECONDS

TimeUnit

useFixedDelay (scheduler)

Controls if fixed delay or fixed rate is used. See ScheduledExecutorService in JDK for details.

true

boolean

account (security)

The account to log in with, sent with the FTP ACCT command when the server asks for an account after the password. Without a username, Camel logs in as anonymous with this account.

String

password (security)

Password to use for login.

String

username (security)

The user name to log in with. For ftp and ftps, the login is anonymous when it is not set.

String

shuffle (sort)

To shuffle the list of files (sort in random order).

false

boolean

sortBy (sort)

Sorts the files with File Language expressions, such as sortBy=file:name. Separate several groups with a semicolon to sort by the next group when the previous one is equal, such as sortBy=file:modified;file:name. Prefix a group with reverse: to sort it in reverse order, and with ignoreCase: to compare text ignoring the case (reverse: comes first when both are used).

String

sorter (sort)

Pluggable sorter as a java.util.Comparator class that compares org.apache.camel.component.file.GenericFile objects.

Comparator

Message Headers

The FTP component supports the following message header(s), which is/are listed below:

Name Description Default Type

CamelFileLength (consumer)

Constant: FILE_LENGTH

A long value containing the file size.

long

CamelFileLastModified (consumer)

Constant: FILE_LAST_MODIFIED

A Long value containing the last modified timestamp of the file.

long

CamelFileNameOnly (consumer)

Constant: FILE_NAME_ONLY

Only the file name (the name with no leading paths).

String

CamelFileName (common)

Constant: FILE_NAME

(producer) Specifies the name of the file to write (relative to the endpoint directory). This name can be a String; a String with a file or simple Language expression; or an Expression object. If it’s null then Camel will auto-generate a filename based on the message unique ID. (consumer) Name of the consumed file as a relative file path with offset from the starting directory configured on the endpoint.

String

CamelFileNameConsumed (consumer)

Constant: FILE_NAME_CONSUMED

The name of the file that has been consumed.

String

CamelFileAbsolute (consumer)

Constant: FILE_ABSOLUTE

Whether the path of the consumed file is absolute (true), or relative (false).

Boolean

CamelFileAbsolutePath (consumer)

Constant: FILE_ABSOLUTE_PATH

The absolute path to the file. For relative files this path holds the relative path instead.

String

CamelFilePath (consumer)

Constant: FILE_PATH

The file path. For relative files this is the starting directory. For absolute files this is the absolute path.

String

CamelFileRelativePath (consumer)

Constant: FILE_RELATIVE_PATH

The relative path.

String

CamelFileParent (common)

Constant: FILE_PARENT

The parent path.

String

CamelFileNameProduced (producer)

Constant: FILE_NAME_PRODUCED

The path and name of the file that the producer wrote: the starting directory of the endpoint followed by the file name. This header is set by Camel, to provide the name of the file that was written.

String

CamelOverruleFileName (producer)

Constant: OVERRULE_FILE_NAME

Is used for overruling CamelFileName header and use the value instead (but only once, as the producer will remove this header after writing the file). The value can only be a String. Notice that if the option fileName has been configured, then this is still being evaluated.

Object

CamelFileLocalWorkPath (consumer)

Constant: FILE_LOCAL_WORK_PATH

Path to the local work file, if local work directory is used.

String

CamelRemoteFileInputStream (consumer)

Constant: REMOTE_FILE_INPUT_STREAM

The input stream of the remote file, when the consumer uses streamDownload=true.

InputStream

CamelFileHost (consumer)

Constant: FILE_HOST

The remote hostname.

String

CamelFtpReplyCode (common)

Constant: FTP_REPLY_CODE

The reply code of the last operation on the server. For ftp and ftps, it is the reply code of the FTP server. For sftp, it is the SFTP status code, 0 when the operation succeeded. The mina-sftp component does not set it.

int

CamelFtpReplyString (common)

Constant: FTP_REPLY_STRING

The reply text of the last operation on the server. For ftp and ftps, it is the reply text of the FTP server. For sftp, it is OK when the operation succeeded, or the error message. The mina-sftp component does not set it.

String

Message Body

The message body at each side of the FTP component: Consumer is the body of the messages the consumer creates, Consumer reply the bodies a consumer that answers its caller can reply with, Producer input the bodies the producer can send or write, and Producer output the body after the producer.

Side Body Description

Consumer

file

The file as read: a RemoteFile, which converts to text, bytes or a stream; a stream with streamDownload; with preMove its content, a byte array.

  • With streamDownload=true: stream

  • With download=false: null

Not known when preMove is set.

Producer input

text, bytes, stream or file

What converts to an InputStream: text, bytes, a stream or a file. A Map or a List fails: marshal it first.

  • With allowNullBody=true: null, text, bytes, stream or file

Producer output

unchanged

The bodies are the ones with the default options. A side that is not listed is not known, and tooling does not guess it. The carriers, the sides and the tools that use them are described in Message Body Types.

Usage

FTPS host name verification

The FTPS client that Camel creates checks, on the control connection, that the certificate of the server matches the host of the endpoint, with the same rules as an HTTPS client. The check happens during the TLS handshake, before login. Data connections (PROT P) use the same trust manager, but Apache Commons Net does not check their host name. A connection to an IP address needs a certificate that lists that address as a subject alternative name. Set hostnameVerification=false to turn this check off; the certificate is still checked by the trust manager. The option does not apply to a custom ftpClient.

Use the hostnameVerification option to control the check. Setting ftpClient.endpointCheckingEnabled on the endpoint also turns it on or off, and takes precedence over hostnameVerification, but the security policy (for example camel.main.profile=prod) only checks the hostnameVerification option.

FTPS component default trust store

Without trust settings, an ftps endpoint checks the certificate of the server against the default trust store of the JVM: the cacerts file of the JDK, or the trust store set with the javax.net.ssl.trustStore system property. A server certificate signed by a public certificate authority needs no configuration.

For a server with a self-signed certificate, or a certificate signed by your own certificate authority, put that certificate (or the certificate of the authority) in a trust store and configure the endpoint with one of:

  • the ftpClient.trustStore. options: ftpClient.trustStore.file, ftpClient.trustStore.password, and optionally ftpClient.trustStore.type (the default key store type of the JVM by default) and ftpClient.trustStore.algorithm (the default trust manager algorithm of the JVM by default).

  • sslContextParameters: the trust store is then the one of the provided SSLContextParameters instance, and the ftpClient.keyStore. and ftpClient.trustStore. options are not used.

ftps://admin@myserver/inbox?password=RAW(secret)&ftpClient.trustStore.file=/etc/camel/ftps-truststore.p12&ftpClient.trustStore.type=PKCS12&ftpClient.trustStore.password=RAW(changeit)

A custom ftpClient (an FTPSClient instance) keeps the trust manager it was created with: Camel does not change it. To check the server certificate in another way, configure the trust manager yourself, on a custom ftpClient with setTrustManager, or with the trust managers of sslContextParameters.

You can configure additional options on the ftpClient and ftpClientConfig from the URI directly by using the ftpClient. or ftpClientConfig. prefix.

For example, to set the setDataTimeout on the FTPClient to 30 seconds you can do:

  • Java

  • XML

  • YAML

from("ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000").to("bean:foo");
<route>
  <from uri="ftp://foo@myserver?password=secret&amp;ftpClient.dataTimeout=30000"/>
  <to uri="bean:foo"/>
</route>
- route:
    from:
      uri: ftp://foo@myserver
      parameters:
        password: secret
        ftpClient.dataTimeout: 30000
      steps:
        - to:
            uri: bean:foo

You can mix and match and use both prefixes, for example, to configure date format or timezones.

  • Java

  • XML

  • YAML

from("ftp://foo@myserver?password=secret&ftpClient.dataTimeout=30000&ftpClientConfig.serverLanguageCode=fr").to("bean:foo");
<route>
  <from uri="ftp://foo@myserver?password=secret&amp;ftpClient.dataTimeout=30000&amp;ftpClientConfig.serverLanguageCode=fr"/>
  <to uri="bean:foo"/>
</route>
- route:
    from:
      uri: ftp://foo@myserver
      parameters:
        password: secret
        ftpClient.dataTimeout: 30000
        ftpClientConfig.serverLanguageCode: fr
      steps:
        - to:
            uri: bean:foo

You can have as many of these options as you like.

See the documentation of the Apache Commons FTP FTPClientConfig for possible options and more details. And as well for Apache Commons FTP FTPClient.

If you do not like having many and long configurations in the url, you can refer to the ftpClient or ftpClientConfig to use by letting Camel lookup in the Registry for it.

For example:

   <bean id="myConfig" class="org.apache.commons.net.ftp.FTPClientConfig">
       <property name="lenientFutureDates" value="true"/>
       <property name="serverLanguageCode" value="fr"/>
   </bean>

And then let Camel look up this bean when you use the # notation in the url.

  • Java

  • XML

  • YAML

from("ftp://foo@myserver?password=secret&ftpClientConfig=#myConfig").to("bean:foo");
<route>
  <from uri="ftp://foo@myserver?password=secret&amp;ftpClientConfig=#myConfig"/>
  <to uri="bean:foo"/>
</route>
- route:
    from:
      uri: ftp://foo@myserver
      parameters:
        password: secret
        ftpClientConfig: "#myConfig"
      steps:
        - to:
            uri: bean:foo

Concurrency

The FTP consumer (with the same endpoint) does not support concurrency (the backing FTP client is not thread safe). You can use multiple FTP consumers to poll from different endpoints. It is only a single endpoint that does not support concurrent consumers.

The FTP producer does not have this issue, it supports concurrency.

When the route hands the file over to another thread, for example with to("seda:…​"), the file is deleted or moved (delete, move, moveFailed) on that thread, when it is done with the file, on the connection of the consumer. The ftp and ftps consumers run one operation at a time on their connection, so such a delete or move waits until the consumer is done with its current operation (such as the download of the next file), and the other way around.

A server that stops answering

When the FTP/FTPS server stops answering on an open connection (it hangs, or a firewall drops the connection without closing it), the client notices it only when soTimeout expires (or timeout during a transfer). Camel then does not wait on that connection again:

  • When the consumer retrieves a file and the server does not answer in time, only that file fails: the consumer closes the connection, which it cannot use any more, and leaves the other files of the poll to the next poll, which connects again. With streamDownload=true, the route reads the file from the server: when that read times out, the file fails in the route, and the consumer waits up to soTimeout for the reply that ends the transfer, then closes the connection in the same way.

  • After a failed poll, the consumer closes the connection without sending QUIT.

  • When disconnecting, for example when the consumer or the producer stops, the client sends QUIT and waits at most 2 seconds (soTimeout when it is shorter) for its reply.

File and directory names with a line break

The FTP control connection sends one command per line, so a remote file or directory name with a carriage return or a line feed cannot be sent as the argument of one command. The ftp and ftps components refuse such a name with a GenericFileOperationFailedException before they send any command for it, for example when the producer writes a file whose CamelFileName header has a line break. Remove or replace these characters in the name before the producer.

Default when consuming files

The FTP consumer will by default leave the consumed files untouched on the remote FTP server. You have to configure it explicitly if you want it to delete the files or move them to another location. For example, you can use delete=true to delete the files, or use move=.done to move the files into a hidden done subdirectory.

The regular File consumer is different as it will by default move files to a .camel sub directory. The reason Camel does not do this by default for the FTP consumer is that it may lack permissions by default to be able to move or delete files.

limitations

The option readLock can be used to force Camel not to consume files that are currently in the progress of being written. However, this option is turned off by default, as it requires that the user has write access. See the options table for more details about read locks. There are other solutions to avoid consuming files that are currently being written over FTP; for instance, you can write to a temporary destination and move the file after it has been written.

The ftp, ftps and sftp consumers support the read locks none, rename and changed. readLock=false and readLock=off mean none. Any other readLock value, such as the markerFile, fileLock, idempotent, idempotent-changed and idempotent-rename read locks of the File component, fails when the consumer is created, also with poll and pollEnrich, with IllegalArgumentException: ReadLock invalid. The readLock option is not checked when a custom exclusiveReadLockStrategy or processStrategy is set, as it does not apply then.

When moving files using move or preMove option the files are restricted to the FTP_ROOT folder. That prevents you from moving files outside the FTP area. If you want to move files to another area, you can use soft links and move files into a soft linked folder.

Exchange Properties

Camel sets the following exchange properties

Header Description

CamelBatchIndex

The current index out of total number of files being consumed in this batch.

CamelBatchSize

The total number of files being consumed in this batch.

CamelBatchComplete

true if there are no more files in this batch.

About timeouts

FTP and FTPS use Apache Commons Net and SFTP uses JSch, so the same options map to different settings of each library. All timeout values are in milliseconds.

Option Default What it bounds

connectTimeout

10 seconds

Opening the connection to the server (FTP, FTPS and SFTP).

soTimeout

5 minutes

FTP/FTPS: each read on the control connection, that is the wait for the reply to every command (login, NOOP, changing directory, listing, the end of each transfer). It corresponds to ftpClient.soTimeout. For SFTP, see Timeouts and dead connections.

timeout

30 seconds

FTP/FTPS only: each read on the data connection (downloads and directory listings). It corresponds to ftpClient.dataTimeout. It does not bound an upload, which only writes to the data connection.

Noticing a dead or silent server

A server that stops answering without closing the connection (the host is gone, or a firewall or NAT drops the packets) is noticed only when one of these timeouts expires. With the defaults, every command on such a connection waits up to 5 minutes for its reply, for example the NOOP that the producer sends before each upload to check the connection (sendNoop=true). These durations are how the client libraries behave, approximately, not guarantees of Camel. Lower soTimeout to a little more than your server needs to answer a command:

ftp://scott@ftp.example.com/inbox?password=RAW(tiger)&connectTimeout=5000&soTimeout=30000&throwExceptionOnConnectFailed=true

By default, a consumer that cannot connect or log in logs a WARN once and skips the poll, which counts as a successful poll: its health check stays UP for the whole outage. With throwExceptionOnConnectFailed=true the failed connection fails the poll, so the health check reports the consumer DOWN and the pollStrategy gets the error. This applies to FTP, FTPS and SFTP.

Uploads interrupted by a broken connection

When the connection breaks during an upload, the server usually keeps the part it received under the name of the file, and the producer does not remove it: a consumer on the other side can pick up a truncated file. Upload under a temporary name with tempPrefix or tempFileName. The producer renames the file to its final name only once the upload is complete, and a redelivery replaces the temporary file left by the failed attempt.

Transfer mode

FTP and FTPS transfer files in ASCII mode by default (binary=false), which converts line endings and so corrupts any file that is not text. Set binary=true for such files.

Using Local Work Directory

Camel supports consuming from remote FTP servers and downloading the files directly into a local work directory. This avoids reading the entire remote file content into memory as it is streamed directly into the local file using FileOutputStream.

Camel will store to a local file with the same name as the remote file, though with .inprogress as the extension while the file is being downloaded. Afterward, the file is renamed to remove the .inprogress suffix. And finally, when the Exchange is complete, the local file is deleted.

So if you want to download files from a remote FTP server and store it as files, then you need to route to a file endpoint such as:

  • Java

  • XML

  • YAML

from("ftp://someone@someserver.com?password=secret&localWorkDirectory=/tmp").to("file://inbox");
<route>
  <from uri="ftp://someone@someserver.com?password=secret&amp;localWorkDirectory=/tmp"/>
  <to uri="file://inbox"/>
</route>
- route:
    from:
      uri: ftp://someone@someserver.com
      parameters:
        password: secret
        localWorkDirectory: /tmp
      steps:
        - to:
            uri: file://inbox

The route above is ultra efficient as it avoids reading the entire file content into memory. It will download the remote file directly to a local file stream. The java.io.File handle is then used as the Exchange body. The file producer leverages this fact and can work directly on the work file java.io.File handle and perform a java.io.File.rename to the target filename. As Camel knows it’s a local work file, it can optimize and use a rename instead of a file copy, as the work file is meant to be deleted anyway.

Stepwise changing directories

Camel FTP can operate in two modes in terms of traversing directories when consuming files (e.g., downloading) or producing files (e.g., uploading)

  • stepwise

  • not stepwise

You may want to pick either one depending on your situation and security issues. Some Camel end users can only download files if they use stepwise, while others can only download if they do not.

You can use the stepwise option to control the behavior.

Note that stepwise changing of directory will in most cases only work when the user is confined to its home directory and when the home directory is reported as "/".

The difference between the two of them is best illustrated with an example. Suppose we have the following directory structure on the remote FTP server, we need to traverse and download files:

/
/one
/one/two
/one/two/sub-a
/one/two/sub-b

And that we have a file in each of sub-a (a.txt) and sub-b (b.txt) folder.

  • Default (Stepwise enabled)

  • Stepwise Disabled

Using stepwise=true (default mode)
TYPE A
200 Type set to A
PWD
257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
250 CWD successful. "/one/two" is current directory.
SYST
215 UNIX emulated by FileZilla
PORT 127,0,0,1,17,94
200 Port command successful
LIST
150 Opening data channel for directory list.
226 Transfer OK
CWD sub-a
250 CWD successful. "/one/two/sub-a" is current directory.
PORT 127,0,0,1,17,95
200 Port command successful
LIST
150 Opening data channel for directory list.
226 Transfer OK
CDUP
200 CDUP successful. "/one/two" is current directory.
CWD sub-b
250 CWD successful. "/one/two/sub-b" is current directory.
PORT 127,0,0,1,17,96
200 Port command successful
LIST
150 Opening data channel for directory list.
226 Transfer OK
CDUP
200 CDUP successful. "/one/two" is current directory.
CWD /
250 CWD successful. "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
250 CWD successful. "/one/two" is current directory.
PORT 127,0,0,1,17,97
200 Port command successful
RETR foo.txt
150 Opening data channel for file transfer.
226 Transfer OK
CWD /
250 CWD successful. "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
250 CWD successful. "/one/two" is current directory.
CWD sub-a
250 CWD successful. "/one/two/sub-a" is current directory.
PORT 127,0,0,1,17,98
200 Port command successful
RETR a.txt
150 Opening data channel for file transfer.
226 Transfer OK
CWD /
250 CWD successful. "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
250 CWD successful. "/one/two" is current directory.
CWD sub-b
250 CWD successful. "/one/two/sub-b" is current directory.
PORT 127,0,0,1,17,99
200 Port command successful
RETR b.txt
150 Opening data channel for file transfer.
226 Transfer OK
QUIT
221 Goodbye
disconnected.

As you can see when stepwise is enabled, it will traverse the directory structure using CD xxx. The current directory is asked for only when the connection does not know it, usually once per connection, and after a download the connection stays in the directory of the file: the next file in the same directory is downloaded without changing directory, and the connection changes back only before an operation that needs the starting directory.

Using stepwise=false
230 Logged on
TYPE A
200 Type set to A
SYST
215 UNIX emulated by FileZilla
PORT 127,0,0,1,4,122
200 Port command successful
LIST one/two
150 Opening data channel for directory list
226 Transfer OK
PORT 127,0,0,1,4,123
200 Port command successful
LIST one/two/sub-a
150 Opening data channel for directory list
226 Transfer OK
PORT 127,0,0,1,4,124
200 Port command successful
LIST one/two/sub-b
150 Opening data channel for directory list
226 Transfer OK
PORT 127,0,0,1,4,125
200 Port command successful
RETR one/two/foo.txt
150 Opening data channel for file transfer.
226 Transfer OK
PORT 127,0,0,1,4,126
200 Port command successful
RETR one/two/sub-a/a.txt
150 Opening data channel for file transfer.
226 Transfer OK
PORT 127,0,0,1,4,127
200 Port command successful
RETR one/two/sub-b/b.txt
150 Opening data channel for file transfer.
226 Transfer OK
QUIT
221 Goodbye
disconnected.

As you can see when not using stepwise, there is no CD operation invoked at all.

Filtering Strategies

Camel supports pluggable filtering strategies. They are described below.

See also the documentation for filtering strategies on the File component.

Custom filtering

Camel supports pluggable filtering strategies. This strategy it to use the build in org.apache.camel.component.file.GenericFileFilter in Java. You can then configure the endpoint with such a filter to skip certain filters before being processed.

In the sample, we have built our own filter that only accepts files starting with report in the filename.

And then we can configure our route using the filter attribute to reference our filter (using # notation) that we have defined in the spring XML file:

  • Java

  • XML

  • YAML

from("ftp://someuser@someftpserver.com?password=secret&filter=#myFilter")
    .to("bean:processInbox");
   <!-- define our sorter as a plain spring bean -->
   <bean id="myFilter" class="com.mycompany.MyFileFilter"/>

  <route>
    <from uri="ftp://someuser@someftpserver.com?password=secret&amp;filter=#myFilter"/>
    <to uri="bean:processInbox"/>
  </route>
- route:
    from:
      uri: ftp://someuser@someftpserver.com
      parameters:
        password: secret
        filter: "#myFilter"
      steps:
        - to:
            uri: bean:processInbox

Filtering using ANT path matcher

The ANT path matcher is a filter shipped out-of-the-box with the file component: the antInclude and antExclude options need no other dependency. Use them for wildcards such as *.txt: the fileName option is a file name, not a pattern, and the include and exclude options are regular expressions.

The file paths are matched with the following rules:

  • ? matches one character

  • * matches zero or more characters

  • ** matches zero or more directories in a path

The sample below demonstrates how to use it:

  • Java

  • XML

  • YAML

from("ftp://admin@localhost:2222/public/camel?antInclude=**/*.txt").to("...");
<route>
  <from uri="ftp://admin@localhost:2222/public/camel?antInclude=**/*.txt"/>
  <to uri="..."/>
</route>
- route:
    from:
      uri: ftp://admin@localhost:2222/public/camel
      parameters:
        antInclude: "**/*.txt"
      steps:
        - to:
            uri: "..."

Using a proxy with SFTP

To use an HTTP proxy to connect to your remote host, you can configure your route in the following way:

  • Java

  • XML

  • YAML

from("sftp://localhost:9999/root?username=admin&password=admin&proxy=#proxy")
    .to("bean:processFile");
<!-- define our sorter as a plain spring bean -->
<bean id="proxy" class="com.jcraft.jsch.ProxyHTTP">
  <constructor-arg value="localhost"/>
  <constructor-arg value="7777"/>
</bean>

<route>
  <from uri="sftp://localhost:9999/root?username=admin&amp;password=admin&amp;proxy=#proxy"/>
  <to uri="bean:processFile"/>
</route>
- route:
    from:
      uri: sftp://localhost:9999/root
      parameters:
        username: admin
        password: admin
        proxy: "#proxy"
      steps:
        - to:
            uri: bean:processFile

You can also assign a username and password to the proxy, if necessary. Please consult the documentation for com.jcraft.jsch.Proxy to discover all options.

Setting preferred SFTP authentication method

If you want to explicitly specify the list of authentication methods that should be used by sftp component, use preferredAuthentications option. If, for example, you would like Camel to attempt to authenticate with a private/public SSH key and fallback to user/password authentication in the case when no public key is available, use the following route configuration:

  • Java

  • XML

  • YAML

from("sftp://localhost:9999/root?username=admin&password=admin&preferredAuthentications=publickey,password")
    .to("bean:processFile");
<route>
  <from uri="sftp://localhost:9999/root?username=admin&amp;password=admin&amp;preferredAuthentications=publickey,password"/>
  <to uri="bean:processFile"/>
</route>
- route:
    from:
      uri: sftp://localhost:9999/root
      parameters:
        username: admin
        password: admin
        preferredAuthentications: publickey,password
      steps:
        - to:
            uri: bean:processFile

Consuming a single file using a fixed name

When you want to download a single file and knows the file name, you can use fileName=myFileName.txt to tell Camel the name of the file to download. By default, the consumer will still do an FTP LIST command to do a directory listing and then filter these files based on the fileName option. Though in this use-case it may be desirable to turn off the directory listing by setting useList=false. For example, the user account used to log in to the FTP server may not have permission to do an FTP LIST command. So you can turn off this with useList=false, and then provide the fixed name of the file to download with fileName=myFileName.txt, then the FTP consumer can still download the file. If the file for some reason does not exist, then Camel will by default throw an exception, you can turn this off and ignore this by setting ignoreFileNotFoundOrPermissionError=true.

For example, to have a Camel route that picks up a single file, and delete it after use you can do

  • Java

  • XML

  • YAML

from("ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true")
  .to("activemq:queue:report");
<route>
  <from uri="ftp://admin@localhost:21/nolist/?password=admin&amp;stepwise=false&amp;useList=false&amp;ignoreFileNotFoundOrPermissionError=true&amp;fileName=report.txt&amp;delete=true"/>
  <to uri="activemq:queue:report"/>
</route>
- route:
    from:
      uri: ftp://admin@localhost:21/nolist/
      parameters:
        password: admin
        stepwise: false
        useList: false
        ignoreFileNotFoundOrPermissionError: true
        fileName: report.txt
        delete: true
      steps:
        - to:
            uri: activemq:queue:report

Notice that we have used all the options we talked above.

You can also use this with ConsumerTemplate. For example, to download a single file (if it exists) and grab the file content as a String type:

Java-only: using ConsumerTemplate to download a single file
String data = template.retrieveBodyNoWait("ftp://admin@localhost:21/nolist/?password=admin&stepwise=false&useList=false&ignoreFileNotFoundOrPermissionError=true&fileName=report.txt&delete=true", String.class);

Debug logging

This component has log level TRACE that can be helpful if you have problems.

Why does FTP component not download any files?

The FTP component has many options. So make sure you have configured it properly. Also, a common issue is that you have to use either active or passive mode. So you may have to set passiveMode=true on the endpoint configuration. When the server refuses the listing of the directory, for example the PORT command of active mode, the poll fails and the consumer logs the reply of the server.

Examples

In the sample below, we set up Camel to download all the reports from the FTP server once every hour (60 min) as BINARY content and store it as files on the local file system.

  • Java

  • XML

  • YAML

from("ftp://scott@localhost/public/reports?password=tiger&binary=true&delay=60000")
    .to("file://target/test-reports");
<route>
  <from uri="ftp://scott@localhost/public/reports?password=tiger&amp;binary=true&amp;delay=60000"/>
  <to uri="file://target/test-reports"/>
</route>
- route:
    from:
      uri: ftp://scott@localhost/public/reports
      parameters:
        password: tiger
        binary: true
        delay: "60000"
      steps:
        - to:
            uri: file://target/test-reports

Consuming a remote FTPS server (implicit SSL) and client authentication

  • Java

  • XML

  • YAML

from("ftps://admin@localhost:2222/public/camel?password=admin&securityProtocol=SSL&implicit=true&ftpClient.keyStore.file=./src/test/resources/server.jks&ftpClient.keyStore.password=password&ftpClient.keyStore.keyPassword=password")
    .to("bean:foo");
<route>
  <from uri="ftps://admin@localhost:2222/public/camel?password=admin&amp;securityProtocol=SSL&amp;implicit=true&amp;ftpClient.keyStore.file=./src/test/resources/server.jks&amp;ftpClient.keyStore.password=password&amp;ftpClient.keyStore.keyPassword=password"/>
  <to uri="bean:foo"/>
</route>
- route:
    from:
      uri: ftps://admin@localhost:2222/public/camel
      parameters:
        password: admin
        securityProtocol: SSL
        implicit: true
        ftpClient.keyStore.file: ./src/test/resources/server.jks
        ftpClient.keyStore.password: password
        ftpClient.keyStore.keyPassword: password
      steps:
        - to:
            uri: bean:foo

Consuming a remote FTPS server (explicit TLS) and a custom trust store configuration

  • Java

  • XML

  • YAML

from("ftps://admin@localhost:2222/public/camel?password=admin&ftpClient.trustStore.file=./src/test/resources/server.jks&ftpClient.trustStore.password=password")
    .to("bean:foo");
<route>
  <from uri="ftps://admin@localhost:2222/public/camel?password=admin&amp;ftpClient.trustStore.file=./src/test/resources/server.jks&amp;ftpClient.trustStore.password=password"/>
  <to uri="bean:foo"/>
</route>
- route:
    from:
      uri: ftps://admin@localhost:2222/public/camel
      parameters:
        password: admin
        ftpClient.trustStore.file: ./src/test/resources/server.jks
        ftpClient.trustStore.password: password
      steps:
        - to:
            uri: bean:foo

Examples

ftp://someone@someftpserver.com/public/upload/images/holiday2008?password=secret&binary=true

ftp://someoneelse@someotherftpserver.co.uk:12049/reports/2008/password=secret&binary=false

ftp://publicftpserver.com/download

More information

This component is an extension of the File component.

You can find additional samples and details on the File component page.