ballerina/ftp

Overview

This module provides an FTP/SFTP client and an FTP/SFTP server listener implementation to facilitate an FTP/SFTP connection connected to a remote location.

FTP Client

The ftp:Client connects to an FTP server and performs various operations on the files. Currently, it supports the generic FTP operations; get, delete, put, append, mkdir, rmdir, isDirectory, rename, size, and list.

An FTP client is defined using the protocol and host parameters and optionally, the port and auth. Authentication configuration can be configured using the auth parameter for Basic Auth and private key.

An authentication-related configuration can be given to the FTP client with the auth configuration.

Creating a Client

The following code creates an FTP client and performs the I/O operations, which connect to the FTP server with Basic Auth.

1// Define the FTP client configuration.
2ftp:ClientConfiguration ftpConfig = {
3 protocol: ftp:FTP,
4 host: "<The FTP host>",
5 port: <The FTP port>,
6 auth: {
7 credentials: {
8 username: "<The FTP username>",
9 password: "<The FTP passowrd>"
10 }
11 }
12};
13
14// Create the FTP client.
15ftp:Client|ftp:Error ftpClient = new(ftpConfig);
Creating a Directory

The following code creates a directory in the remote FTP server.

1ftp:Error? mkdirResponse = ftpClient->mkdir("<The directory path>");
Uploading File to a Remote Server

The following code uploads a file to a remote FTP server.

1stream<io:Block, io:Error?> fileByteStream
2 = check io:fileReadBlocksAsStream(putFilePath, <Block size>);
3ftp:Error? putResponse = ftpClient->put("<The resource path>", fileByteStream);
Compressing and Uploading a File to a Remote Server

The following code compresses and uploads a file to a remote FTP server.

1// Set the optional boolean flag as 'true' to compress before uploading
2stream<io:Block, io:Error?> fileByteStream
3 = check io:fileReadBlocksAsStream(putFilePath, <Block size>);
4ftp:Error? compressedPutResponse = ftpClient->put("<Resource path>",
5 fileByteStream, compressionType=ZIP);
Getting the Size of a Remote File

The following code gets the size of a file in a remote FTP server.

1int|ftp:Error sizeResponse = ftpClient->size("<The resource path>");
Reading the Content of a Remote File

The following code reads the content of a file in a remote FTP server.

1stream<byte[], io:Error?>|Error str = clientEP -> get("<The file path>");
2if (str is stream<byte[], io:Error?>) {
3 record {|byte[] value;|}|io:Error? arr1 = str.next();
4 if (arr1 is record {|byte[] value;|}) {
5 string fileContent = check strings:fromBytes(arr1.value);
6 // `fileContent` is the `string` value of first byte array
7 record {|byte[] value;|}|io:Error? arr2 = str.next();
8 // Similarly following content chunks can be iteratively read with `next` method.
9 // Final chunk will contain the terminal value which is `()`.
10 }
11 io:Error? closeResult = str.close();
12}
Renaming or Moving a Remote file to Another Remote Location in the Same FTP Server

The following code renames or moves a file to another location in the same remote FTP server.

1ftp:Error? renameResponse = ftpClient->rename("<The source file path>",
2 "<The destination file path>");
Deleting a Remote File

The following code deletes a remote file in a remote FTP server.

1ftp:Error? deleteResponse = ftpClient->delete("<The resource path>");
Removing a Directory From a Remote Server

The following code removes a directory in a remote FTP server.

1ftp:Error? rmdirResponse = ftpClient->rmdir("<The directory path>");

FTP Listener

The ftp:Listener is used to listen to a remote FTP location and trigger a WatchEvent type of event when new files are added to or deleted from the directory. The fileResource function is invoked when a new file is added and/or deleted.

An FTP listener is defined using the mandatory protocol, host, and path parameters. The authentication configuration can be done using the auth parameter and the polling interval can be configured using the pollingInterval parameter. The default polling interval is 60 seconds.

The fileNamePattern parameter can be used to define the type of files the FTP listener will listen to. For instance, if the listener gets invoked for text files, the value (.*).txt can be given for the config.

An authentication-related configuration can be given to the FTP listener with the auth configuration.

Creating a Listener

The FTP Listener can be used to listen to a remote directory. It will keep listening to the specified directory and notify on file addition and deletion periodically.

1listener ftp:Listener remoteServer = check new({
2 protocol: ftp:FTP,
3 host: "<The FTP host>",
4 auth: {
5 credentials: {
6 username: "<The FTP username>",
7 password: "<The FTP passowrd>"
8 }
9 },
10 port: <The FTP port>,
11 path: "<The remote FTP direcotry location>",
12 pollingInterval: <Polling interval>,
13 fileNamePattern: "<File name pattern>"
14});
15
16service on remoteServer {
17 remote function onFileChange(ftp:WatchEvent fileEvent) {
18
19 foreach ftp:FileInfo addedFile in fileEvent.addedFiles {
20 log:print("Added file path: " + addedFile.path);
21 }
22 foreach string deletedFile in fileEvent.deletedFiles {
23 log:print("Deleted file path: " + deletedFile);
24 }
25 }
26}

Secure access with SFTP

SFTP is a secure protocol alternative to the FTP, which runs on top of the SSH protocol. There are several ways to authenticate an SFTP server. One is using the username and the password. Another way is using the client's private key. The Ballerina SFTP client and the listener support only those authentication standards. An authentication-related configuration can be given to the SFTP client/listener with the auth configuration. Password-based authentication is defined with the credentials configuration while the private key based authentication is defined with the privateKey configuration.

SFTP Client Configuration

1ftp:ClientConfiguration sftpConfig = {
2 protocol: ftp:SFTP,
3 host: "<The SFTP host>",
4 port: <The SFTP port>,
5 auth: {
6 credentials: {username: "<The SFTP username>", password: "<The SFTP password>"},
7 privateKey: {
8 path: "<The private key file path>",
9 password: "<The private key file password>"
10 }
11 }
12};

SFTP Listener Configuration

1listener ftp:Listener remoteServer = check new({
2 protocol: ftp:SFTP,
3 host: "<The SFTP host>",
4 port: <The SFTP port>,
5 path: "<The remote SFTP direcotry location>",
6 pollingInterval: <Polling interval>,
7 fileNamePattern: "<File name pattern>",
8 auth: {
9 credentials: {username: "<The SFTP username>", password: "<The SFTP password>"},
10 privateKey: {
11 path: "<The private key file path>",
12 password: "<The private key file password>"
13 }
14 }
15});

Listeners

[1]

Listener

Represents a service listener that monitors the FTP location.

Clients

[1]

Client

Represents an FTP client that intracts with an FTP server

Object Types

[1]

Service

Represents a FTP service.

Records

[8]

AuthConfiguration

Configurations for facilitating secure communication with a remote FTP server.

ClientConfiguration

Configuration for FTP client.

Credentials

Username/password authentication related configurations.

FileInfo

Metadata for newly-added files.

InputContent

Configuration for the input given for put and append operations of the FTP module.

ListenerConfiguration

Configuration for FTP listener.

PrivateKey

Configuration to read a privte key.

WatchEvent

This represents the latest status change of the server from the last status change.

Enums

[2]

Compression

Compression type.

Protocol

Represents the set of protocols supported by the FTP listener and client.

Errors

[1]

Error

Defines the common error type for the module.