If you haven’t already got groovy installed, ensure it is (instructions for Fedora below):

sudo dnf install -y groovy

Setup your working directory as follows:

$ tree .
.
├── log4j.properties
└── ReadFileFromFtpServer.groovy
0 directories, 2 files
view raw tree hosted with ❤ by GitHub

log4j.properties has logging levels turned down, just so the line output is the file content from the FTP server.

log4j.rootLogger=INFO, out
#
# change the following line to enable info/debug log of Camel
#
log4j.logger.org.apache.camel=OFF
log4j.appender.out=org.apache.log4j.ConsoleAppender
log4j.appender.out.layout=org.apache.log4j.PatternLayout
log4j.appender.out.layout.ConversionPattern=[%30.30t] %-30.30c{1} %-5p %m%n

ReadFileFromFtpServer.groovy is the main bulk of code which defines a camel route to connect to an ftp site with a username and password. Notice the @Grab annotations which pull in the required java libraries upon first attempting to run the script (these will download to ~/user/.groovy/grapes). It is also possible to trigger IntelliJ to download the dependencies for you: https://mrhaki.blogspot.com/2017/10/groovy-goodness-download-grab.html

import org.apache.camel.LoggingLevel
import org.apache.camel.builder.RouteBuilder
import org.apache.camel.impl.DefaultCamelContext
@Grab(group = 'org.apache.camel', module = 'camel-core', version = '2.21.0')
@Grab(group = 'org.apache.camel', module = 'camel-ftp', version = '2.21.0')
@Grab(group = 'org.slf4j', module = 'slf4j-log4j12', version = '1.7.26')
@Grab(group = 'log4j', module = 'log4j', version = '1.2.17')
def static pollFtp() {
String ftpLocation = 'localhost'
String ftpPort = '21'
String ftpUsername = 'someuser'
String ftpPassword = 'r3dh4t1!!!'
def camelCtx = new DefaultCamelContext()
camelCtx.addRoutes(new RouteBuilder() {
def void configure() {
from("ftp://${ftpLocation}:${ftpPort}?autoCreate=false&username=${ftpUsername}&password=${ftpPassword}&passiveMode=true" +
'&localWorkDirectory=/tmp' +
'&transferLoggingLevel=INFO&transferLoggingIntervalSeconds=1&transferLoggingVerbose=false&delay=5s&noop=true')
.log(LoggingLevel.INFO, 'Downloaded File Content: ${body}')
}
})
camelCtx.start()
// Stop Camel when the JVM is shut down
Runtime.runtime.addShutdownHook({ ->
camelCtx.stop()
})
synchronized(this){ this.wait() }
}
pollFtp()

Once you run the script with groovy ReadFileFromFtpServer.groovy you should see log output to console of any files on the ftp server. Note that the script will not consume the files due to the camel ftp option noop=true

$ groovy ReadFileFromFtpServer.groovy
[thread #1 - ftp://localhost:21] route1 INFO Downloaded File Content: hello world
view raw output hosted with ❤ by GitHub

References


codergists