Camel Components

SMB

Since Camel 4.3

Both producer and consumer are supported

The Server Message Block (SMB) component provides a way to connect natively to SMB file shares, such as those provided by Microsoft Windows or Samba.

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

URI format

smb:hostname[:port]/shareName[/path][?options]

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 SMB 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 SMB endpoint is configured using URI syntax:

smb:hostname:port/shareName/path

With the following path and query parameters:

Path Parameters

Name Description Default Type

hostname (common)

Required The hostname or IP address of the SMB server.

String

port (common)

The TCP port of the SMB server.

445

int

shareName (common)

Required The name of the share on the SMB server.

String

path (common)

The directory within the share: the consumer polls it, and the producer writes the files in it. When not set, the root directory of the share is used.

String

Query Parameters

Name Description Default Type

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 SMB server (close the share, the session and the connection) after use: the producer after each file it writes, the consumer after each poll, once the last exchange of the poll is done. The next use connects and logs in again. It does not stop the consumer: stop the route for that.

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

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

searchPattern (consumer)

A wildcard pattern, such as *.txt, that the SMB server matches the names in each directory listing against: * matches any number of characters and ? a single character. The server does the matching (the exact rules depend on the server), so the files that do not match are not sent to Camel, unlike with the include option, a regular expression that Camel applies. With recursive, the pattern also applies to the subdirectories: only the subdirectories whose names match are polled. When not set, all the files are listed.

String

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)

Whether the consumer streams the file content into the route: the content is an InputStream that reads the file from the share as the route reads it, and the file stays open on the share until the exchange completes. When false, the whole file is read into memory, as a byte array, before the exchange is routed. Not used with localWorkDirectory, where the file is first written to a local file.

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 SMB consumer should download the file. If this option is set to false, then the message body will be null, but the consumer will still trigger a Camel Exchange that has details about the file such as file name, file size, etc. It’s just that the file will not be downloaded.

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

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

startingDirectoryMustExist (consumer (advanced))

Whether the consumer checks, when it starts, that the starting directory exists on the share, and fails to start when it does not. Only used when autoCreate is false: autoCreate, enabled by default, creates the directory instead.

false

boolean

throwExceptionOnConnectFailed (consumer (advanced))

Whether the consumer throws the exception when, before a poll, it cannot connect and log in to the SMB server, or cannot create the starting directory. By default, the poll is skipped and a WARN is logged. When enabled, the exception goes to the rollback method of the PollingConsumerPollStrategy, and then to the exception handler of the consumer (the routing error handler with bridgeErrorHandler).

false

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

disconnectOnBatchComplete (producer (advanced))

Whether the producer disconnects from the SMB server after writing the file of the last exchange of a batch, the exchange with the CamelBatchComplete property set to true, such as the last file of a poll of a file consumer.

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

renameUsingCopy (producer (advanced))

Whether to rename files by copying them on the server (SMB server-side copy) and deleting the original, instead of the SMB rename. It applies to every rename: the move, preMove and moveFailed options and the rename read lock of the consumer, and the tempFileName option and fileExist=Move of the producer. It takes precedence over copyAndDeleteOnRenameFail.

false

boolean

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 opening the TCP connection to the SMB server. 0 waits without a limit.

5000

int

copyAndDeleteOnRenameFail (advanced)

Whether to fall back to copying the file on the server (SMB server-side copy) and deleting the original when the SMB rename of a file fails. The fallback is immediate and logged at WARN.

false

boolean

readTimeout (advanced)

The timeout, in milliseconds, for the SMB server to answer a read of file content. 0 waits without a limit.

60000

int

smbConfig (advanced)

Autowired The smbj SmbConfig to create the SMBClient with, for the settings that have no option here, such as the SMB dialects, message signing, DFS, the authenticators and the buffer sizes. A single SmbConfig bean in the registry is used automatically. It is used as is, so it cannot be combined with the encryptData, connectTimeout, readTimeout, writeTimeout and transactTimeout options (the consumer or producer fails to be created): set them on the SmbConfig instead. When not set, Camel builds one with the smbj defaults: the dialects SMB 2.0.2 to 3.1.1, message signing enabled but required only when the server requires it, and no DFS.

