This is an automated email from the ASF dual-hosted git repository.
davsclaus pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/camel.git
The following commit(s) were added to refs/heads/main by this push:
new c9d3853712aa CAMEL-26657: camel-ftp, camel-sftp - no change of
directory and back, nor autoCreate check, for each file (#30536)
c9d3853712aa is described below
commit c9d3853712aa6debfe656964018577a57968c314
Author: Adriano Machado <[email protected]>
AuthorDate: Sun Nov 22 03:11:58 2026 -0500
CAMEL-26657: camel-ftp, camel-sftp - no change of directory and back, nor
autoCreate check, for each file (#30536)
With the default stepwise=true, an upload, a download or (ftp) a delete
stays
in the directory of its file, so the next file in that directory needs no
change of directory. Operations that use names relative to the starting
directory (rename, listing, existence check, site command, directory
changes,
FtpOperations.getClient()) change back first. SFTP changes back with a
single
cd to the absolute starting directory. FTP asks for the current directory
once
per connection instead of a PWD per file.
With the default autoCreate=true, a directory is checked or created once per
connection. An upload into a cached directory that was removed since creates
it again and is tried once more, unless the body is a stream or the upload
appends.
The ftp producer skips the NOOP before an upload when the server completed a
command less than a second before (RemoteFileOperations.isRecentlyUsed());
the
health check and the consumer still send it.
Per upload into a two-segment directory with defaults: 3 SFTP requests
instead
of 15, and no PWD/CWD/NOOP on FTP.
_Claude Code on behalf of Adriano Machado (@ammachado)_
_This was generated by an AI agent and may contain inaccuracies.
Please verify before relying on it._
Review fixes:
- CAMEL-26657: camel-ftp, camel-sftp - review fixes for the stepwise and
autoCreate changes
- CAMEL-26657: camel-ftp, camel-sftp - second round of review fixes
Co-Authored-By: Claude Opus 5.5 <[email protected]>
---
.../apache/camel/catalog/docs/ftp-component.adoc | 14 +-
.../camel/component/file/remote/FtpUtils.java | 18 +
.../file/remote/RemoteFileOperations.java | 12 +
.../component/file/remote/RemoteFileProducer.java | 5 +-
.../camel-ftp/src/main/docs/ftp-component.adoc | 14 +-
.../camel/component/file/remote/FtpOperations.java | 520 ++++++++++++++++-----
.../component/file/remote/SftpOperations.java | 316 +++++++++----
.../RemoteFileProducerPreWriteCheckTest.java | 34 ++
.../integration/FtpConsumerSendNoopFalseIT.java | 12 +-
.../remote/integration/FtpStepwiseCommandsIT.java | 374 +++++++++++++++
.../sftp/integration/SftpStepwiseRequestsIT.java | 257 ++++++++++
.../ROOT/pages/camel-4x-upgrade-guide-4_24.adoc | 33 ++
12 files changed, 1371 insertions(+), 238 deletions(-)
diff --git
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
index 085c526fbd12..4494ef2cab68 100644
---
a/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
+++
b/catalog/camel-catalog/src/generated/resources/org/apache/camel/catalog/docs/ftp-component.adoc
@@ -534,8 +534,6 @@ CDUP
200 CDUP successful. "/one/two" is current directory.
CWD /
250 CWD successful. "/" is current directory.
-PWD
-257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
@@ -547,8 +545,6 @@ RETR foo.txt
226 Transfer OK
CWD /
250 CWD successful. "/" is current directory.
-PWD
-257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
@@ -562,8 +558,6 @@ RETR a.txt
226 Transfer OK
CWD /
250 CWD successful. "/" is current directory.
-PWD
-257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
@@ -575,14 +569,16 @@ PORT 127,0,0,1,17,99
RETR b.txt
150 Opening data channel for file transfer.
226 Transfer OK
-CWD /
-250 CWD successful. "/" is current directory.
QUIT
221 Goodbye
disconnected.
----
As you can see when stepwise is enabled, it will traverse the directory
-structure using CD xxx.
+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.
Stepwise Disabled::
+
diff --git
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java
index 45f616b3d1ca..9048966fce18 100644
---
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java
+++
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/FtpUtils.java
@@ -17,11 +17,14 @@
package org.apache.camel.component.file.remote;
import java.io.File;
+import java.nio.file.Path;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.Iterator;
import org.apache.camel.Component;
+import org.apache.camel.StreamCache;
+import org.apache.camel.component.file.GenericFile;
import org.apache.camel.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -153,4 +156,19 @@ public final class FtpUtils {
return absoluteFileName;
}
+ /**
+ * Whether an upload can read the message body again after a failed
attempt: the body is not a stream or a reader
+ * that the failed attempt may have read, but data, a local file, or a
{@link StreamCache}, which the caller must
+ * {@link StreamCache#reset() reset} before the next attempt.
+ *
+ * @param body the message body
+ * @return <tt>true</tt> for no body, a byte array, a text, a local
file, or a stream cache
+ * @since 4.24
+ */
+ public static boolean isBodyReadableAgain(Object body) {
+ return body == null || body instanceof byte[] || body instanceof
CharSequence || body instanceof File
+ || body instanceof Path || body instanceof GenericFile<?> file
&& file.getFile() instanceof File
+ || body instanceof StreamCache;
+ }
+
}
diff --git
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
index 4bbc5b361950..0806261d4491 100644
---
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
+++
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileOperations.java
@@ -85,6 +85,18 @@ public interface RemoteFileOperations<T> extends
GenericFileOperations<T> {
*/
boolean sendNoop() throws GenericFileOperationFailedException;
+ /**
+ * Whether the server completed an operation on this connection so
recently that a noop before the next upload would
+ * not show anything new about the connection. The default returns
<tt>false</tt>, so the producer always sends the
+ * noop.
+ *
+ * @return <tt>true</tt> if the producer can skip the noop before the next
upload
+ * @since 4.24
+ */
+ default boolean isRecentlyUsed() {
+ return false;
+ }
+
/**
* Sends a site command to the remote server
*
diff --git
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducer.java
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducer.java
index f473428921ea..4a19f74d0a5b 100644
---
a/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducer.java
+++
b/components/camel-ftp-common/src/main/java/org/apache/camel/component/file/remote/RemoteFileProducer.java
@@ -109,7 +109,10 @@ public class RemoteFileProducer<T> extends
GenericFileProducer<T> {
@Override
public void preWriteCheck(Exchange exchange) throws Exception {
- doPreWriteCheck(exchange,
getEndpoint().getConfiguration().isSendNoop());
+ // skip the noop when the operations report a recent upload, download
or noop (see isRecentlyUsed); the health
+ // check calls doPreWriteCheck(exchange, true) itself, so it is not
affected
+ boolean sendNoop = getEndpoint().getConfiguration().isSendNoop() &&
!getOperations().isRecentlyUsed();
+ doPreWriteCheck(exchange, sendNoop);
}
protected void doPreWriteCheck(Exchange exchange, boolean sendNoop) throws
Exception {
diff --git a/components/camel-ftp/src/main/docs/ftp-component.adoc
b/components/camel-ftp/src/main/docs/ftp-component.adoc
index 085c526fbd12..4494ef2cab68 100644
--- a/components/camel-ftp/src/main/docs/ftp-component.adoc
+++ b/components/camel-ftp/src/main/docs/ftp-component.adoc
@@ -534,8 +534,6 @@ CDUP
200 CDUP successful. "/one/two" is current directory.
CWD /
250 CWD successful. "/" is current directory.
-PWD
-257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
@@ -547,8 +545,6 @@ RETR foo.txt
226 Transfer OK
CWD /
250 CWD successful. "/" is current directory.
-PWD
-257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
@@ -562,8 +558,6 @@ RETR a.txt
226 Transfer OK
CWD /
250 CWD successful. "/" is current directory.
-PWD
-257 "/" is current directory.
CWD one
250 CWD successful. "/one" is current directory.
CWD two
@@ -575,14 +569,16 @@ PORT 127,0,0,1,17,99
RETR b.txt
150 Opening data channel for file transfer.
226 Transfer OK
-CWD /
-250 CWD successful. "/" is current directory.
QUIT
221 Goodbye
disconnected.
----
As you can see when stepwise is enabled, it will traverse the directory
-structure using CD xxx.
+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.
Stepwise Disabled::
+
diff --git
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
index 47514dfa9b8b..7d8386d29e32 100644
---
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
+++
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/FtpOperations.java
@@ -25,19 +25,24 @@ import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketTimeoutException;
import java.time.Duration;
+import java.util.Collections;
import java.util.Iterator;
import java.util.Objects;
+import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
+import org.apache.camel.StreamCache;
import org.apache.camel.component.file.FileComponent;
import org.apache.camel.component.file.GenericFile;
import org.apache.camel.component.file.GenericFileEndpoint;
import org.apache.camel.component.file.GenericFileExist;
import org.apache.camel.component.file.GenericFileHelper;
import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.support.LRUCacheFactory;
import org.apache.camel.support.ObjectHelper;
import org.apache.camel.support.task.BlockingTask;
import org.apache.camel.support.task.Tasks;
@@ -63,6 +68,16 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
* How long a disconnect waits at most for the reply to QUIT (soTimeout
when it is shorter).
*/
private static final int QUIT_REPLY_TIMEOUT = 2000;
+ /**
+ * How long after the server completed an upload, a download or a noop the
producer does not send a noop before the
+ * next upload, as the connection was just seen working.
+ */
+ private static final long RECENTLY_USED_NANOS =
TimeUnit.SECONDS.toNanos(1);
+ /**
+ * How many directories autoCreate remembers on a connection at most: the
gain is for repeated uploads into the same
+ * directories, and a producer that writes into a new directory for each
message must not grow without limit.
+ */
+ private static final int MAX_BUILT_DIRECTORIES = 100;
protected final Logger log = LoggerFactory.getLogger(getClass());
protected final FTPClient client;
@@ -76,6 +91,41 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
* file. Each operation holds this lock, so that the commands and replies
of two operations do not mix.
*/
protected final ReentrantLock lock = new ReentrantLock();
+ /**
+ * The current directory of the connection, as the server gave it to PWD
or as an absolute change of directory set
+ * it, so that a stepwise operation does not ask for it each time. {@code
null} when unknown.
+ */
+ private String workingDirectory;
+ /**
+ * The directory to change back to before an operation that uses names
relative to the directory where the
+ * operations started: a stepwise upload, download or delete stays in the
directory of its file, so that the next
+ * download or delete in that directory needs no change of directory (an
upload changes back and into it again, see
+ * {@link #storeFileInItsDirectory(String, Exchange)}). {@code null} when
there is nothing to change back.
+ */
+ private String restoreDirectory;
+ /**
+ * The directory part of the file name (relative to {@link
#restoreDirectory}, or absolute) that a stepwise upload,
+ * download or delete changed into. {@code null} when the connection is
not in such a directory, also when the
+ * change failed half way.
+ */
+ private String stepwiseDirectory;
+ /**
+ * Whether an upload, a download or a delete runs, with or without
stepwise: the operations that it calls, such as
+ * the existence check or the move of an existing file, use names relative
to the directory of the file and must not
+ * change back.
+ */
+ private boolean inStepwiseOperation;
+ /**
+ * The directories that a file was uploaded into on this connection, as
absolute paths (see
+ * {@link #builtDirectoryKey(String)}), so that autoCreate does not check
them again before the next upload. Only an
+ * upload adds a directory: the moves of a consumer check their directory
each time. Holds the
+ * {@link #MAX_BUILT_DIRECTORIES} most recently used ones.
+ */
+ private final Set<String> builtDirectories =
Collections.newSetFromMap(LRUCacheFactory.newLRUCache(MAX_BUILT_DIRECTORIES));
+ /**
+ * When the server last completed an upload, a download or a noop ({@link
System#nanoTime()}), or 0.
+ */
+ private volatile long lastCompletedNanos;
private static class TaskPayload {
final RemoteFileConfiguration configuration;
@@ -117,6 +167,8 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
throws GenericFileOperationFailedException {
lock.lock();
try {
+ // a new connection starts in the login directory
+ resetConnectionState();
client.setCopyStreamListener(clientActivityListener);
try {
@@ -329,6 +381,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
public void disconnect() throws GenericFileOperationFailedException {
lock.lock();
try {
+ resetConnectionState();
try {
doDisconnect();
} catch (GenericFileOperationFailedException e) {
@@ -413,37 +466,24 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
checkName(name);
boolean result;
- String target = name;
- String currentDir = null;
-
+ boolean outer = inStepwiseOperation;
try {
reconnectIfNecessary(null);
- if (endpoint.getConfiguration().isStepwise()) {
- // remember current directory
- currentDir = getCurrentDirectory();
- target = FileUtil.stripPath(name);
-
- try {
- changeCurrentDirectory(FileUtil.onlyPath(name));
- } catch (GenericFileOperationFailedException e) {
- // we could not change directory, try to change back
before
- changeCurrentDirectory(currentDir);
- throw e;
- }
- }
-
- // delete the file
- log.trace("Client deleteFile: {}", target);
- result = client.deleteFile(target);
+ if (outer) {
+ result = deleteFileDuringOperation(name);
+ } else {
+ inStepwiseOperation = true;
+ String target = changeToDirectoryOf(name);
- // change back to previous directory
- if (currentDir != null) {
- changeCurrentDirectory(currentDir);
+ // delete the file
+ log.trace("Client deleteFile: {}", target);
+ result = client.deleteFile(target);
}
-
} catch (IOException e) {
throw new GenericFileOperationFailedException(
client.getReplyCode(), client.getReplyString(),
e.getMessage(), e);
+ } finally {
+ inStepwiseOperation = outer;
}
return result;
@@ -452,6 +492,30 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
}
}
+ /**
+ * Deletes a file while an upload or a download runs, such as from a
custom move-existing strategy of the upload:
+ * the name is relative to the directory of the file of that operation, so
a stepwise delete changes in relative to
+ * that directory and back, and leaves the connection where the operation
needs it.
+ */
+ private boolean deleteFileDuringOperation(String name) throws IOException {
+ String path = FileUtil.onlyPath(name);
+ if (path == null || !endpoint.getConfiguration().isStepwise()) {
+ log.trace("Client deleteFile: {}", name);
+ return client.deleteFile(name);
+ }
+ String current = currentDirectory();
+ try {
+ workingDirectory = null;
+ changeDirectory(FtpUtils.compactPath(path));
+ String target = FileUtil.stripPath(name);
+ log.trace("Client deleteFile: {}", target);
+ return client.deleteFile(target);
+ } finally {
+ changeDirectory(current);
+ workingDirectory = current;
+ }
+ }
+
@Override
public boolean renameFile(String from, String to) throws
GenericFileOperationFailedException {
lock.lock();
@@ -461,6 +525,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
checkName(to);
try {
reconnectIfNecessary(null);
+ leaveStepwiseDirectory();
return client.rename(from, to);
} catch (IOException e) {
throw new GenericFileOperationFailedException(
@@ -480,11 +545,18 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
checkName(directory);
log.trace("buildDirectory({})", directory);
+ String key = builtDirectoryKey(directory);
+ if (builtDirectories.contains(key)) {
+ log.trace("Directory {} was checked or created before on this
connection", directory);
+ return true;
+ }
+ leaveStepwiseDirectory();
try {
- String originalDirectory = client.printWorkingDirectory();
+ String originalDirectory = getCurrentDirectory();
boolean success;
// maybe the full directory already exists
+ workingDirectory = null;
success = client.changeWorkingDirectory(directory);
if (!success) {
log.trace("Trying to build remote directory: {}",
directory);
@@ -523,6 +595,8 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
clientActivityListener.onBeginDownloading(endpoint.getConfiguration().remoteServerInformation(),
name);
boolean answer;
+ boolean outer = inStepwiseOperation;
+ inStepwiseOperation = true;
try {
log.trace("retrieveFile({})", name);
if
(org.apache.camel.util.ObjectHelper.isNotEmpty(endpoint.getLocalWorkDirectory()))
{
@@ -536,9 +610,12 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
} catch (GenericFileOperationFailedException e) {
clientActivityListener.onGeneralError(endpoint.getConfiguration().remoteServerInformation(),
e.getMessage());
throw e;
+ } finally {
+ inStepwiseOperation = outer;
}
if (answer) {
+ lastCompletedNanos = System.nanoTime();
clientActivityListener.onDownloadComplete(endpoint.getConfiguration().remoteServerInformation(),
name);
}
return answer;
@@ -594,23 +671,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
org.apache.camel.util.ObjectHelper.notNull(target,
"Exchange should have the " +
FileComponent.FILE_EXCHANGE_FILE + " set");
- String remoteName = name;
- String currentDir = null;
- if (endpoint.getConfiguration().isStepwise()) {
- // remember current directory
- currentDir = getCurrentDirectory();
-
- // change directory to path where the file is to be retrieved
- // (must do this as some FTP servers cannot retrieve using
- // absolute path)
- String path = FileUtil.onlyPath(name);
- if (path != null) {
- changeCurrentDirectory(path);
- }
- // remote name is now only the file name as we just changed
- // directory
- remoteName = FileUtil.stripPath(name);
- }
+ String remoteName = changeToDirectoryOf(name);
log.trace("Client retrieveFile: {}", remoteName);
if (endpoint.getConfiguration().isStreamDownload()) {
@@ -634,11 +695,6 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE,
client.getReplyCode());
exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING,
client.getReplyString());
- // change back to current directory
- if (endpoint.getConfiguration().isStepwise()) {
- changeCurrentDirectory(currentDir);
- }
-
} catch (IOException e) {
throw new
GenericFileOperationFailedException(client.getReplyCode(),
client.getReplyString(), e.getMessage(), e);
}
@@ -725,23 +781,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
// store the java.io.File handle as the body
target.setBody(local);
- String remoteName = name;
- String currentDir = null;
- if (endpoint.getConfiguration().isStepwise()) {
- // remember current directory
- currentDir = getCurrentDirectory();
-
- // change directory to path where the file is to be retrieved
- // (must do this as some FTP servers cannot retrieve using
- // absolute path)
- String path = FileUtil.onlyPath(name);
- if (path != null) {
- changeCurrentDirectory(path);
- }
- // remote name is now only the file name as we just changed
- // directory
- remoteName = FileUtil.stripPath(name);
- }
+ String remoteName = changeToDirectoryOf(name);
// the file exists so lets try to resume the download
if (resumeDownload && existingSize > 0) {
@@ -758,11 +798,6 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
exchange.getIn().setHeader(FtpConstants.FTP_REPLY_CODE,
client.getReplyCode());
exchange.getIn().setHeader(FtpConstants.FTP_REPLY_STRING,
client.getReplyString());
- // change back to current directory
- if (endpoint.getConfiguration().isStepwise()) {
- changeCurrentDirectory(currentDir);
- }
-
} catch (IOException e) {
log.trace("Error occurred during retrieving file: {} to local
directory.", name);
// if we do not attempt to resume download, then attempt to delete
@@ -823,30 +858,25 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
log.trace("storeFile({})", name);
boolean answer;
- String currentDir = null;
- String path = FileUtil.onlyPath(name);
- String targetName = name;
-
try {
- if (path != null && endpoint.getConfiguration().isStepwise()) {
- // must remember current dir so we stay in that directory
after
- // the write
- currentDir = getCurrentDirectory();
-
- // change to path of name
- changeCurrentDirectory(path);
-
- // the target name should be without path, as we have
changed
- // directory
- targetName = FileUtil.stripPath(name);
+ GenericFileOperationFailedException failure = null;
+ try {
+ answer = storeFileInItsDirectory(name, exchange);
+ } catch (GenericFileOperationFailedException e) {
+ failure = e;
+ answer = false;
}
-
- // store the file
- answer = doStoreFile(name, targetName, exchange);
-
- // change back to current directory if we changed directory
- if (currentDir != null) {
- changeCurrentDirectory(currentDir);
+ if (!answer) {
+ // the reply to the change of directory or to STOR, not to
a SITE CHMOD that may follow it
+ int code = failure != null ? failure.getCode() :
storeReplyCode(exchange);
+ if (FTPReply.isNegativePermanent(code) &&
isBuiltDirectoryMissing(name, exchange, failure)) {
+ answer = storeFileInBuiltDirectoryAgain(name,
exchange, failure);
+ } else if (failure != null) {
+ throw failure;
+ }
+ }
+ if (answer) {
+ rememberBuiltDirectory(FileUtil.onlyPath(name));
}
} catch (GenericFileOperationFailedException e) {
clientActivityListener.onGeneralError(endpoint.getConfiguration().remoteServerInformation(),
e.getMessage());
@@ -854,6 +884,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
}
if (answer) {
+ lastCompletedNanos = System.nanoTime();
clientActivityListener.onUploadComplete(endpoint.getConfiguration().remoteServerInformation(),
name);
}
@@ -861,7 +892,8 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
Integer code =
exchange.getIn().getHeader(FtpConstants.FTP_REPLY_CODE, Integer.class);
String status =
exchange.getIn().getHeader(FtpConstants.FTP_REPLY_STRING, String.class);
if (code != null && status != null) {
- throw new GenericFileOperationFailedException(code,
status, "Error writing file [" + targetName + "]");
+ throw new GenericFileOperationFailedException(
+ code, status, "Error writing file [" +
targetNameOf(name) + "]");
}
}
@@ -957,11 +989,212 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
}
}
+ private boolean storeFileInItsDirectory(String name, Exchange exchange) {
+ // change into the directory of the file for each upload, even when
the previous upload left the connection
+ // there: a server such as vsftpd keeps the directory itself, not its
path, so after the directory was renamed
+ // or replaced, a STOR without the change would store the file in the
old directory, without an error
+ leaveStepwiseDirectory();
+ boolean outer = inStepwiseOperation;
+ inStepwiseOperation = true;
+ try {
+ return doStoreFile(name, changeToDirectoryOf(name), exchange);
+ } finally {
+ inStepwiseOperation = outer;
+ }
+ }
+
+ private boolean storeFileInBuiltDirectoryAgain(
+ String name, Exchange exchange,
GenericFileOperationFailedException failure) {
+ String directory = FileUtil.onlyPath(name);
+ String reason = failure != null
+ ? failure.getMessage() :
exchange.getIn().getHeader(FtpConstants.FTP_REPLY_STRING, String.class);
+ log.info("Cannot store file: {} as directory: {}, where a file was
stored before on this connection, was removed"
+ + " since ({}). Creating the directory again and storing the
file once more.",
+ name, directory, reason);
+ try {
+ if (!buildDirectory(directory, false)) {
+ throw new GenericFileOperationFailedException(
+ "Cannot store file: " + name + " as directory: " +
directory
+ + " was removed
and cannot be created again");
+ }
+ if (exchange.getIn().getBody() instanceof StreamCache cache) {
+ // the failed attempt may have read it
+ cache.reset();
+ }
+ return storeFileInItsDirectory(name, exchange);
+ } catch (GenericFileOperationFailedException retryFailure) {
+ if (failure != null) {
+ retryFailure.addSuppressed(failure);
+ }
+ throw retryFailure;
+ }
+ }
+
+ private int storeReplyCode(Exchange exchange) {
+ Integer code = exchange.getIn().getHeader(FtpConstants.FTP_REPLY_CODE,
Integer.class);
+ return code != null ? code : client.getReplyCode();
+ }
+
+ /**
+ * Records that a file was stored in a directory, so that autoCreate does
not check it again on this connection.
+ */
+ private void rememberBuiltDirectory(String directory) {
+ if (directory != null) {
+
builtDirectories.add(builtDirectoryKey(endpoint.getConfiguration().normalizePath(directory)));
+ }
+ }
+
+ /**
+ * As {@link #isBuiltDirectoryMissing(String, Exchange)}, but a failure of
the check is added to the failure of the
+ * upload, which is thrown, so that the reason of the failed upload is
kept.
+ */
+ private boolean isBuiltDirectoryMissing(String name, Exchange exchange,
GenericFileOperationFailedException failure) {
+ try {
+ return isBuiltDirectoryMissing(name, exchange);
+ } catch (RuntimeException checkFailure) {
+ if (failure == null) {
+ throw checkFailure;
+ }
+ failure.addSuppressed(checkFailure);
+ throw failure;
+ }
+ }
+
+ /**
+ * Whether an upload failed as the directory where a file was stored
before on this connection was removed since,
+ * and can be tried again once the directory is created again: autoCreate
is enabled, the body can be read again,
+ * and the upload does not append (it could append twice). Changes back to
the directory where the operations
+ * started, forgets the directory so that the next upload checks it, and
sends a CWD to check that the directory is
+ * missing, as the server gives no specific reply for it.
+ */
+ private boolean isBuiltDirectoryMissing(String name, Exchange exchange) {
+ String directory = FileUtil.onlyPath(name);
+ if (directory == null || !endpoint.isAutoCreate()) {
+ return false;
+ }
+ changeBackToRestoreDirectory();
+ directory = endpoint.getConfiguration().normalizePath(directory);
+ boolean known = builtDirectories.remove(builtDirectoryKey(directory));
+ if (!known || !FtpUtils.isBodyReadableAgain(exchange.getIn().getBody())
+ || endpoint.getFileExist() == GenericFileExist.Append) {
+ return false;
+ }
+ // the server gives no specific reply for a missing directory, so
check that it is missing
+ String original = currentDirectory();
+ try {
+ workingDirectory = null;
+ if (client.changeWorkingDirectory(directory)) {
+ changeCurrentDirectory(original);
+ return false;
+ }
+ workingDirectory = original;
+ return true;
+ } catch (IOException e) {
+ throw new GenericFileOperationFailedException(
+ client.getReplyCode(), client.getReplyString(),
e.getMessage(), e);
+ }
+ }
+
+ private String targetNameOf(String name) {
+ return endpoint.getConfiguration().isStepwise() ?
FileUtil.stripPath(name) : name;
+ }
+
+ /**
+ * Changes into the directory of a file for a stepwise upload, download or
delete, as some servers cannot use a path
+ * in the name of the file, unless the connection is already there, and
returns the name relative to it. Without
+ * stepwise, or for a file without a path, changes back to the directory
where the operations started and returns
+ * the name.
+ */
+ private String changeToDirectoryOf(String name) {
+ String path = FileUtil.onlyPath(name);
+ if (path == null || !endpoint.getConfiguration().isStepwise()) {
+ changeBackToRestoreDirectory();
+ return name;
+ }
+ changeToStepwiseDirectory(path);
+ return FileUtil.stripPath(name);
+ }
+
+ /**
+ * Changes into the directory of a stepwise operation, unless a previous
one left the connection there, and
+ * remembers the directory to change back to. When the change fails half
way, the next operation changes back.
+ */
+ private void changeToStepwiseDirectory(String path) {
+ if (restoreDirectory != null && path.equals(stepwiseDirectory)) {
+ log.trace("Already in directory: {}", path);
+ return;
+ }
+ changeBackToRestoreDirectory();
+ restoreDirectory = currentDirectory();
+ changeCurrentDirectory(path);
+ stepwiseDirectory = path;
+ }
+
+ /**
+ * Changes back to the directory where a stepwise operation started,
before an operation that uses names relative to
+ * it. Does nothing while a stepwise operation runs, as the operations it
calls use names relative to the directory
+ * of its file.
+ */
+ private void leaveStepwiseDirectory() {
+ if (!inStepwiseOperation) {
+ changeBackToRestoreDirectory();
+ }
+ }
+
+ private void changeBackToRestoreDirectory() {
+ String directory = restoreDirectory;
+ if (directory == null) {
+ return;
+ }
+ restoreDirectory = null;
+ stepwiseDirectory = null;
+ try {
+ changeCurrentDirectory(directory);
+ } catch (RuntimeException e) {
+ // the next operation tries again
+ restoreDirectory = directory;
+ throw e;
+ }
+ }
+
+ private void resetConnectionState() {
+ workingDirectory = null;
+ restoreDirectory = null;
+ stepwiseDirectory = null;
+ builtDirectories.clear();
+ lastCompletedNanos = 0;
+ }
+
+ /**
+ * The key of a directory that autoCreate checked or created: a relative
directory is relative to the directory that
+ * a relative name resolves against, once the connection changed back from
a stepwise operation.
+ */
+ private String builtDirectoryKey(String directory) {
+ if (FileUtil.hasLeadingSeparator(directory)) {
+ return directory;
+ }
+ String base = !inStepwiseOperation && restoreDirectory != null ?
restoreDirectory : currentDirectory();
+ return base + "/" + directory;
+ }
+
+ private String currentDirectory() {
+ if (workingDirectory == null) {
+ try {
+ workingDirectory = client.printWorkingDirectory();
+ } catch (IOException e) {
+ throw new GenericFileOperationFailedException(
+ client.getReplyCode(), client.getReplyString(),
e.getMessage(), e);
+ }
+ }
+ return workingDirectory;
+ }
+
@Override
public boolean storeFileDirectly(String name, String payload) throws
GenericFileOperationFailedException {
lock.lock();
try {
checkName(name);
+ leaveStepwiseDirectory();
ByteArrayInputStream bis = new
ByteArrayInputStream(payload.getBytes());
try {
return client.storeFile(name, bis);
@@ -982,6 +1215,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
try {
log.trace("existsFile({})", name);
checkName(name);
+ leaveStepwiseDirectory();
if (endpoint.isFastExistsCheck()) {
return fastExistsFile(name);
}
@@ -1035,14 +1269,10 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
lock.lock();
try {
log.trace("getCurrentDirectory()");
- try {
- String answer = client.printWorkingDirectory();
- log.trace("Current dir: {}", answer);
- return answer;
- } catch (IOException e) {
- throw new GenericFileOperationFailedException(
- client.getReplyCode(), client.getReplyString(),
e.getMessage(), e);
- }
+ leaveStepwiseDirectory();
+ String answer = currentDirectory();
+ log.trace("Current dir: {}", answer);
+ return answer;
} finally {
lock.unlock();
}
@@ -1057,40 +1287,50 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
return;
}
checkName(path);
+ leaveStepwiseDirectory();
// must compact path so FTP server can traverse correctly
// use the ftp utils implementation of the compact path
path = FtpUtils.compactPath(path);
- // not stepwise should change directory in one operation
- if (!endpoint.getConfiguration().isStepwise()) {
- doChangeDirectory(path);
- return;
- }
-
- // if it starts with the root path then a little special handling
for
- // that
+ workingDirectory = null;
+ changeDirectory(path);
if (FileUtil.hasLeadingSeparator(path)) {
- // change to root path
- doChangeDirectory(path.substring(0, 1));
- path = path.substring(1);
+ // the server is now in that directory, so a stepwise
operation does not ask for it
+ workingDirectory = path;
}
+ } finally {
+ lock.unlock();
+ }
+ }
- // split into multiple dirs
- final String[] dirs = path.split("/|\\\\");
+ private void changeDirectory(String path) {
+ // not stepwise should change directory in one operation
+ if (!endpoint.getConfiguration().isStepwise()) {
+ doChangeDirectory(path);
+ return;
+ }
- if (dirs == null || dirs.length == 0) {
- // path was just a relative single path
- doChangeDirectory(path);
- return;
- }
+ // if it starts with the root path then a little special handling for
+ // that
+ if (FileUtil.hasLeadingSeparator(path)) {
+ // change to root path
+ doChangeDirectory(path.substring(0, 1));
+ path = path.substring(1);
+ }
- // there are multiple dirs so do this in chunks
- for (String dir : dirs) {
- doChangeDirectory(dir);
- }
- } finally {
- lock.unlock();
+ // split into multiple dirs
+ final String[] dirs = path.split("/|\\\\");
+
+ if (dirs == null || dirs.length == 0) {
+ // path was just a relative single path
+ doChangeDirectory(path);
+ return;
+ }
+
+ // there are multiple dirs so do this in chunks
+ for (String dir : dirs) {
+ doChangeDirectory(dir);
}
}
@@ -1136,6 +1376,8 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
public void changeToParentDirectory() throws
GenericFileOperationFailedException {
lock.lock();
try {
+ leaveStepwiseDirectory();
+ workingDirectory = null;
try {
client.changeToParentDirectory();
} catch (IOException e) {
@@ -1152,6 +1394,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
lock.lock();
try {
log.trace("Listing remote files");
+ leaveStepwiseDirectory();
clientActivityListener.onScanningForFiles(endpoint.remoteServerInformation(),
null);
try {
return checkListing(client.listFiles(), "the current
directory");
@@ -1177,6 +1420,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
path = ".";
}
checkName(path);
+ leaveStepwiseDirectory();
try {
return checkListing(client.listFiles(path), "directory: " +
path);
@@ -1218,7 +1462,11 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
try {
log.trace("sendNoOp");
try {
- return client.sendNoOp();
+ boolean answer = client.sendNoOp();
+ if (answer) {
+ lastCompletedNanos = System.nanoTime();
+ }
+ return answer;
} catch (IOException e) {
throw new GenericFileOperationFailedException(
client.getReplyCode(), client.getReplyString(),
e.getMessage(), e);
@@ -1233,6 +1481,7 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
lock.lock();
try {
log.trace("sendSiteCommand({})", command);
+ leaveStepwiseDirectory();
try {
return client.sendSiteCommand(command);
} catch (IOException e) {
@@ -1293,8 +1542,27 @@ public class FtpOperations implements
RemoteFileOperations<FTPFile> {
return success;
}
+ /**
+ * The FTP client, in the directory where the operations started: a
stepwise upload, download or delete stays in the
+ * directory of its file until another operation needs the starting
directory, so this changes back first. The next
+ * upload, download or delete may change directory again. As the caller
can change directory with the client, the
+ * current directory is asked for again when an operation needs it.
+ */
public FTPClient getClient() {
- return client;
+ lock.lock();
+ try {
+ leaveStepwiseDirectory();
+ workingDirectory = null;
+ return client;
+ } finally {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public boolean isRecentlyUsed() {
+ long last = lastCompletedNanos;
+ return last != 0 && System.nanoTime() - last < RECENTLY_USED_NANOS;
}
private void reconnectIfNecessary(Exchange exchange) throws
GenericFileOperationFailedException {
diff --git
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
index 590882685a91..8de52dd2dd2f 100644
---
a/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
+++
b/components/camel-ftp/src/main/java/org/apache/camel/component/file/remote/SftpOperations.java
@@ -33,8 +33,10 @@ import java.security.KeyPair;
import java.time.Duration;
import java.util.Arrays;
import java.util.Base64;
+import java.util.Collections;
import java.util.List;
import java.util.Locale;
+import java.util.Set;
import java.util.Vector;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@@ -58,6 +60,7 @@ import org.apache.camel.Exchange;
import org.apache.camel.InvalidPayloadException;
import org.apache.camel.LoggingLevel;
import org.apache.camel.RuntimeCamelException;
+import org.apache.camel.StreamCache;
import org.apache.camel.component.file.FileComponent;
import org.apache.camel.component.file.GenericFile;
import org.apache.camel.component.file.GenericFileEndpoint;
@@ -66,6 +69,7 @@ import org.apache.camel.component.file.GenericFileHelper;
import org.apache.camel.component.file.GenericFileListingOperations;
import org.apache.camel.component.file.GenericFileOperationFailedException;
import org.apache.camel.spi.CamelLogger;
+import org.apache.camel.support.LRUCacheFactory;
import org.apache.camel.support.ResourceHelper;
import org.apache.camel.support.task.BlockingTask;
import org.apache.camel.support.task.Tasks;
@@ -96,6 +100,11 @@ public class SftpOperations
// while the stop of the producer waits for an operation of another
thread, how often it checks whether the shutdown
// is forced, and then how long it waits for the disconnect
private static final long DISCONNECT_ON_STOP_WAIT_MILLIS = 1000;
+ /**
+ * How many directories autoCreate remembers on a connection at most: the
gain is for repeated uploads into the same
+ * directories, and a producer that writes into a new directory for each
message must not grow without limit.
+ */
+ private static final int MAX_BUILT_DIRECTORIES = 100;
private Proxy proxy;
private SftpEndpoint endpoint;
private ChannelSftp channel;
@@ -104,6 +113,32 @@ public class SftpOperations
private final Lock lock = new ReentrantLock();
// whether connect, with its reconnect attempts, holds the lock
private volatile boolean connecting;
+ /**
+ * The directory to change back to before an operation that uses names
relative to the directory where the
+ * operations started: a stepwise upload or download stays in the
directory of its file, so that the next file in
+ * that directory needs no change of directory. {@code null} when there is
nothing to change back. JSch keeps the
+ * current directory on the client and sends absolute paths, but checks
every change of directory with the server.
+ */
+ private String restoreDirectory;
+ /**
+ * The directory part of the file name (relative to {@link
#restoreDirectory}, or absolute) that a stepwise upload
+ * or download changed into. {@code null} when the connection is not in
such a directory, also when the change
+ * failed half way.
+ */
+ private String stepwiseDirectory;
+ /**
+ * Whether an upload or a download runs, with or without stepwise: the
operations that it calls, such as the
+ * existence check or the move of an existing file, use names relative to
the directory of the file and must not
+ * change back.
+ */
+ private boolean inStepwiseOperation;
+ /**
+ * The directories that a file was uploaded into on this connection, as
absolute paths (see
+ * {@link #builtDirectoryKey(String)}), so that autoCreate does not check
them again before the next upload. Only an
+ * upload adds a directory: the moves of a consumer check their directory
each time. Holds the
+ * {@link #MAX_BUILT_DIRECTORIES} most recently used ones.
+ */
+ private final Set<String> builtDirectories =
Collections.newSetFromMap(LRUCacheFactory.newLRUCache(MAX_BUILT_DIRECTORIES));
private static class TaskPayload {
final RemoteFileConfiguration configuration;
@@ -188,6 +223,8 @@ public class SftpOperations
}
configureBulkRequests();
+ // a new channel starts in the login directory
+ resetDirectoryState();
return true;
} finally {
@@ -710,6 +747,7 @@ public class SftpOperations
channel.disconnect();
}
} finally {
+ resetDirectoryState();
lock.unlock();
}
}
@@ -810,6 +848,7 @@ public class SftpOperations
// ensure these
session = null;
channel = null;
+ resetDirectoryState();
lock.unlock();
}
}
@@ -828,6 +867,7 @@ public class SftpOperations
name = endpoint.getConfiguration().normalizePath(name);
LOG.debug("Deleting file: {}", name);
reconnectIfNecessary(null);
+ leaveStepwiseDirectory();
channel.rm(quotePathForJsch(name));
return true;
} catch (SftpException e) {
@@ -844,6 +884,7 @@ public class SftpOperations
try {
LOG.debug("Renaming file: {} to: {}", from, to);
reconnectIfNecessary(null);
+ leaveStepwiseDirectory();
// make use of the '/' separator because JSch expects this
// as the file separator even on Windows
to = FileUtil.compactPath(to, '/');
@@ -865,6 +906,12 @@ public class SftpOperations
directory = endpoint.getConfiguration().normalizePath(directory);
LOG.trace("buildDirectory({},{})", directory, absolute);
+ String key = builtDirectoryKey(directory);
+ if (builtDirectories.contains(key)) {
+ LOG.trace("Directory {} was checked or created before on this
connection", directory);
+ return true;
+ }
+ leaveStepwiseDirectory();
// ignore absolute as all dirs are relative with FTP
boolean success = false;
@@ -962,16 +1009,87 @@ public class SftpOperations
lock.lock();
try {
LOG.trace("getCurrentDirectory()");
- String answer = channel.pwd();
+ leaveStepwiseDirectory();
+ String answer = pwd();
LOG.trace("Current dir: {}", answer);
return answer;
- } catch (SftpException e) {
- throw operationFailed("Cannot get current directory", e);
} finally {
lock.unlock();
}
}
+ private String pwd() {
+ try {
+ // JSch keeps the current directory on the client: this sends
nothing
+ return channel.pwd();
+ } catch (SftpException e) {
+ throw operationFailed("Cannot get current directory", e);
+ }
+ }
+
+ /**
+ * Changes into the directory of a stepwise upload or download, unless a
previous one left the connection there, and
+ * remembers the directory to change back to. When the change fails half
way, the next operation changes back.
+ */
+ private void changeToStepwiseDirectory(String path) {
+ if (restoreDirectory != null && path.equals(stepwiseDirectory)) {
+ LOG.trace("Already in directory: {}", path);
+ return;
+ }
+ changeBackToRestoreDirectory();
+ restoreDirectory = pwd();
+ changeCurrentDirectory(path);
+ stepwiseDirectory = path;
+ }
+
+ /**
+ * Changes back to the directory where a stepwise upload or download
started, before an operation that uses names
+ * relative to it. Does nothing while a stepwise operation runs, as the
operations it calls use names relative to
+ * the directory of its file.
+ */
+ private void leaveStepwiseDirectory() {
+ if (!inStepwiseOperation) {
+ changeBackToRestoreDirectory();
+ }
+ }
+
+ private void changeBackToRestoreDirectory() {
+ String directory = restoreDirectory;
+ if (directory == null) {
+ return;
+ }
+ restoreDirectory = null;
+ stepwiseDirectory = null;
+ try {
+ // one change to the absolute path that JSch gave, not up one
directory at a time, as the directory that the
+ // connection is in may have been removed
+ LOG.trace("Changing back to directory: {}", directory);
+ doChangeDirectory(directory);
+ } catch (RuntimeException e) {
+ // the next operation tries again
+ restoreDirectory = directory;
+ throw e;
+ }
+ }
+
+ private void resetDirectoryState() {
+ restoreDirectory = null;
+ stepwiseDirectory = null;
+ builtDirectories.clear();
+ }
+
+ /**
+ * The key of a directory that autoCreate checked or created: a relative
directory is relative to the directory that
+ * a relative name resolves against, once the connection changed back from
a stepwise operation.
+ */
+ private String builtDirectoryKey(String directory) {
+ if (FileUtil.hasLeadingSeparator(directory)) {
+ return directory;
+ }
+ String base = !inStepwiseOperation && restoreDirectory != null ?
restoreDirectory : pwd();
+ return base + "/" + directory;
+ }
+
@Override
public void changeCurrentDirectory(String path) throws
GenericFileOperationFailedException {
lock.lock();
@@ -980,6 +1098,7 @@ public class SftpOperations
if (ObjectHelper.isEmpty(path)) {
return;
}
+ leaveStepwiseDirectory();
// must compact path so SFTP server can traverse correctly, make
use of
// the '/'
@@ -1105,6 +1224,7 @@ public class SftpOperations
// list current directory if file path is not given
path = ".";
}
+ leaveStepwiseDirectory();
Vector<?> files = channel.ls(quotePathForJsch(path));
@@ -1124,6 +1244,7 @@ public class SftpOperations
String dir = ObjectHelper.isEmpty(path) ? "." : path;
try {
LOG.trace("Listing remote files from path {} one at a time", dir);
+ leaveStepwiseDirectory();
RuntimeException[] failure = { null };
channel.ls(quotePathForJsch(dir), entry -> {
try {
@@ -1170,6 +1291,7 @@ public class SftpOperations
public boolean isSymbolicLink(String path) throws
GenericFileOperationFailedException {
lock.lock();
try {
+ leaveStepwiseDirectory();
return channel.lstat(quotePathForJsch(path)).isLink();
} catch (SftpException e) {
throw operationFailed("Cannot get the attributes of: " + path, e);
@@ -1182,6 +1304,7 @@ public class SftpOperations
public String readSymbolicLink(String path) throws
GenericFileOperationFailedException {
lock.lock();
try {
+ leaveStepwiseDirectory();
return channel.readlink(quotePathForJsch(path));
} catch (SftpException e) {
throw operationFailed("Cannot read the symbolic link: " + path, e);
@@ -1243,6 +1366,7 @@ public class SftpOperations
lock.lock();
try {
LOG.trace("retrieveFile({})", name);
+ inStepwiseOperation = true;
if (ObjectHelper.isNotEmpty(endpoint.getLocalWorkDirectory())) {
// local work directory is configured so we should store file
// content as files in this local directory
@@ -1252,6 +1376,7 @@ public class SftpOperations
return retrieveFileToStreamInBody(name, exchange);
}
} finally {
+ inStepwiseOperation = false;
lock.unlock();
}
}
@@ -1276,29 +1401,12 @@ public class SftpOperations
@SuppressWarnings("unchecked")
private boolean retrieveFileToStreamInBody(String name, Exchange exchange)
throws GenericFileOperationFailedException {
- String currentDir = null;
- boolean retrieved = false;
try {
GenericFile<ChannelSftp.LsEntry> target
= (GenericFile<ChannelSftp.LsEntry>)
exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE);
ObjectHelper.notNull(target, "Exchange should have the " +
FileComponent.FILE_EXCHANGE_FILE + " set");
- String remoteName = name;
- if (endpoint.getConfiguration().isStepwise()) {
- // remember current directory
- currentDir = getCurrentDirectory();
-
- // change directory to path where the file is to be retrieved
- // (must do this as some FTP servers cannot retrieve using
- // absolute path)
- String path = FileUtil.onlyPath(name);
- if (path != null) {
- changeCurrentDirectory(path);
- }
- // remote name is now only the file name as we just changed
- // directory
- remoteName = FileUtil.stripPath(name);
- }
+ String remoteName = changeToDirectoryOf(name);
// use input stream which works with Apache SSHD used for testing
InputStream is = channel.get(quotePathForJsch(remoteName));
@@ -1317,16 +1425,12 @@ public class SftpOperations
}
createResultHeadersFromExchange(null, exchange);
- retrieved = true;
return true;
} catch (SftpException e) {
createResultHeadersFromExchange(e, exchange);
throw operationFailed("Cannot retrieve file: " + name, e);
} catch (IOException e) {
throw new GenericFileOperationFailedException("Cannot retrieve
file: " + name, e);
- } finally {
- // change back to current directory if we changed directory
- changeBackToDirectory(currentDir, retrieved);
}
}
@@ -1382,31 +1486,13 @@ public class SftpOperations
} catch (Exception e) {
throw new GenericFileOperationFailedException("Cannot create new
local work file: " + local, e);
}
- String currentDir = null;
- boolean retrieved = false;
try {
// store the java.io.File handle as the body
file.setBody(local);
- String remoteName = name;
- if (endpoint.getConfiguration().isStepwise()) {
- // remember current directory
- currentDir = getCurrentDirectory();
-
- // change directory to path where the file is to be retrieved
- // (must do this as some FTP servers cannot retrieve using
- // absolute path)
- String path = FileUtil.onlyPath(name);
- if (path != null) {
- changeCurrentDirectory(path);
- }
- // remote name is now only the file name as we just changed
- // directory
- remoteName = FileUtil.stripPath(name);
- }
+ String remoteName = changeToDirectoryOf(name);
channel.get(quotePathForJsch(remoteName), os);
- retrieved = true;
} catch (SftpException e) {
createResultHeadersFromExchange(e, exchange);
LOG.trace("Error occurred during retrieving file: {} to local
directory. Deleting local work file: {}", name, temp);
@@ -1422,8 +1508,6 @@ public class SftpOperations
throw operationFailed("Cannot retrieve file: " + name, e);
} finally {
IOHelper.close(os, "retrieve: " + name, LOG);
- // change back to current directory if we changed directory
- changeBackToDirectory(currentDir, retrieved);
}
createResultHeadersFromExchange(null, exchange);
@@ -1453,62 +1537,115 @@ public class SftpOperations
LOG.trace("storeFile({})", name);
+ String directory = FileUtil.onlyPath(name);
boolean answer;
- String currentDir = null;
- String path = FileUtil.onlyPath(name);
- String targetName = name;
-
- if (path != null && endpoint.getConfiguration().isStepwise()) {
- // must remember current dir so we stay in that directory after
- // the write
- currentDir = getCurrentDirectory();
-
- // change to path of name
- changeCurrentDirectory(path);
-
- // the target name should be without path, as we have changed
- // directory
- targetName = FileUtil.stripPath(name);
- }
-
- boolean stored = false;
try {
- // store the file
- answer = doStoreFile(name, targetName, exchange);
- stored = true;
- } finally {
- // change back to current directory if we changed directory
- changeBackToDirectory(currentDir, stored);
+ answer = storeFileInItsDirectory(name, exchange);
+ } catch (GenericFileOperationFailedException e) {
+ boolean missing;
+ try {
+ missing = e.getCode() == ChannelSftp.SSH_FX_NO_SUCH_FILE
&& isBuiltDirectoryMissing(directory, exchange);
+ } catch (RuntimeException checkFailure) {
+ e.addSuppressed(checkFailure);
+ throw e;
+ }
+ if (!missing) {
+ throw e;
+ }
+ answer = storeFileInBuiltDirectoryAgain(name, directory,
exchange, e);
+ }
+ if (answer) {
+ rememberBuiltDirectory(directory);
}
-
return answer;
} finally {
lock.unlock();
}
}
+ private boolean storeFileInItsDirectory(String name, Exchange exchange) {
+ inStepwiseOperation = true;
+ try {
+ String targetName = changeToDirectoryOf(name);
+ return doStoreFile(name, targetName, exchange);
+ } finally {
+ inStepwiseOperation = false;
+ }
+ }
+
+ private boolean storeFileInBuiltDirectoryAgain(
+ String name, String directory, Exchange exchange,
GenericFileOperationFailedException failure) {
+ LOG.info("Cannot store file: {} as directory: {}, where a file was
stored before on this connection, was removed"
+ + " since ({}). Creating the directory again and storing the
file once more.",
+ name, directory, failure.getMessage());
+ try {
+ if (!buildDirectory(directory, false)) {
+ throw new GenericFileOperationFailedException(
+ "Cannot store file: " + name + " as directory: " +
directory
+ + " was removed
and cannot be created again");
+ }
+ if (exchange.getIn().getBody() instanceof StreamCache cache) {
+ // the failed attempt may have read it
+ cache.reset();
+ }
+ return storeFileInItsDirectory(name, exchange);
+ } catch (GenericFileOperationFailedException retryFailure) {
+ retryFailure.addSuppressed(failure);
+ throw retryFailure;
+ }
+ }
+
/**
- * Changes back to the directory that a stepwise operation started in,
also when the operation failed, so that the
- * next operation does not start in the directory of the file. When the
operation failed, a failure to change back
- * is only logged, so that it does not hide why the operation failed.
- *
- * @param directory the directory to change back to, or {@code null} if
the operation did not change directory
- * @param succeeded whether the operation succeeded
+ * Records that a file was stored in a directory, so that autoCreate does
not check it again on this connection.
*/
- private void changeBackToDirectory(String directory, boolean succeeded) {
- if (directory == null) {
- return;
+ private void rememberBuiltDirectory(String directory) {
+ if (directory != null) {
+
builtDirectories.add(builtDirectoryKey(endpoint.getConfiguration().normalizePath(directory)));
}
- if (succeeded) {
- changeCurrentDirectory(directory);
- return;
+ }
+
+ /**
+ * Whether an upload failed as the directory where a file was stored
before on this connection was removed since,
+ * and can be tried again once the directory is created again: autoCreate
is enabled, the body can be read again,
+ * and the upload does not append (it could append twice). Changes back to
the directory where the operations
+ * started, forgets the directory so that the next upload checks it, and
asks the server whether the directory
+ * exists, as the same status can come from a step after the upload, such
as the chmod of the file.
+ */
+ private boolean isBuiltDirectoryMissing(String directory, Exchange
exchange) {
+ if (directory == null || !endpoint.isAutoCreate()) {
+ return false;
+ }
+ changeBackToRestoreDirectory();
+ directory = endpoint.getConfiguration().normalizePath(directory);
+ boolean known = builtDirectories.remove(builtDirectoryKey(directory));
+ if (!known || !FtpUtils.isBodyReadableAgain(exchange.getIn().getBody())
+ || endpoint.getFileExist() == GenericFileExist.Append) {
+ return false;
}
try {
- changeCurrentDirectory(directory);
- } catch (GenericFileOperationFailedException e) {
- LOG.debug("Cannot change back to directory: {} after a failed
operation due to: {}", directory, e.getMessage(),
- e);
+ channel.stat(quotePathForJsch(directory));
+ return false;
+ } catch (SftpException e) {
+ if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE) {
+ return true;
+ }
+ throw operationFailed("Cannot get the attributes of: " +
directory, e);
+ }
+ }
+
+ /**
+ * Changes into the directory of a file for a stepwise upload or download,
as some servers cannot use a path in the
+ * name of the file, unless the connection is already there, and returns
the name relative to it. Without stepwise,
+ * or for a file without a path, changes back to the directory where the
operations started and returns the name.
+ */
+ private String changeToDirectoryOf(String name) {
+ String path = FileUtil.onlyPath(name);
+ if (path == null || !endpoint.getConfiguration().isStepwise()) {
+ changeBackToRestoreDirectory();
+ return name;
}
+ changeToStepwiseDirectory(path);
+ return FileUtil.stripPath(name);
}
private boolean doStoreFile(String name, String targetName, Exchange
exchange) throws GenericFileOperationFailedException {
@@ -1600,6 +1737,7 @@ public class SftpOperations
lock.lock();
ByteArrayInputStream bis = new
ByteArrayInputStream(payload.getBytes());
try {
+ leaveStepwiseDirectory();
channel.put(bis, quotePathForJsch(name));
return true;
} catch (SftpException e) {
@@ -1615,6 +1753,7 @@ public class SftpOperations
lock.lock();
try {
LOG.trace("existsFile({})", name);
+ leaveStepwiseDirectory();
if (endpoint.isFastExistsCheck()) {
return fastExistsFile(name);
}
@@ -1641,6 +1780,9 @@ public class SftpOperations
try {
// normalize the name as the store does, so the file that is
checked is the one that is stored
name = endpoint.getConfiguration().normalizePath(name);
+ // the read lock of the consumer checks a file by its name
relative to the starting directory, after the
+ // download of the previous file left the connection in the
directory of that file
+ leaveStepwiseDirectory();
SftpATTRS attrs;
try {
attrs = lstat(name);
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerPreWriteCheckTest.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerPreWriteCheckTest.java
index 726e0980311f..4c8c60f02870 100644
---
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerPreWriteCheckTest.java
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/RemoteFileProducerPreWriteCheckTest.java
@@ -26,6 +26,7 @@ import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
@@ -165,6 +166,39 @@ class RemoteFileProducerPreWriteCheckTest {
verify(operations,
never()).connect(any(RemoteFileConfiguration.class), any(Exchange.class));
}
+ /**
+ * Test that the noop before an upload is skipped when the connection
completed a command a moment ago, such as the
+ * previous upload (CAMEL-26657): it would not tell more about whether the
connection works.
+ */
+ @Test
+ void testRecentlyUsedConnectionSkipsNoop() throws Exception {
+ when(configuration.isSendNoop()).thenReturn(true);
+ simulateLoggedIn();
+ when(operations.isRecentlyUsed()).thenReturn(true);
+
+ producer.preWriteCheck(exchange);
+
+ verify(operations, never()).sendNoop();
+ verify(operations,
never()).connect(any(RemoteFileConfiguration.class), any(Exchange.class));
+ }
+
+ /**
+ * Test that the health check sends a noop also when the connection was
used a moment ago: it must find out whether
+ * the server still answers (CAMEL-26657).
+ */
+ @Test
+ void testHealthCheckSendsNoopOnRecentlyUsedConnection() throws Exception {
+ when(configuration.isSendNoop()).thenReturn(true);
+ simulateLoggedIn();
+ // the health check does not ask, so the stub may be unused
+ lenient().when(operations.isRecentlyUsed()).thenReturn(true);
+ when(operations.sendNoop()).thenReturn(true);
+
+ producer.doPreWriteCheck(exchange, true);
+
+ verify(operations, times(1)).sendNoop();
+ }
+
/**
* Test that when not logged in, reconnection is attempted regardless of
noop.
*/
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerSendNoopFalseIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerSendNoopFalseIT.java
index 7403476167bb..90b60716465c 100644
---
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerSendNoopFalseIT.java
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpConsumerSendNoopFalseIT.java
@@ -52,7 +52,7 @@ public class FtpConsumerSendNoopFalseIT extends
BaseServerTestSupport {
private final AtomicInteger noops = new AtomicInteger();
private final AtomicInteger logins = new AtomicInteger();
private final AtomicInteger retrieves = new AtomicInteger();
- private final AtomicInteger pwds = new AtomicInteger();
+ private final AtomicInteger lists = new AtomicInteger();
// a poll strategy that does not disconnect when a poll fails, unlike the
default one of the ftp consumer
@BindToRegistry("myPollStrategy")
@@ -74,8 +74,8 @@ public class FtpConsumerSendNoopFalseIT extends
BaseServerTestSupport {
logins.incrementAndGet();
} else if ("RETR".equalsIgnoreCase(request.getCommand())) {
retrieves.incrementAndGet();
- } else if ("PWD".equalsIgnoreCase(request.getCommand())) {
- pwds.incrementAndGet();
+ } else if ("LIST".equalsIgnoreCase(request.getCommand())) {
+ lists.incrementAndGet();
}
return super.beforeCommand(session, request);
}
@@ -164,9 +164,9 @@ public class FtpConsumerSendNoopFalseIT extends
BaseServerTestSupport {
MockEndpoint.assertIsSatisfied(context);
Awaitility.await().atMost(5, TimeUnit.SECONDS)
.until(() ->
!service.ftpFile("pollstrategy/hello.txt").toFile().exists());
- // and the consumer has polled again, as each poll starts with a PWD
command (stepwise=true)
- int pwdsAfterDelete = pwds.get();
- Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> pwds.get()
> pwdsAfterDelete + 1);
+ // and the consumer has polled again, as each poll lists the directory
+ int listsAfterDelete = lists.get();
+ Awaitility.await().atMost(5, TimeUnit.SECONDS).until(() -> lists.get()
> listsAfterDelete + 1);
// the server closes the connection between polls. The client does not
notice, so the first command of the next
// poll fails, and the failure is thrown out of the poll to a poll
strategy that does not disconnect
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpStepwiseCommandsIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpStepwiseCommandsIT.java
new file mode 100644
index 000000000000..cef8aa06bf1c
--- /dev/null
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/integration/FtpStepwiseCommandsIT.java
@@ -0,0 +1,374 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.integration;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.file.Files;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.GenericFileEndpoint;
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.component.file.GenericFileOperations;
+import org.apache.camel.component.file.remote.BaseServerTestSupport;
+import org.apache.camel.component.file.remote.FtpEndpoint;
+import org.apache.camel.component.file.remote.FtpOperations;
+import org.apache.camel.component.file.strategy.FileMoveExistingStrategy;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.stream.ByteArrayInputStreamCache;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.infra.ftp.services.embedded.EmbeddedConfiguration;
+import org.apache.camel.test.infra.ftp.services.embedded.FtpEmbeddedService;
+import org.apache.camel.util.FileUtil;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.ftpserver.FtpServerFactory;
+import org.apache.ftpserver.ftplet.DefaultFtpReply;
+import org.apache.ftpserver.ftplet.DefaultFtplet;
+import org.apache.ftpserver.ftplet.FtpException;
+import org.apache.ftpserver.ftplet.FtpRequest;
+import org.apache.ftpserver.ftplet.FtpSession;
+import org.apache.ftpserver.ftplet.FtpletResult;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.awaitility.Awaitility.await;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With the default stepwise and autoCreate, an upload does not ask for the
current directory, nor check that the
+ * directory exists, for each file (CAMEL-26657). It still changes into the
directory of its file each time: a server
+ * such as vsftpd keeps the directory itself, not its path, so a connection
that stayed in a directory that was renamed
+ * since would store the file in the renamed directory.
+ */
+public class FtpStepwiseCommandsIT extends BaseServerTestSupport {
+
+ // the server refuses to store a file of this name, in a directory that
exists
+ private static final String REFUSED = "refused.txt";
+
+ // by command, such as CWD
+ private final Map<String, AtomicInteger> commands = new
ConcurrentHashMap<>();
+ // the commands that change or use a directory, with their argument, such
as "CWD out", in the order received
+ private final List<String> sequence = new CopyOnWriteArrayList<>();
+
+ @RegisterExtension
+ public FtpEmbeddedService service = new FtpEmbeddedService() {
+ @Override
+ protected FtpServerFactory
createFtpServerFactory(EmbeddedConfiguration embeddedConfiguration) {
+ FtpServerFactory factory =
super.createFtpServerFactory(embeddedConfiguration);
+ factory.setFtplets(Map.of("counter", new DefaultFtplet() {
+ @Override
+ public FtpletResult beforeCommand(FtpSession session,
FtpRequest request)
+ throws FtpException, IOException {
+ String command = request.getCommand().toUpperCase();
+ commands.computeIfAbsent(command, k -> new
AtomicInteger()).incrementAndGet();
+ if (List.of("CWD", "PWD", "MKD", "STOR", "DELE", "RNFR",
"RNTO").contains(command)) {
+ sequence.add(request.hasArgument() ? command + " " +
request.getArgument() : command);
+ }
+ if ("STOR".equalsIgnoreCase(request.getCommand()) &&
REFUSED.equals(request.getArgument())) {
+ session.write(new DefaultFtpReply(550, "Refused"));
+ return FtpletResult.SKIP;
+ }
+ return super.beforeCommand(session, request);
+ }
+ }));
+ return factory;
+ }
+ };
+
+ private String ftpUri(String directory) {
+ return "ftp://admin@localhost:{{ftp.server.port}}/" + directory +
"?password=admin";
+ }
+
+ private int count(String command) {
+ AtomicInteger count = commands.get(command);
+ return count != null ? count.get() : 0;
+ }
+
+ @Test
+ public void
uploadsIntoTheSameDirectoryChangeIntoItWithoutAskingOrChecking() throws
Exception {
+ String uri = ftpUri("p1/out");
+ // connects, creates the directory and changes into it
+ template.sendBodyAndHeader(uri, "warm-up", Exchange.FILE_NAME,
"warm-up.txt");
+
+ commands.clear();
+ sequence.clear();
+ for (int i = 0; i < 10; i++) {
+ template.sendBodyAndHeader(uri, "message " + i,
Exchange.FILE_NAME, "file-" + i + ".txt");
+ }
+
+ // per file: back to the starting directory, stepwise into the
directory of the file, and a data connection and
+ // a STOR. No PWD, and no check that the directory exists. The NOOP
that the producer skips within a second of
+ // the previous upload is not counted here, as it depends on time:
RemoteFileProducerPreWriteCheckTest checks it
+ for (int i = 0; i < 10; i++) {
+ assertEquals(List.of("CWD /", "CWD p1", "CWD out", "STOR file-" +
i + ".txt"),
+ sequence.subList(i * 4, i * 4 + 4), "sequence: " +
sequence);
+ }
+ assertEquals(40, sequence.size(), "sequence: " + sequence);
+ assertEquals(0, count("CDUP"), "commands: " + commands);
+ for (int i = 0; i < 10; i++) {
+ assertEquals("message " + i,
Files.readString(service.ftpFile("p1/out/file-" + i + ".txt")));
+ }
+ }
+
+ @Test
+ public void directoryRemovedBetweenUploadsIsCreatedAgain() throws
Exception {
+ String uri = ftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ // removed by someone else while the connection stays in it
+ FileUtil.removeDir(service.ftpFile("p1").toFile());
+ commands.clear();
+
+ template.sendBodyAndHeader(uri, "second", Exchange.FILE_NAME,
"second.txt");
+
+ assertEquals("second",
Files.readString(service.ftpFile("p1/out/second.txt")));
+ // the change into the remembered directory failed, so the directory
was created again and the upload tried
+ // once more
+ assertEquals(1, count("STOR"), "commands: " + commands);
+ assertTrue(count("MKD") >= 1, "commands: " + commands);
+ }
+
+ @Test
+ public void directoryRenamedBetweenUploadsIsNotUsed() throws Exception {
+ String uri = ftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ // the receiving side hands the directory off and starts a new one,
while the connection stays in it
+ Files.move(service.ftpFile("p1/out"), service.ftpFile("p1/out.1"));
+ Files.createDirectories(service.ftpFile("p1/out"));
+ sequence.clear();
+
+ template.sendBodyAndHeader(uri, "second", Exchange.FILE_NAME,
"second.txt");
+
+ assertEquals("second",
Files.readString(service.ftpFile("p1/out/second.txt")));
+ assertFalse(Files.exists(service.ftpFile("p1/out.1/second.txt")));
+ // the embedded server resolves STOR against the path of its current
directory, so it would store the file in
+ // the new directory without the change of directory: what keeps a
server that holds the directory itself
+ // (vsftpd) from using the renamed one is that the upload changes into
the path again
+ assertEquals(List.of("CWD /", "CWD p1", "CWD out", "STOR second.txt"),
sequence);
+ }
+
+ @Test
+ public void streamCacheBodyIsUploadedAgainIntoARemovedDirectory() throws
Exception {
+ String uri = ftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ FileUtil.removeDir(service.ftpFile("p1").toFile());
+ commands.clear();
+
+ // a stream body reaches the producer as a stream cache with the
default stream caching: it is read again
+ // from the start
+ template.sendBodyAndHeader(uri, new ByteArrayInputStreamCache(new
ByteArrayInputStream("second".getBytes())),
+ Exchange.FILE_NAME, "second.txt");
+
+ assertEquals("second",
Files.readString(service.ftpFile("p1/out/second.txt")));
+ assertTrue(count("MKD") >= 1, "commands: " + commands);
+ }
+
+ @Test
+ public void refusedUploadIntoAnExistingDirectoryIsNotTriedAgain() throws
Exception {
+ String uri = ftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+ commands.clear();
+
+ // the directory exists, so the refusal has another cause: the file is
not uploaded twice
+ assertThrows(CamelExecutionException.class,
+ () -> template.sendBodyAndHeader(uri, "refused",
Exchange.FILE_NAME, REFUSED));
+ assertEquals(1, count("STOR"), "commands: " + commands);
+ assertEquals(0, count("MKD"), "commands: " + commands);
+
+ template.sendBodyAndHeader(uri, "next", Exchange.FILE_NAME,
"next.txt");
+ assertEquals("next",
Files.readString(service.ftpFile("p1/out/next.txt")));
+ }
+
+ @Test
+ public void readerBodyIsNotUploadedAgainIntoARemovedDirectory() throws
Exception {
+ String uri = ftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ FileUtil.removeDir(service.ftpFile("p1").toFile());
+ commands.clear();
+
+ // a failed upload may have read the reader (which is not an
InputStream), so a second upload could store a part
+ // of it
+ StringReader stream = new StringReader("second");
+ assertThrows(CamelExecutionException.class,
+ () -> template.sendBodyAndHeader(uri, stream,
Exchange.FILE_NAME, "second.txt"));
+ assertEquals(0, count("STOR"), "commands: " + commands);
+ assertEquals(0, count("MKD"), "commands: " + commands);
+
+ // the next upload checks the directory again
+ template.sendBodyAndHeader(uri, "third", Exchange.FILE_NAME,
"third.txt");
+ assertEquals("third",
Files.readString(service.ftpFile("p1/out/third.txt")));
+ }
+
+ @Test
+ public void consumerMovesIntoARemovedDirectoryAgain() throws Exception {
+ Files.createDirectories(service.ftpFile("inbox"));
+ Files.writeString(service.ftpFile("inbox/1.txt"), "1");
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceived("1");
+
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ from(ftpUri("inbox") + "&move=.done&initialDelay=0&delay=100")
+ .convertBodyTo(String.class)
+ .to("mock:result");
+ }
+ });
+ MockEndpoint.assertIsSatisfied(context);
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
Files.exists(service.ftpFile("inbox/.done/1.txt")));
+
+ // removed by someone else while the consumer stays connected: only an
upload remembers a directory, so the
+ // move of the next file checks the directory and creates it again
+ FileUtil.removeDir(service.ftpFile("inbox/.done").toFile());
+ mock.reset();
+ mock.expectedBodiesReceived("2");
+ Files.writeString(service.ftpFile("inbox/2.txt"), "2");
+
+ MockEndpoint.assertIsSatisfied(context);
+ await().atMost(10, TimeUnit.SECONDS).until(() ->
Files.exists(service.ftpFile("inbox/.done/2.txt")));
+ assertFalse(Files.exists(service.ftpFile("inbox/2.txt")));
+ }
+
+ @Test
+ public void
uploadsIntoAnotherDirectoryAndWithoutPathUseTheStartDirectory() throws
Exception {
+ String uri = ftpUri("base");
+ template.sendBodyAndHeader(uri, "1", Exchange.FILE_NAME, "a/1.txt");
+ template.sendBodyAndHeader(uri, "2", Exchange.FILE_NAME, "b/2.txt");
+ template.sendBodyAndHeader(uri, "3", Exchange.FILE_NAME, "a/3.txt");
+ template.sendBodyAndHeader(uri, "x", Exchange.FILE_NAME, "x.txt");
+
+ // each name is relative to the directory of the endpoint, whichever
directory the previous upload left the
+ // connection in
+ assertEquals("1", Files.readString(service.ftpFile("base/a/1.txt")));
+ assertEquals("2", Files.readString(service.ftpFile("base/b/2.txt")));
+ assertEquals("3", Files.readString(service.ftpFile("base/a/3.txt")));
+ assertEquals("x", Files.readString(service.ftpFile("base/x.txt")));
+ assertFalse(Files.exists(service.ftpFile("base/b/a")));
+ assertFalse(Files.exists(service.ftpFile("base/a/x.txt")));
+ }
+
+ @Test
+ public void
uploadAfterAChangeOfDirectoryThatFailedHalfWayUsesTheStartDirectory() throws
Exception {
+ Files.createDirectories(service.ftpFile("p1"));
+ Files.createDirectories(service.ftpFile("p2"));
+ // the operations themselves, as the producer disconnects after a
failed upload
+ FtpOperations operations = connect(ftpUri("") + "&autoCreate=false");
+ try {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getIn().setBody("content");
+
+ // the change into p1 succeeds, the change into missing fails
+ assertThrows(GenericFileOperationFailedException.class,
+ () -> operations.storeFile("p1/missing/a.txt", exchange,
-1));
+ assertTrue(operations.storeFile("p2/b.txt", exchange, -1));
+ } finally {
+ operations.disconnect();
+ }
+
+ assertEquals("content", Files.readString(service.ftpFile("p2/b.txt")));
+ assertFalse(Files.exists(service.ftpFile("p1/p2")));
+ }
+
+ @Test
+ public void operationsAfterAStepwiseUploadUseTheStartDirectory() throws
Exception {
+ Files.createDirectories(service.ftpFile("p1/out"));
+ FtpOperations operations = connect(ftpUri(""));
+ try {
+ String start = operations.getCurrentDirectory();
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getIn().setBody("content");
+
+ assertTrue(operations.storeFile("p1/out/a.txt", exchange, -1));
+
+ // the upload left the connection in the directory of the file:
the existence check, and the client that
+ // code outside the operations uses with names relative to the
start directory, change back first
+ assertTrue(operations.existsFile("p1/out/a.txt"));
+ assertTrue(operations.storeFile("p1/out/b.txt", exchange, -1));
+ assertEquals(start,
operations.getClient().printWorkingDirectory());
+ } finally {
+ operations.disconnect();
+ }
+ }
+
+ @Test
+ public void autoCreateRemembersOnlyTheMostRecentDirectories() throws
Exception {
+ String uri = ftpUri("base");
+ // more directories than the operations remember, each checked or
created once
+ for (int i = 0; i <= 100; i++) {
+ template.sendBodyAndHeader(uri, "x", Exchange.FILE_NAME, "d" + i +
"/x.txt");
+ }
+ sequence.clear();
+
+ // the first one was forgotten, so it is checked again; the last one
is still known
+ template.sendBodyAndHeader(uri, "y", Exchange.FILE_NAME, "d0/y.txt");
+ template.sendBodyAndHeader(uri, "y", Exchange.FILE_NAME, "d100/y.txt");
+
+ assertEquals(1, sequence.stream().filter("CWD
base/d0"::equals).count(), "sequence: " + sequence);
+ assertEquals(0, sequence.stream().filter("CWD
base/d100"::equals).count(), "sequence: " + sequence);
+ assertEquals("y", Files.readString(service.ftpFile("base/d0/y.txt")));
+ assertEquals("y",
Files.readString(service.ftpFile("base/d100/y.txt")));
+ }
+
+ @Test
+ public void
deleteFromAMoveExistingStrategyKeepsTheUploadInTheDirectoryOfTheFile() throws
Exception {
+ Files.createDirectories(service.ftpFile("p1/out"));
+ Files.writeString(service.ftpFile("p1/out/a.txt"), "old");
+ Files.writeString(service.ftpFile("p1/out/a.txt.bak"), "older");
+ // as SftpDefaultMoveExistingFileStrategy does: delete the target
through the operations, then rename
+ context.getRegistry().bind("deleteThenRename", new
FileMoveExistingStrategy() {
+ @Override
+ public boolean moveExistingFile(
+ GenericFileEndpoint<?> endpoint, GenericFileOperations<?>
operations,
+ String fileName) {
+ operations.deleteFile(fileName + ".bak");
+ return operations.renameFile(fileName, fileName + ".bak");
+ }
+ });
+
+ template.sendBodyAndHeader(ftpUri("p1/out") +
"&fileExist=Move&moveExisting=${file:name}.bak"
+ +
"&moveExistingFileStrategy=#deleteThenRename",
+ "new", Exchange.FILE_NAME, "a.txt");
+
+ // the delete and the rename use names relative to the directory of
the file, and the upload stays there
+ assertEquals("new", Files.readString(service.ftpFile("p1/out/a.txt")));
+ assertEquals("old",
Files.readString(service.ftpFile("p1/out/a.txt.bak")));
+ assertFalse(Files.exists(service.ftpFile("a.txt")));
+ }
+
+ private FtpOperations connect(String uri) throws Exception {
+ @SuppressWarnings("unchecked")
+ FtpEndpoint<FTPFile> endpoint = context.getEndpoint(uri,
FtpEndpoint.class);
+ FtpOperations operations = (FtpOperations)
endpoint.createRemoteFileOperations();
+ operations.connect(endpoint.getConfiguration(), null);
+ return operations;
+ }
+}
diff --git
a/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
new file mode 100644
index 000000000000..6b8c2273f380
--- /dev/null
+++
b/components/camel-ftp/src/test/java/org/apache/camel/component/file/remote/sftp/integration/SftpStepwiseRequestsIT.java
@@ -0,0 +1,257 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.camel.component.file.remote.sftp.integration;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.StringReader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import org.apache.camel.CamelExecutionException;
+import org.apache.camel.Exchange;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.component.file.remote.SftpEndpoint;
+import org.apache.camel.component.file.remote.SftpOperations;
+import org.apache.camel.component.mock.MockEndpoint;
+import org.apache.camel.converter.stream.ByteArrayInputStreamCache;
+import org.apache.camel.support.DefaultExchange;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.camel.util.FileUtil;
+import org.apache.sshd.sftp.common.SftpConstants;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * With the default stepwise and autoCreate, an upload or a download does not
change into the directory of its file and
+ * back, nor check that the directory exists, for each file (CAMEL-26657).
JSch checks every change of directory with
+ * two requests (REALPATH and STAT), and stepwise changes directory one path
segment at a time.
+ */
+class SftpStepwiseRequestsIT extends CamelTestSupport {
+
+ @RegisterExtension
+ SftpExistsFileIT.CountingSftpEmbeddedService service = new
SftpExistsFileIT.CountingSftpEmbeddedService();
+
+ private Path base;
+
+ @BeforeEach
+ void createTestDirectory() throws IOException {
+ // the root directory of the server is shared by the tests of this
class and kept between runs
+ base =
Files.createTempDirectory(Files.createDirectories(service.getFtpRootDir()),
"test");
+ }
+
+ @Test
+ void uploadsIntoTheSameDirectorySendOnlyTheFile() throws Exception {
+ String uri = sftpUri("p1/out");
+ // connects, creates the directory and changes into it
+ template.sendBodyAndHeader(uri, "warm-up", Exchange.FILE_NAME,
"warm-up.txt");
+
+ service.reset();
+ for (int i = 0; i < 10; i++) {
+ template.sendBodyAndHeader(uri, "message " + i,
Exchange.FILE_NAME, "file-" + i + ".txt");
+ }
+
+ // an OPEN, a WRITE and a CLOSE per file: no REALPATH and STAT to
change directory and back, and no listing or
+ // attributes to check that the directory exists
+ assertEquals(10, service.requests(SftpConstants.SSH_FXP_OPEN));
+ assertEquals(10, service.requests(SftpConstants.SSH_FXP_WRITE));
+ assertEquals(10, service.requests(SftpConstants.SSH_FXP_CLOSE));
+ assertEquals(0, service.requests(SftpConstants.SSH_FXP_REALPATH));
+ assertEquals(0, service.requests(SftpConstants.SSH_FXP_STAT));
+ assertEquals(0, service.requests(SftpConstants.SSH_FXP_LSTAT));
+ assertEquals(0, service.requests(SftpConstants.SSH_FXP_OPENDIR));
+ for (int i = 0; i < 10; i++) {
+ assertEquals("message " + i,
Files.readString(base.resolve("p1/out/file-" + i + ".txt")));
+ }
+ }
+
+ @Test
+ void directoryRemovedBetweenUploadsIsCreatedAgain() throws Exception {
+ String uri = sftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ // removed by someone else while the connection stays in it
+ FileUtil.removeDir(base.resolve("p1").toFile());
+ service.reset();
+
+ template.sendBodyAndHeader(uri, "second", Exchange.FILE_NAME,
"second.txt");
+
+ assertEquals("second",
Files.readString(base.resolve("p1/out/second.txt")));
+ // the upload into the remembered directory failed, so the directory
was created again and the upload tried
+ // once more
+ assertEquals(2, service.requests(SftpConstants.SSH_FXP_OPEN));
+ assertTrue(service.requests(SftpConstants.SSH_FXP_MKDIR) >= 1,
"requests: " + service.requests());
+ }
+
+ @Test
+ void streamCacheBodyIsUploadedAgainIntoARemovedDirectory() throws
Exception {
+ String uri = sftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ FileUtil.removeDir(base.resolve("p1").toFile());
+ service.reset();
+
+ // a stream body reaches the producer as a stream cache with the
default stream caching: it is read again
+ // from the start
+ template.sendBodyAndHeader(uri, new ByteArrayInputStreamCache(new
ByteArrayInputStream("second".getBytes())),
+ Exchange.FILE_NAME, "second.txt");
+
+ assertEquals("second",
Files.readString(base.resolve("p1/out/second.txt")));
+ assertTrue(service.requests(SftpConstants.SSH_FXP_MKDIR) >= 1,
"requests: " + service.requests());
+ }
+
+ @Test
+ void autoCreateRemembersOnlyTheMostRecentDirectories() throws Exception {
+ // without stepwise, an upload into a remembered directory sends no
request to change or check a directory
+ String uri = sftpUri("") + "&stepwise=false";
+ // more directories than the operations remember, each checked or
created once
+ for (int i = 0; i <= 100; i++) {
+ template.sendBodyAndHeader(uri, "x", Exchange.FILE_NAME, "d" + i +
"/x.txt");
+ }
+
+ service.reset();
+ template.sendBodyAndHeader(uri, "y", Exchange.FILE_NAME, "d100/y.txt");
+ assertEquals(0, service.requests(SftpConstants.SSH_FXP_STAT),
"requests: " + service.requests());
+
+ // the first one was forgotten, so it is checked again
+ service.reset();
+ template.sendBodyAndHeader(uri, "y", Exchange.FILE_NAME, "d0/y.txt");
+ assertTrue(service.requests(SftpConstants.SSH_FXP_STAT) >= 1,
"requests: " + service.requests());
+
+ assertEquals("y", Files.readString(base.resolve("d0/y.txt")));
+ assertEquals("y", Files.readString(base.resolve("d100/y.txt")));
+ }
+
+ @Test
+ void readerBodyIsNotUploadedAgainIntoARemovedDirectory() throws Exception {
+ String uri = sftpUri("p1/out");
+ template.sendBodyAndHeader(uri, "first", Exchange.FILE_NAME,
"first.txt");
+
+ FileUtil.removeDir(base.resolve("p1").toFile());
+ service.reset();
+
+ // the failed upload may have read the reader (which is not an
InputStream), so a second upload could store a
+ // part of it
+ StringReader stream = new StringReader("second");
+ assertThrows(CamelExecutionException.class,
+ () -> template.sendBodyAndHeader(uri, stream,
Exchange.FILE_NAME, "second.txt"));
+ assertEquals(1, service.requests(SftpConstants.SSH_FXP_OPEN));
+ assertEquals(0, service.requests(SftpConstants.SSH_FXP_MKDIR));
+
+ // the next upload checks the directory again
+ template.sendBodyAndHeader(uri, "third", Exchange.FILE_NAME,
"third.txt");
+ assertEquals("third",
Files.readString(base.resolve("p1/out/third.txt")));
+ }
+
+ @Test
+ void uploadsIntoAnotherDirectoryAndWithoutPathUseTheStartDirectory()
throws Exception {
+ String uri = sftpUri("");
+ template.sendBodyAndHeader(uri, "1", Exchange.FILE_NAME, "a/1.txt");
+ template.sendBodyAndHeader(uri, "2", Exchange.FILE_NAME, "b/2.txt");
+ template.sendBodyAndHeader(uri, "3", Exchange.FILE_NAME, "a/3.txt");
+ template.sendBodyAndHeader(uri, "x", Exchange.FILE_NAME, "x.txt");
+
+ // each name is relative to the directory of the endpoint, whichever
directory the previous upload left the
+ // connection in
+ assertEquals("1", Files.readString(base.resolve("a/1.txt")));
+ assertEquals("2", Files.readString(base.resolve("b/2.txt")));
+ assertEquals("3", Files.readString(base.resolve("a/3.txt")));
+ assertEquals("x", Files.readString(base.resolve("x.txt")));
+ assertFalse(Files.exists(base.resolve("b/a")));
+ assertFalse(Files.exists(base.resolve("a/x.txt")));
+ }
+
+ @Test
+ void uploadAfterAChangeOfDirectoryThatFailedHalfWayUsesTheStartDirectory()
throws Exception {
+ Files.createDirectories(base.resolve("p1"));
+ Files.createDirectories(base.resolve("p2"));
+ // the operations themselves, as the producer disconnects after a
failed upload
+ SftpEndpoint endpoint = context.getEndpoint(sftpUri("") +
"&autoCreate=false", SftpEndpoint.class);
+ SftpOperations operations = (SftpOperations)
endpoint.createRemoteFileOperations();
+ operations.connect(endpoint.getConfiguration(), null);
+ try {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getIn().setBody("content");
+
+ // the change into p1 succeeds, the change into missing fails
+ assertThrows(GenericFileOperationFailedException.class,
+ () -> operations.storeFile(base + "/p1/missing/a.txt",
exchange, -1));
+ assertTrue(operations.storeFile(base + "/p2/b.txt", exchange, -1));
+ } finally {
+ operations.disconnect();
+ }
+
+ assertEquals("content", Files.readString(base.resolve("p2/b.txt")));
+ assertFalse(Files.exists(base.resolve("p1/" + base)));
+ }
+
+ @Test
+ void readLockChecksEveryFileOfAPollAfterADownload() throws Exception {
+ Files.createDirectories(base.resolve("inbox"));
+ Files.writeString(base.resolve("inbox/a.txt"), "a");
+ Files.writeString(base.resolve("inbox/b.txt"), "b");
+
+ MockEndpoint mock = getMockEndpoint("mock:result");
+ mock.expectedBodiesReceivedInAnyOrder("a", "b");
+
+ context.addRoutes(new RouteBuilder() {
+ @Override
+ public void configure() {
+ // the read lock checks the second file by its name relative
to the starting directory, after the
+ // download of the first file left the connection in the inbox
directory
+ from(sftpUri("inbox") +
"&noop=true&initialDelay=0&delay=60000&readLock=changed"
+ + "&readLockCheckInterval=100&readLockTimeout=5000")
+ .convertBodyTo(String.class)
+ .to("mock:result");
+ }
+ });
+
+ MockEndpoint.assertIsSatisfied(context);
+ }
+
+ @Test
+ void operationAfterAStepwiseUploadUsesNamesRelativeToTheStartDirectory()
throws Exception {
+ Files.createDirectories(base.resolve("p1/out"));
+ SftpEndpoint endpoint = context.getEndpoint(sftpUri(""),
SftpEndpoint.class);
+ SftpOperations operations = (SftpOperations)
endpoint.createRemoteFileOperations();
+ operations.connect(endpoint.getConfiguration(), null);
+ try {
+ Exchange exchange = new DefaultExchange(context);
+ exchange.getIn().setBody("content");
+
+ assertTrue(operations.storeFile(base + "/p1/out/a.txt", exchange,
-1));
+
+ // base is a relative path: the upload left the connection in the
directory of the file, so the existence
+ // check must change back before it resolves the name, else it
would look for p1/out/<base>/p1/out/a.txt
+ assertTrue(operations.existsFile(base + "/p1/out/a.txt"));
+ } finally {
+ operations.disconnect();
+ }
+ }
+
+ private String sftpUri(String directory) {
+ return "sftp://localhost:" + service.getPort() + "/" + base + "/" +
directory
+ + "?username=admin&password=admin&knownHostsFile=" +
service.getKnownHostsFile();
+ }
+}
diff --git
a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
index 8ab48d5b6d8d..60d1ed6ed3a2 100644
--- a/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
+++ b/docs/user-manual/modules/ROOT/pages/camel-4x-upgrade-guide-4_24.adoc
@@ -506,6 +506,39 @@ the same HTTP status as before, and a body that is a
JSON-RPC error response wit
code is `-32700` (parse error) for a message that cannot be parsed, and
`-32600` (invalid request) otherwise; before,
a missing header or session id gave `-32601` and an unknown session `-32603`.
+=== camel-ftp, camel-sftp - fewer directory changes with stepwise and
autoCreate
+
+No option or default changes. With the default `stepwise=true`, an upload, a
download or (ftp) a delete no longer
+changes back to the directory it started from after each file: the connection
stays in the directory of the file, so the
+next download or delete in that directory needs no change of directory. The
connection changes back before an operation
+that uses names relative to the starting directory, such as a rename, a
listing, an existence check, a read lock check,
+a site command, (sftp) a delete, or an upload or download into another
directory. An ftp upload changes back and into
+the directory of its file each time, as some servers (such as vsftpd) keep the
directory itself rather than its path,
+and would store the file in a directory that was renamed or replaced since.
The ftp component asks for the current
+directory only when the connection does not know it, usually once per
connection, instead of sending `PWD` for each
+file.
+
+With the default `autoCreate=true`, the producer no longer checks that a
directory exists before each upload into a
+directory where it already stored a file on the same connection; it remembers
the 100 most recently used directories
+per connection. When such a directory is removed while the connection is open,
the first attempt to upload into it
+fails; the producer then creates the directory again and uploads the file once
more, and logs this at INFO level. It
+does not try again when the message body is a stream (other than a stream
cache, which is the default for streams with
+stream caching enabled) or a reader, or with `fileExist=Append`: that upload
fails, and the next one checks the
+directory. The directories that a consumer moves files into (`move`,
`preMove`, `moveFailed`) are still checked each
+time.
+
+With the default `sendNoop=true`, the ftp producer no longer sends a `NOOP`
before an upload when the server completed
+an upload, a download or a `NOOP` on that connection less than a second
before. A connection that the server closed
+within that second is then found by the upload, which fails, instead of by the
`NOOP`, after which the producer would
+have connected again; the next upload connects again. The consumer still sends
a `NOOP` before each poll, and the
+health check before each check.
+
+The absolute paths that the SFTP server sees do not change. The FTP server
sees fewer `CWD` and `PWD` commands, and its
+current directory between two uploads is the directory of the last file, not
the starting directory. `FtpOperations`
+`getClient()` changes back to the starting directory before it returns the
client; code that keeps the `FTPClient` (for
+example the one set with the `ftpClient` option) and sends commands with
relative names between two operations of Camel
+must change directory itself.
+
=== camel-ai-resource - fixed resourceUri cannot contain braces
Starting in Camel 4.24, `ai-resource` rejects a fixed `resourceUri` containing
`{` or `}` at route startup. The MCP SDK interprets those characters as
URI-template expressions. Routes that intend variable path segments must use
`uriTemplate` instead, for example
`+ai-resource:customer?uriTemplate=camel:///customers/{id}+`. If the braces are
literal URI characters, percent-encode them as `%7B` and `%7D`.