# Virtualise a managed file gateway

## What a managed file gateway does

A managed file gateway passes files between a company's systems and its partners. Each party uploads files to a mailbox on the gateway and downloads files from it, or has files delivered to a server of its own, over SFTP or IBM® Connect:Direct. To test a system that exchanges files with a gateway, Traffic Parrot can stand in for the gateway, so the test needs neither the gateway nor the partners behind it.

This page works through an example of each flow. The [Files guide](https://trafficparrot.com/documentation/5.67.x/filemessage.html) is the reference for everything the examples use.

| The system under test | Traffic Parrot | See |
| --- | --- | --- |
| Uploads a file to its mailbox on the gateway, over SFTP | Is the SFTP server, and consumes the file | [Mailbox upload and download](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#mailboxes) |
| Downloads a file from its mailbox, often the reply to an upload | Writes the reply into the mailbox | [Mailbox upload and download](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#mailboxes) |
| Receives a file that the gateway delivers to its own SFTP server | Logs in to that server and writes the file, when a trigger file says so | [A file pushed to the system under test](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#push) |
| Exchanges files with the gateway through its own Connect:Direct node | Reads and writes the directories of a test Connect:Direct node that you run | [A test node, with Traffic Parrot behind it](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#connect-direct-landing) |
| Works through a gateway that passes files on to a partner over Connect:Direct | Stands in for the partner, over SFTP | [A partner the gateway reaches over Connect:Direct](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#connect-direct-partner) |

The SFTP examples use Traffic Parrot's own SFTP server, which needs a licence that includes file messaging.

## Mailbox upload and download

In this example the system under test logs in to the gateway as `partner-a`, uploads a payment file to `inbox` and downloads an acknowledgement from `outbox`. Traffic Parrot is the SFTP server it logs in to.

### 1. Switch on the SFTP server

In [`trafficparrot.properties`](https://trafficparrot.com/documentation/5.67.x/user_guide.html#properties), set:

```
trafficparrot.file.sftp.server.enabled=true
```

Create `sftp-server-users.json` next to that file:

```json
[
  {
    "username": "partner-a",
    "password": "partner-a-password"
  },
  {
    "username": "sut-server",
    "password": "sut-server-password"
  }
]
```

The second user is for the [push example](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#push), where it plays the system under test's own SFTP server. [Restart Traffic Parrot](https://trafficparrot.com/documentation/5.67.x/user_guide.html#start-and-stop). The [log](https://trafficparrot.com/documentation/5.67.x/logging.html) then has a line that starts like this, and goes on to name the root directory, the host key file and the key's fingerprint:

```
Started the embedded SFTP server on 0.0.0.0:8022 for 2 user(s) under
```

[Traffic Parrot as the SFTP server](https://trafficparrot.com/documentation/5.67.x/filemessage.html#sftp-server) describes the port, logging in with a key in place of a password, and the host key.

### 2. Add the connections

Connections are listed in `root-directories.json` in the installation directory. With the two this page uses and no others, the file is:

```json
[
  {
    "connectionId": "gateway",
    "connectionName": "Gateway",
    "connectionData": {
      "driver": "LOCAL_FILE_SYSTEM",
      "rootDirectory": "sftp-server-root"
    }
  },
  {
    "connectionId": "sut-sftp",
    "connectionName": "SUT SFTP server",
    "connectionData": {
      "driver": "SFTP",
      "hostname": "localhost",
      "port": 8022,
      "username": "sut-server",
      "password": "sut-server-password",
      "remoteBasePath": "/"
    }
  }
]
```

`Gateway` is a [Local File System connection](https://trafficparrot.com/documentation/5.67.x/filemessage.html#local-file-system) on the SFTP server's root directory, `sftp-server-root` in the installation directory, so the one connection reaches every user's mailbox. `SUT SFTP server` is for the push example. Traffic Parrot reads the file each time a replay session starts, so a change needs no restart.

### 3. Add the mapping

Save this as `file-mappings/payment-acknowledgement.json` in the installation directory. Traffic Parrot creates `file-mappings` at its first start.

```json
{
  "id": "5d0e7a52-3c1b-4f6e-8a2d-9b4c1e7f3a01",
  "request": {
    "destination": { "name": "partner-a/inbox", "type": "QUEUE" },
    "fileNameMatcher": { "matches": "payment-.*\\.xml" },
    "bodyMatcher": { "contains": "<currency>GBP</currency>" }
  },
  "response": {
    "destination": { "name": "partner-a/outbox", "type": "QUEUE" },
    "fileName": "ack-{{request.fileName}}",
    "text": "<ack><status>ACCEPTED</status></ack>",
    "bodyType": "TEXT"
  }
}
```

The mapping answers a file in `partner-a/inbox` whose name matches `payment-.*\.xml` and whose content contains `<currency>GBP</currency>`. The reply goes to `partner-a/outbox` and is named after the request. Directories are relative to the connection's root, so each starts with the user's home directory, which has the user's name.

Traffic Parrot reads a mapping file as soon as it is saved, with no restart. Mappings can also be built in the web UI, on [Files > Add/Edit](https://trafficparrot.com/documentation/5.67.x/filemessage.html#add-edit-file-message-mappings), and the [file message mapping key reference](https://trafficparrot.com/documentation/5.67.x/mapping-explorer/reference/file-message.html) lists every key. The `{{request.fileName}}` in the reply's name needs [`trafficparrot.file.handlebars.enabled`](https://trafficparrot.com/documentation/5.67.x/properties.html#trafficparrot.file.handlebars.enabled) to be `true`, as it is unless you use the [performance profile](https://trafficparrot.com/documentation/5.67.x/properties.html#performance-considerations).

### 4. Start a replay session

Go to **Files > Replay**. On the **Manual** tab, choose `Gateway` under both **Consume requests from** and **and replay responses to**, and click **Turn ON**.

The session creates `partner-a/inbox` and `partner-a/outbox` under the root directory. Until a session has run once they do not exist and an upload to `inbox` fails, so start the session before the system under test connects. Replay is off again after Traffic Parrot restarts.

### 5. Upload and download

The system under test connects to port `8022` as `partner-a` with the password `partner-a-password`. It sees its home directory as `/`. It uploads `inbox/payment-1.xml`:

```
<payment><amount>100.00</amount><currency>GBP</currency></payment>
```

Within a fraction of a second, `outbox/ack-payment-1.xml` is there to download:

```
<ack><status>ACCEPTED</status></ack>
```

`payment-1.xml` is gone from `inbox`: Traffic Parrot deletes each file it answers. A file that no mapping matches, a payment in another currency here, stays in `inbox` and gets no reply. See [When a file is not answered](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#not-answered).

## A file pushed to the system under test

A gateway also delivers files by logging in to the receiver's SFTP server. Traffic Parrot does the same when the reply side of a replay session is an [SFTP connection](https://trafficparrot.com/documentation/5.67.x/filemessage.html#sftp-driver). The system under test sends nothing to answer here, so your test supplies the request: a trigger file, uploaded at the moment the delivery should happen.

### 1. Point a connection at the system under test

The `SUT SFTP server` connection [above](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#mailboxes-connections) holds the host, port, user and password of the system under test's SFTP server, and in `remoteBasePath` the directory on it that a mapping's directories are relative to. To try the example with no such server, leave the entry as it is: it points at Traffic Parrot's own SFTP server, where the user `sut-server` plays the part.

### 2. Turn replay off and add the mapping

Click **Turn OFF** on **Files > Replay**, then save this as `file-mappings/statement-push.json`:

```json
{
  "id": "5d0e7a52-3c1b-4f6e-8a2d-9b4c1e7f3a02",
  "request": {
    "destination": { "name": "partner-a/triggers", "type": "QUEUE" },
    "fileNameMatcher": { "equalTo": "push-statement.trigger" },
    "bodyMatcher": { "anything": "anything" }
  },
  "response": {
    "destination": { "name": "incoming", "type": "QUEUE" },
    "fileName": "statement.csv",
    "text": "account,balance\n12345678,100.00\n",
    "bodyType": "TEXT"
  }
}
```

A file named `push-statement.trigger` in `partner-a/triggers`, whatever its content, is answered with `statement.csv` in the directory `incoming`.

Add this file only now. A Manual session serves every mapping in `file-mappings`: with the file in place earlier, the session of the previous section would have consumed the trigger too, and written the statement under the `Gateway` root, where no user sees it. Replay is turned off first because a session watches the request directories of the mappings that were there when it started, and no others.

### 3. Start a Script session

On **Files > Replay**, choose the **Script** tab, paste this and click **Turn ON**:

```
RequestRootDirectory:'Gateway'
ResponseRootDirectory:'Gateway'
RequestSubdirectories:'partner-a/inbox'

RequestRootDirectory:'Gateway'
ResponseRootDirectory:'SUT SFTP server'
RequestSubdirectories:'partner-a/triggers'
```

Each block is one consume and reply pair, as [Replaying using a script](https://trafficparrot.com/documentation/5.67.x/filemessage.html#replay-script) describes. The first keeps answering payments in the mailbox. The second consumes `partner-a/triggers` on `Gateway` and writes its replies through `SUT SFTP server`. The names are the connections' `connectionName` values, written exactly, capitals included. With any other name the start is refused with `Unable to find connection with name` and the name. To start the script without the page, from a CI job say, see [the API call that starts a script](https://trafficparrot.com/documentation/5.67.x/filemessage.html#replay-script-api).

### 4. Upload the trigger

As `partner-a`, upload `triggers/push-statement.trigger` with any content that is not empty. Traffic Parrot consumes it, logs in to the system under test's server and writes `incoming/statement.csv` there, creating `incoming` if it is missing:

```
account,balance
12345678,100.00
```

In the try-out, log in as `sut-server` to find it. The first push of a session takes about a second. Three things to know:

- Traffic Parrot logs in to the SFTP server only when it has a file to deliver. Starting the session neither connects nor checks the connection. If the server cannot be reached at the first push, the trigger is consumed, nothing is delivered, and the log has an ERROR that names the trigger file and says `SFTP operation failed for` with the host and port. Correct the connection, start the session again and upload the trigger again.
- An empty trigger file is answered only after about 30 seconds, with a warning in the log: Traffic Parrot waits that long in case whoever is writing the file has not finished. So give the trigger some content.
- After Traffic Parrot restarts, replay is off and the script box is empty. Paste the script and turn replay on again.

## A reply decided in Java

A mapping's matchers and a [Handlebars template](https://trafficparrot.com/documentation/5.67.x/dynamic.html) are enough for most replies. When the reply depends on the request in a way they do not express, a Java class can decide it: a file message response transformer. This one rejects a payment of zero and accepts any other:

```
package com.example.gateway;

import com.github.tomakehurst.wiremock.extension.Parameters;
import com.trafficparrot.sdk.file.FileMessage;
import com.trafficparrot.sdk.file.FileMessageResponse;
import com.trafficparrot.sdk.file.FileMessageResponseTransformer;
import com.trafficparrot.sdk.messaging.Destination;

public class AcknowledgePayment extends FileMessageResponseTransformer {
    @Override
    protected FileMessageResponse doTransform(Destination requestDestination, FileMessage requestMessage, FileMessageResponse response, Parameters parameters) {
        String status = requestMessage.text.contains("<amount>0.00</amount>") ? "REJECTED" : "ACCEPTED";
        return new FileMessageResponse(response.destination, response.fileName, "<ack><status>" + status + "</status></ack>");
    }
}
```

### 1. Build the jar

Save the class as `AcknowledgePayment.java` in the installation directory and run these two commands there. They need a JDK, version 17 or later: a Java runtime alone has no compiler.

```
javac --release 17 -proc:none -cp "lib/trafficparrot/internal/*:lib/trafficparrot/dependencies/*" -d build AcknowledgePayment.java
jar cf acknowledge-payment.jar -C build .
```

The classpath is the two directories that hold Traffic Parrot's SDK and the libraries it uses. On Windows, write `;` for the `:` between them. `--release 17` compiles for Java 17, so the class runs on that version and on later ones, and `-proc:none` stops the compiler running the annotation processors it finds in those jars. For more than one class, the [SDK workspace project](https://trafficparrot.com/documentation/5.67.x/dynamic.html#custom-extensions-sdk-javadoc) builds and tests an extension jar with Maven, and the [SDK Javadoc](https://trafficparrot.com/documentation/5.67.x/sdk-javadoc/index.html) describes `FileMessageResponseTransformer`.

### 2. Install it

Copy `acknowledge-payment.jar` to `lib/external` in the installation directory, where [jars are loaded at start](https://trafficparrot.com/documentation/5.67.x/dynamic.html#custom-extensions-without-rezipping). In `trafficparrot.properties`, add the class to the file message response transformers, so that the mapping editor lists it under **Response transformer**:

```
trafficparrot.file.responsetransformers=com.example.gateway.AcknowledgePayment
```

Restart Traffic Parrot. Write the class name exactly: if Traffic Parrot cannot load a class named in that property, **Files > Add/Edit** and **Files > Replay** show an error page, and the log names the class with `was not found on the classpath`.

### 3. Name it in the mapping

Add the class to the response in `file-mappings/payment-acknowledgement.json`:

```json
  "response": {
    "destination": { "name": "partner-a/outbox", "type": "QUEUE" },
    "fileName": "ack-{{request.fileName}}",
    "text": "<ack><status>ACCEPTED</status></ack>",
    "bodyType": "TEXT",
    "fileMessageResponseTransformerClassName": "com.example.gateway.AcknowledgePayment"
  }
```

Do this once the jar is loaded. A mapping that names a class Traffic Parrot has not loaded answers nothing: the request file stays where it is, and the log has an ERROR that names the file and the class.

### 4. Try it

Start the replay session again, since the restart turned it off. A payment of `<amount>100.00</amount>` is answered as before. One of `<amount>0.00</amount>`, uploaded as `inbox/payment-5.xml`, gets `outbox/ack-payment-5.xml`:

```
<ack><status>REJECTED</status></ack>
```

### How a transformer runs

- It runs once a request file has matched the mapping, [before the response is rendered](https://trafficparrot.com/documentation/5.67.x/dynamic.html#custom-extensions-when-they-run). It receives the mapping's response as written and returns the one to write, and Traffic Parrot then evaluates the Handlebars expressions in the file name and text it returned. So write the reply's text from strings of your own, as the example does. Content copied into it from the request would be evaluated as a template too.
- If the class throws an exception, a reply is still written: a text file with the mapping's file name whose content is the error message. The exception is in the log.
- For a [large file](https://trafficparrot.com/documentation/5.67.x/filemessage.html#large-files), the request's `text` is `null`. That section also shows a transformer that answers with a file, which Traffic Parrot copies without reading it into memory.

## Connect:Direct

Traffic Parrot does not speak the Connect:Direct protocol. Where the system under test sends and receives through its own Connect:Direct node, a real node has to answer it, and Traffic Parrot takes the gateway's place behind that node. Traffic Parrot's side is file replay, as on the rest of this page. The steps on a Connect:Direct node are marked: they need a licensed node, so we have not run them. Take their detail from IBM's documentation.

### A test node, with Traffic Parrot behind it

This is for a system under test that exchanges files with the gateway through its own Connect:Direct node. In the test environment that node talks to a test Connect:Direct node of yours, in place of the gateway's. The test node writes each file it receives into a directory, Traffic Parrot answers the file with a file in a second directory, and the test node sends that one back.

1. **Where Traffic Parrot runs.** Run it on the test node's host, or have the node write to a disk that is local to Traffic Parrot. On Linux, a Local File System connection does not notice a file that another host writes onto a network mount while a session is running.

2. **The system under test's node** (not run by us). Point its network map entry for the gateway at the test node.

3. **The test node, receiving** (not run by us). Have the Process that receives a file write it into `inbound` under a landing directory, with a name ending `.part`, and rename it once the copy is complete. Traffic Parrot leaves alone a name that matches [`trafficparrot.file.remote.temporaryFileNames`](https://trafficparrot.com/documentation/5.67.x/properties.html#trafficparrot.file.remote.temporaryFileNames), by default `*.tmp`, `*.part` and `*.filepart`, and picks the file up under its final name. So it never reads a file that is half written.

4. **Connections.** Add two [Local File System connections](https://trafficparrot.com/documentation/5.67.x/filemessage.html#local-file-system): `C:D landing`, whose root is the landing directory, and `C:D outbound`, whose root is the directory the test node sends from.

5. **Mapping.** Any file in `inbound` whose content has the header line is answered in `outbound` with a file named after it, so each file gets a reply of its own:

   ```json
   {
     "id": "6c2d9a4e-1f3b-4e57-9b0a-2d7e5c8f1a01",
     "request": {
       "destination": { "name": "inbound", "type": "QUEUE" },
       "fileNameMatcher": { "anything": "anything" },
       "bodyMatcher": { "contains": "account,amount,currency" }
     },
     "response": {
       "destination": { "name": "outbound", "type": "QUEUE" },
       "fileName": "{{request.fileName}}.ack",
       "text": "status\nACCEPTED\n",
       "bodyType": "TEXT"
     }
   }
   ```

6. **Replay.** On **Files > Replay**, on the **Manual** tab, consume requests from `C:D landing` and replay responses to `C:D outbound`.

7. **The test node, sending** (not run by us). Have Connect:Direct File Agent watch `outbound` under the outbound directory and submit a Process that copies each new file to the system under test's node, then deletes or moves it: Traffic Parrot does not remove its replies. Make the rule ignore `*.tmp` and `*.tmp.*`, the two names a reply can have while it is being written. When the outbound directory is on a different file system from Traffic Parrot's temporary directory, as a mounted volume is, Traffic Parrot first writes a reply there as `<name>.tmp` and then renames it. A reply sent from a file is copied there as `<name>.tmp.<random id>` and then renamed, on any file system: that is a reply whose [body file is over the in-memory limit](https://trafficparrot.com/documentation/5.67.x/filemessage.html#large-files), or one a response transformer answered with a file. Every other name appears complete.

One thing this does not reproduce: the return code of a Connect:Direct Process is the real node's, so Traffic Parrot cannot make a copy fail on purpose. To test the gateway being unreachable, stop the test node.

### Sending only, without File Agent

Where File Agent is not available, a [response transformer](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#transformer) can submit the copy to the system under test's node itself, through IBM's Connect:Direct Java API, with IBM's jar beside the transformer's in `lib/external`. We have not built or run this: IBM's jar comes with a Connect:Direct entitlement. Two things follow from how a transformer runs:

- It is called while the request is being answered. Submit the Process without waiting for it to complete, or replay waits with it, and read the outcome from the node's statistics.
- Traffic Parrot still writes the response that the transformer returns. Give the mapping a response directory that you keep for audit.

### A partner the gateway reaches over Connect:Direct

This is for a test that includes a gateway of your own, which passes files on to a downstream partner over Connect:Direct while the system under test is not on that leg. It needs no Connect:Direct at all: in the test gateway, set the virtualised partner up as an SFTP partner. The gateway then logs in to Traffic Parrot's SFTP server and delivers there, as the system under test does in [Mailbox upload and download](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#mailboxes). The gateway's own Connect:Direct configuration goes untested, which suits a test of your application and not a test of the gateway.

## When a file is not answered

What you see, then why and what to do:

- **An upload fails because `inbox` does not exist.** No replay session has run yet. Start one: it creates the directories its mappings name.
- **The file stays in its directory, and the log has `No match for` with the file's name.** No mapping matched. The log entry above that line shows the closest mapping. Correct the mapping or the file and upload the file again; the same name will do. With [`trafficparrot.messaging.diagnostics.enabled=true`](https://trafficparrot.com/documentation/5.67.x/properties.html#trafficparrot.messaging.diagnostics.enabled), read when Traffic Parrot starts, the [Requests page](https://trafficparrot.com/documentation/5.67.x/filemessage.html#requests-page) lists each unmatched file beside the mappings that came closest.
- **The file stays in its directory, and the log says nothing about it.** The session is not reading that directory. A session reads the request directories of the mappings that were there when it started, and a Script session reads only the directories its blocks list in `RequestSubdirectories`. Add the directory to the script if it is missing, then start the session again and upload the file again.
- **The file stays in its directory, and after about 30 seconds the log has a WARN that says Traffic Parrot `cannot check that it is not being written`.** Most often Traffic Parrot cannot open the file; the WARN gives the reason. Where the reason is the file's permissions, correct them and the file is answered within about a second. On Windows, or where `flock` is not installed, Traffic Parrot needs write permission on the file as well.
- **The file stays in its directory, and the log has an ERROR ending `was not found on the classpath`.** The mapping names a transformer class that Traffic Parrot has not loaded. Put the jar in `lib/external`, restart and upload the file again.
- **The reply comes about 30 seconds late.** The request file was empty. Traffic Parrot waits that long before it takes an empty file as complete.
- **A trigger is consumed and nothing is delivered.** The SFTP connection failed, and the log has an ERROR that names the trigger file. See [Upload the trigger](https://trafficparrot.com/documentation/5.67.x/file-gateway.html#push-result).
- **A login is refused.** The log has a WARN that starts `Embedded SFTP server refused login for` and gives the user, the client's address and the reason, such as `wrong password` or `no such user`.
- **An uploaded file never appears in its directory.** The client did not close the upload, or the write failed. The server [discards such an upload](https://trafficparrot.com/documentation/5.67.x/filemessage.html#sftp-server) and logs its name, its directory and the reason.
- **Nothing is answered after a restart.** Replay is off when Traffic Parrot starts. Start the session again.

## Limits

- A file larger than the in-memory limit is matched by its name alone and handled without being read: see [Large files](https://trafficparrot.com/documentation/5.67.x/filemessage.html#large-files).
- A file that is not text is covered in [Binary files](https://trafficparrot.com/documentation/5.67.x/filemessage.html#binary-files).
- Traffic Parrot's SFTP server speaks SFTP only, with no shell and no SCP. [Traffic Parrot as the SFTP server](https://trafficparrot.com/documentation/5.67.x/filemessage.html#sftp-server) lists its limitations.
- The passwords in `sftp-server-users.json` and `root-directories.json` are plain text. A password in `root-directories.json` can instead [name an environment variable or a file](https://trafficparrot.com/documentation/5.67.x/mappings-in-git.html#passwords), and a user of the SFTP server can log in with a key.
- The log holds the content of the request files and replies that Traffic Parrot reads into memory, so treat it as you treat the files.

**Missing something?** See [When the docs do not say](https://trafficparrot.com/documentation/5.67.x/when-the-docs-do-not-say.html) for where else to look, or [tell us what this page lacks](https://trafficparrot.com/support.html?page=/documentation/file-gateway.html).