SmbConfig

transactTimeout (advanced)

The timeout, in milliseconds, for the SMB server to answer the other requests, such as the login, connecting to the share, listing a directory, opening, closing, renaming, copying and deleting a file, and logging off. 0 waits without a limit.

60000

int

writeTimeout (advanced)

The timeout, in milliseconds, for the SMB server to answer a write of file content. 0 waits without a limit.

60000

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)

Used by the consumer to only pick up a file that is not being written, by first getting an exclusive read lock on it. The supported read locks are: - none - No read lock is used. - changed - Lists the file every readLockCheckInterval, and gets the lock once its length and change time are the same as at the previous check (or, with readLockMinAge, once the file is older than that) and it has at least readLockMinLength bytes. It waits up to readLockTimeout, so it cannot consume files as fast as the others. - rename - Renames the file, and back, to test whether it can get the lock. When the rename fails, the file is skipped with a WARN and tried again on the next poll. 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

domain (security)

The domain of the user, for the NTLM login.

String

encryptData (security)

Whether to use SMB 3 encryption: the client offers it to the server, and when the server supports it, the messages after the login, including the file content, are encrypted (AES-128-GCM or AES-128-CCM). When the server negotiates SMB 2 or does not support encryption, or the login is a guest login, the messages are sent unencrypted, without an error. A share that requires encryption (for Samba, smb encrypt = required) refuses the connection with STATUS_ACCESS_DENIED unless this option is enabled. By default, the messages are not encrypted.

false

boolean

password (security)

The password of the user. When not set, the login uses an empty password.

String

username (security)

The user name to log in to the SMB server with (NTLM authentication). Required: for a guest login, set it to Guest and set no password.

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

The last modified time of the file (the SMB last write time), in milliseconds since the epoch.

long

CamelFileNameOnly (consumer)

Constant: FILE_NAME_ONLY

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

String

CamelFileName (common)

Constant: FILE_NAME

(producer) The name of the file to write, relative to the endpoint directory: a String, or an Expression object that is evaluated (an expression in a String is not evaluated). When the fileName option is set, that is used instead, unless the header is an Expression. When neither is set, Camel generates a name from the message ID. (consumer) The name of the consumed file, as a path relative to the starting directory.

String

CamelFileNameConsumed (consumer)

Constant: FILE_NAME_CONSUMED

The name of the consumed file, as a path relative to the starting directory (the value of CamelFileName when the file was consumed).

String

CamelFileAbsolute (consumer)

Constant: FILE_ABSOLUTE

Whether the path of the consumed file is absolute (starts with a slash). Normally false, as the consumer lists the files with paths relative to the root of the share.

Boolean

CamelFileAbsolutePath (consumer)

Constant: FILE_ABSOLUTE_PATH

The path of the consumed file from the root of the share, including the starting directory.

String

CamelFilePath (consumer)

Constant: FILE_PATH

The path of the consumed file: the starting directory followed by the relative path of the file.

String

CamelFileRelativePath (consumer)

Constant: FILE_RELATIVE_PATH

The path of the consumed file relative to the starting directory.

String

CamelFileParent (common)

Constant: FILE_PARENT

The path of the directory that holds the file, from the root of the share.

String

CamelFileNameProduced (producer)

Constant: FILE_NAME_PRODUCED

The path of the written file from the root of the share (the endpoint directory and the file name). Set by the producer after it writes the file.

String

CamelOverruleFileName (producer)

Constant: OVERRULE_FILE_NAME

The name of the file to write, a String or an Expression, that overrules the CamelFileName header: the producer puts it in CamelFileName, and removes this header after writing the file, so it applies only once. When the fileName option is set, that is used instead, unless the value is an Expression.

Object

CamelFileHost (consumer)

Constant: FILE_HOST

The hostname of the SMB server.

String

CamelSmbFileInputStream (consumer)

Constant: SMB_FILE_INPUT_STREAM

The InputStream of the remote file, with streamDownload. Camel closes it, and the file on the share, when the exchange completes.

InputStream

CamelFileLocalWorkPath (common)

Constant: FILE_LOCAL_WORK_PATH

The path of the local work file that the consumer downloaded the remote file into, with the localWorkDirectory option. Camel deletes this file when the exchange completes.

String

CamelSmbFileExists (producer)

Constant: SMB_FILE_EXISTS

Deprecated Deprecated: use the fileExist option. What the producer does when the file already exists, as a GenericFileExist value (Override, Append, Fail, Ignore or Move). It takes precedence over the fileExist option.

Enum values:

  • Override

  • Append

  • Fail

  • Ignore

  • Move

  • TryRename

GenericFileExist

CamelSmbUncPath (consumer)

Constant: SMB_UNC_PATH

The UNC path of the retrieved file: the server, the share and the path of the file. Set when the consumer downloads the file.

String

Message Body

The message body at each side of the SMB 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: an SmbFile, which converts to text, bytes or a stream; a stream with streamDownload; with preMove its content, a byte array (a stream with streamDownload).

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

Producer

The SMB producer writes the message body to a file in the share. The CamelFileName header (or the fileName option) sets the name of the file; without it, the producer generates a name from the message ID. The following route writes a file to the share, and sets its name in the CamelFileName header:

- route:
    from:
      uri: timer:report
      parameters:
        repeatCount: 1
      steps:
        - setBody:
            expression:
              constant:
                expression: Hello from Camel
        - setHeader:
            name: CamelFileName
            expression:
              simple:
                expression: "report-${date:now:yyyyMMdd}.txt"
        - to:
            uri: smb:myserver/data
            parameters:
              username: "{{smb.username}}"
              password: "{{smb.password}}"

Examples

Polling files

For instance, polling all the files from an SMB file share and reading their contents would look like this:

Java-only: uses fromF with string formatting and method reference Processor
private void process(Exchange exchange) throws IOException {
    final byte[] data = exchange.getMessage().getBody(byte[].class);
    LOG.debug("Read exchange as bytes with contents: {}", new String(data));
}

public void configure() {
    fromF("smb:%s/%s?username=%s&password=%s", service.address(), service.shareName(), service.userName(), service.password())
        .process(this::process)
        .to("mock:result");
}
you may also get the file contents as an InputStream using exchange.getMessage().getBody(InputStream.class).

In YAML, a route that polls the share and logs the content of each file looks like this:

- route:
    from:
      uri: smb:myserver/data
      parameters:
        username: "{{smb.username}}"
        password: "{{smb.password}}"
        move: done
      steps:
        - log:
            message: "Read ${header.CamelFileName}: ${body}"

The consumer leaves the files on the share by default, and reads them again on the next poll. Set move (as above), delete or noop, so that each file is read once.

Polling large directories

With maxMessagesPerPoll, the consumer stops reading the directory once it has the files of the poll, rather than listing the whole directory first. It reads the whole directory when preSort or doneFileName is used, or with eagerMaxMessagesPerPoll=false.

It also reads the whole directory when the server supports SMB 3 directory leases, such as Samba and Windows, and no searchPattern is set: the SMB client then serves a repeat listing from its cache while it holds the lease, which costs less than reading the start of the directory again.

Read locks

The smb consumer supports the read locks none, rename and changed. Any other readLock value, such as the markerFile, fileLock, idempotent, idempotent-changed and idempotent-rename read locks of the File component, and also false and off, fails when the consumer is created, with IllegalArgumentException: ReadLock invalid.

Polling files (advanced)

You can also get access to the file using the underlying File implementation provided by Camel. In that case, polling all the files from an SMB file share and reading their contents would look like this:

Java-only: uses SmbFile class, type casts, fromF with string formatting, and method reference Processor
private void process(Exchange exchange) throws IOException {
    final org.apache.camel.component.smb.SmbFile file = exchange.getMessage().getBody(org.apache.camel.component.smb.SmbFile.class);
    LOG.debug("Read exchange: {}, with contents: {}", file.getFile(), new String((byte[]) file.getBody()));
}

public void configure() {
    fromF("smb:%s/%s?username=%s&password=%s", service.address(), service.shareName(), service.userName(), service.password())
        .process(this::process)
        .to("mock:result");
}

Beware that the File object provided is not a java.io.File instance, but, instead a org.apache.camel.component.smb.SmbFile instance that extends Camel’s GenericFile. Relying on the underlying implementation may make your code more susceptible to problems between version upgrades of the library used to implement this component.

To maintain backward compatibility, a new Camel Header CamelSmbUncPath has been introduced that provides the full absolute path when a File is consumed from the SMB server.

Login

The component logs in with the username, password and domain options. A username without a password logs in with an empty password, so username=Guest without a password is a guest login, when the server allows guest access (for Samba: map to guest and guest ok = yes on the share).

The username is required: an anonymous login (no username) is not supported, and the connection fails with a message that no username is set.

Encryption and timeouts

A share that requires encryption (for Samba smb encrypt = required) refuses the connection with STATUS_ACCESS_DENIED unless encryptData=true is set. With encryptData=true the messages to and from the server, including the file content, are encrypted with SMB 3 encryption, also on a share that does not require it. When the server negotiates SMB 2 or does not support encryption, or the login is a guest login, the messages are sent unencrypted, without an error.

The timeouts of the SMB client are the connectTimeout (5 seconds by default), readTimeout and writeTimeout (of the file content, 60 seconds by default) and transactTimeout options (of the other requests, such as listing a directory, opening, renaming or deleting a file, 60 seconds by default):

- route:
    from:
      uri: smb:myserver/myshare/inbox
      parameters:
        username: "{{smb.username}}"
        password: "{{smb.password}}"
        encryptData: true
        transactTimeout: 10s
      steps:
        - to:
            uri: log:files

For the other settings of the SMB client, configure a com.hierynomus.smbj.SmbConfig bean in the smbConfig option (a single SmbConfig bean in the registry is used automatically). The SmbConfig is then used as it is, so it cannot be combined with the encryptData, connectTimeout, readTimeout, writeTimeout and transactTimeout options: the endpoint fails to start when one of them is set as well. Set them on the SmbConfig instead (withEncryptData, withSocketFactory(new ProxySocketFactory(connectTimeout)), withReadTimeout, withWriteTimeout and withTransactTimeout).

Permissions

The Camel SMB component requires the authenticated user to have appropriate permissions on the SMB share. The exact permissions depend on the operations being performed:

  • Reading files: requires Read Data permission on the file.

  • Writing files: requires Write Data permission on the file and Create Files on the parent directory.

  • Deleting files (e.g., when using delete=true on a consumer): requires Delete permission on the file.

  • Creating the starting directory of a consumer that does not exist (autoCreate, enabled by default): requires Create Folders on the parent directory. When the directory cannot be created, the route still starts: the consumer logs a WARN and tries again on each poll.

STATUS_ACCESS_DENIED (0xc0000022) when deleting files

If you receive a STATUS_ACCESS_DENIED error when the consumer attempts to delete a file after processing, the most common causes are:

  1. The authenticated user lacks the DELETE permission on the file or the parent directory. Ensure the SMB user has been granted the Delete and Delete Child permissions.

  2. The server’s volume uses UNIX security style instead of NTFS. Some storage systems (such as NetApp ONTAP, TrueNAS, or other unified NAS platforms) support multiple volume security styles. When a volume uses UNIX security style, the server ignores NTFS ACLs and evaluates only UNIX file ownership and mode bits (chmod/chown). In this case, even if the Windows "Effective Access" UI shows full permissions, the delete operation can still be denied because the NTFS ACLs shown are not the actual access control mechanism.

To resolve this, either:

  • Change the volume security style to NTFS so that NTFS ACLs are evaluated, or

  • Ensure the UNIX file ownership and mode bits grant the SMB user delete access on the files and their parent directory.