This is an automated email from the ASF dual-hosted git repository.

Croway 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 c08ca14d0342 CAMEL-27016: camel-mina-sftp - stopping the producer does 
not wait for a hung upload once the shutdown is forced (#30177)
c08ca14d0342 is described below

commit c08ca14d0342050230a47be52453c58d501f8739
Author: Federico Mariani <[email protected]>
AuthorDate: Mon Nov 16 14:11:32 2026 +0100

    CAMEL-27016: camel-mina-sftp - stopping the producer does not wait for a 
hung upload once the shutdown is forced (#30177)
    
    * CAMEL-27016: camel-mina-sftp - stopping the producer does not wait for a 
hung upload once the shutdown is forced
    
    The same as CAMEL-27001 for camel-sftp. MinaSftpOperations runs every
    operation under one lock, and storeFile() holds it for the whole upload,
    which waits for the acknowledgement of each write up to the idle timeout
    of the MINA SSHD session (10 minutes by default). 
RemoteFileProducer.doStop()
    calls disconnectOnStop(), which MinaSftpOperations did not override: the
    default isConnected() waited for the lock without bound, so
    CamelContext.stop() did not return while an upload to a server that
    stopped answering hung, also after the shutdown timeout.
    
    MinaSftpOperations.disconnectOnStop() now waits for the lock while the
    shutdown is not forced, checking ShutdownStrategy.isForceShutdown() every
    second, and once it is forced closes the session at once without the lock:
    the SFTP channel closes and the requests that wait for an answer are
    cancelled, so the upload fails and releases the lock; then it disconnects
    as before, which stops the SSH client. A connect in progress is waited for.
    
    * CAMEL-27016: camel-mina-sftp - the stop also stops the SSH client of a 
connect that failed
    
    disconnectOnStop() called disconnect() under the lock only when connected. A
    connect that failed (a rejected password, an authentication timeout) has
    already created and started the SshClient but left no open session, so the
    stop did not stop it, and its NIO2 and timer threads stayed alive
    (CAMEL-24273). It now calls disconnect(), which is null-safe, as
    SftpOperations.disconnectOnStop() does.
    
    The javadoc and the WARN now say "the producer or the consumer" and "an 
upload
    or a download", as SftpOperations does with CAMEL-27018, which makes
    RemoteFileConsumer.doStop() call disconnectOnStop().
---
 .../file/remote/mina/MinaSftpOperations.java       |  97 ++++++-
 .../MinaSftpProducerStopAfterFailedConnectIT.java  | 102 +++++++
 .../MinaSftpProducerStopDuringHungUploadIT.java    | 301 +++++++++++++++++++++
 3 files changed, 499 insertions(+), 1 deletion(-)

diff --git 
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
 
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
index 1cd2816e263e..338d1c11afbe 100644
--- 
a/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
+++ 
b/components/camel-mina-sftp/src/main/java/org/apache/camel/component/file/remote/mina/MinaSftpOperations.java
@@ -111,11 +111,18 @@ public class MinaSftpOperations
      */
     private static final int MAX_BUFFER_SIZE = 126 * 1024 + 512; // ~126KB
 
+    // while the stop of the producer or the consumer waits for an operation 
of another thread, how often it checks
+    // whether the shutdown is forced, and then how long it waits for that 
operation to release the lock
+    private static final long DISCONNECT_ON_STOP_WAIT_MILLIS = 1000;
+
     private MinaSftpEndpoint endpoint;
     private SshClient sshClient;
-    private ClientSession session;
+    // volatile: disconnectOnStop reads it without the lock
+    private volatile ClientSession session;
     private SftpClient sftpClient;
     private final Lock lock = new ReentrantLock();
+    // whether connect, with its reconnect attempts, holds the lock
+    private volatile boolean connecting;
     /**
      * Tracks the current working directory for stepwise navigation.
      * <p/>
@@ -162,6 +169,7 @@ public class MinaSftpOperations
             if (isConnected()) {
                 return true;
             }
+            connecting = true;
 
             BlockingTask task = Tasks.foregroundTask()
                     .withBudget(Budgets.iterationBudget()
@@ -180,6 +188,7 @@ public class MinaSftpOperations
 
             return true;
         } finally {
+            connecting = false;
             lock.unlock();
         }
     }
@@ -862,6 +871,92 @@ public class MinaSftpOperations
         }
     }
 
+    /**
+     * Disconnects when the producer or the consumer stops. Another thread can 
still run an operation that holds the
+     * lock: an upload of the producer, or the poll of the consumer, which the 
stop of its scheduler interrupts, but
+     * which then changes back to the directory it started from (stepwise), on 
a server that may not answer.
+     * <p>
+     * As long as the shutdown of Camel is not forced, this method waits for 
that operation, as {@link #disconnect()}
+     * does: it can be a healthy but slow upload, when a producer cache evicts 
the producer, when an application stops a
+     * {@code ProducerTemplate}, or during a graceful shutdown, which stops 
the producers of a route whose consumer it
+     * stops right away (one that cannot be suspended) while its exchanges are 
still in flight.
+     * <p>
+     * Once the shutdown is forced, as its timeout elapsed, the operation is 
one that the shutdown gave up waiting for,
+     * such as an upload that hangs as long as the server does not answer 
(Apache MINA SSHD waits for an answer up to
+     * its idle timeout, 10 minutes by default). This method then closes the 
session without the lock, so that the
+     * operation fails and releases the lock. A connect in progress is waited 
for: the connect timeout and the reconnect
+     * attempts bound it, and its next attempt would open a new session.
+     * <p>
+     * With the lock, it disconnects also when not connected: a connect that 
failed, such as one whose password the
+     * server rejected, has already started the SSH client, whose threads 
{@link #disconnect()} releases.
+     */
+    @Override
+    public void disconnectOnStop() throws GenericFileOperationFailedException {
+        boolean locked = false;
+        boolean interrupted = false;
+        // a stop that began before the shutdown was forced (as above) is 
still waiting at that time, so check again
+        while (!locked) {
+            try {
+                locked = lock.tryLock(DISCONNECT_ON_STOP_WAIT_MILLIS, 
TimeUnit.MILLISECONDS);
+                if (!locked && !connecting && isForceShutdown()) {
+                    break;
+                }
+            } catch (InterruptedException e) {
+                // keep waiting, as lock() would: the shutdown task, which a 
shutdown cancels when it times out, is
+                // interrupted before the shutdown is forced; the interrupt is 
restored at the end
+                interrupted = true;
+            }
+        }
+        try {
+            if (locked) {
+                try {
+                    disconnect();
+                } finally {
+                    lock.unlock();
+                }
+            } else {
+                disconnectWithoutLock();
+            }
+        } finally {
+            if (interrupted) {
+                Thread.currentThread().interrupt();
+            }
+        }
+    }
+
+    private boolean isForceShutdown() {
+        return 
endpoint.getCamelContext().getShutdownStrategy().isForceShutdown();
+    }
+
+    private void disconnectWithoutLock() {
+        ClientSession current = session;
+        if (current == null || !current.isOpen()) {
+            return;
+        }
+        String server = endpoint.getConfiguration().remoteServerInformation();
+        LOG.warn("The shutdown is forced: disconnecting from {} while another 
thread still runs an operation, such as an"
+                 + " upload or a download that hangs. The operation fails.",
+                server);
+        // closes the session at once, without waiting for the server: its 
SFTP channel closes, and the requests that
+        // wait for an answer of the server fail
+        current.close(true);
+        // then stop the SSH client as disconnect() does, once the operation 
released the lock
+        try {
+            if (lock.tryLock(DISCONNECT_ON_STOP_WAIT_MILLIS, 
TimeUnit.MILLISECONDS)) {
+                try {
+                    disconnect();
+                } finally {
+                    lock.unlock();
+                }
+            } else {
+                LOG.debug("The operation of another thread still holds the 
lock after the session to {} was closed",
+                        server);
+            }
+        } catch (InterruptedException e) {
+            Thread.currentThread().interrupt();
+        }
+    }
+
     @Override
     public void forceDisconnect() throws GenericFileOperationFailedException {
         lock.lock();
diff --git 
a/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerStopAfterFailedConnectIT.java
 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerStopAfterFailedConnectIT.java
new file mode 100644
index 000000000000..72e0c0110639
--- /dev/null
+++ 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerStopAfterFailedConnectIT.java
@@ -0,0 +1,102 @@
+/*
+ * 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.mina.integration;
+
+import java.lang.reflect.Field;
+
+import org.apache.camel.Exchange;
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.component.file.remote.mina.MinaSftpEndpoint;
+import org.apache.camel.component.file.remote.mina.MinaSftpOperations;
+import org.apache.camel.component.file.remote.mina.MinaSftpProducer;
+import org.apache.camel.test.infra.ftp.services.embedded.SftpEmbeddedService;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.sshd.client.SshClient;
+import org.apache.sshd.server.auth.pubkey.PublickeyAuthenticator;
+import org.apache.sshd.server.auth.pubkey.RejectAllPublickeyAuthenticator;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIf;
+import org.junit.jupiter.api.extension.RegisterExtension;
+
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+
+/**
+ * A connect that fails, here as the server rejects the password, has already 
created and started the SSH client, but
+ * left no open session: the stop of the producer must still stop the SSH 
client, so that its NIO2 and timer threads do
+ * not stay alive (CAMEL-24273).
+ */
+@EnabledIf(value = 
"org.apache.camel.test.infra.ftp.services.embedded.SftpUtil#hasRequiredAlgorithms('src/test/resources/hostkey.pem')")
+class MinaSftpProducerStopAfterFailedConnectIT extends CamelTestSupport {
+
+    @RegisterExtension
+    PasswordCheckingSftpEmbeddedService service = new 
PasswordCheckingSftpEmbeddedService();
+
+    @Test
+    void stopAfterFailedConnectStopsSshClient() throws Exception {
+        MinaSftpEndpoint endpoint = context.getEndpoint(
+                "mina-sftp://localhost:"; + service.getPort() + 
"/{{ftp.root.dir}}/upload?username=admin&password=wrong"
+                                                        + 
"&strictHostKeyChecking=no&useUserKnownHostsFile=false"
+                                                        + 
"&maximumReconnectAttempts=0",
+                MinaSftpEndpoint.class);
+        MinaSftpOperations operations = (MinaSftpOperations) 
endpoint.createRemoteFileOperations();
+        MinaSftpProducer producer = new MinaSftpProducer(endpoint, operations);
+        producer.start();
+
+        Exchange exchange = endpoint.createExchange();
+        exchange.getIn().setBody("Hello World");
+        exchange.getIn().setHeader(Exchange.FILE_NAME, "hello.txt");
+        producer.process(exchange);
+        
assertNotNull(exchange.getException(GenericFileOperationFailedException.class),
+                "The upload should fail, as the server rejects the password, 
exception: " + exchange.getException());
+        assertFalse(operations.isConnected(), "The failed connect should leave 
no open session");
+
+        SshClient sshClient = sshClientOf(operations);
+        assertNotNull(sshClient, "The failed connect should have created the 
SSH client");
+        assertTrue(sshClient.isStarted(), "The failed connect should have 
started the SSH client");
+
+        producer.stop();
+
+        assertFalse(sshClient.isStarted(), "The stop of the producer should 
stop the SSH client");
+        assertTrue(sshClient.isClosed(), "The stop of the producer should 
close the SSH client");
+    }
+
+    private static SshClient sshClientOf(MinaSftpOperations operations) throws 
Exception {
+        Field field = MinaSftpOperations.class.getDeclaredField("sshClient");
+        field.setAccessible(true);
+        return (SshClient) field.get(operations);
+    }
+
+    /**
+     * The embedded SFTP server, which accepts only the password {@code 
admin}, and no public key (the SSH client offers
+     * the keys of the user, such as {@code ~/.ssh/id_rsa}).
+     */
+    static class PasswordCheckingSftpEmbeddedService extends 
SftpEmbeddedService {
+
+        @Override
+        public void setUpServer() throws Exception {
+            super.setUpServer();
+            sshd.setPasswordAuthenticator((username, password, session) -> 
"admin".equals(password));
+        }
+
+        @Override
+        protected PublickeyAuthenticator getPublickeyAuthenticator() {
+            return RejectAllPublickeyAuthenticator.INSTANCE;
+        }
+    }
+}
diff --git 
a/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerStopDuringHungUploadIT.java
 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerStopDuringHungUploadIT.java
new file mode 100644
index 000000000000..9ef310edb62f
--- /dev/null
+++ 
b/components/camel-mina-sftp/src/test/java/org/apache/camel/component/file/remote/mina/integration/MinaSftpProducerStopDuringHungUploadIT.java
@@ -0,0 +1,301 @@
+/*
+ * 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.mina.integration;
+
+import java.nio.file.Files;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.Future;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.TimeoutException;
+
+import org.apache.camel.CamelContext;
+import org.apache.camel.Consumer;
+import org.apache.camel.Exchange;
+import org.apache.camel.Processor;
+import org.apache.camel.Producer;
+import org.apache.camel.ProducerTemplate;
+import org.apache.camel.builder.RouteBuilder;
+import org.apache.camel.component.file.GenericFileOperationFailedException;
+import org.apache.camel.support.DefaultConsumer;
+import org.apache.camel.support.DefaultEndpoint;
+import org.apache.camel.test.infra.ftp.services.embedded.SftpEmbeddedService;
+import org.apache.camel.test.junit6.CamelTestSupport;
+import org.apache.sshd.server.session.ServerSession;
+import org.apache.sshd.sftp.server.FileHandle;
+import org.apache.sshd.sftp.server.SftpEventListener;
+import org.apache.sshd.sftp.server.SftpSubsystemFactory;
+import org.awaitility.core.ConditionTimeoutException;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledIf;
+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.assertNotNull;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * An upload that hangs, because the server stopped answering, holds the lock 
of {@code MinaSftpOperations} for as long
+ * as it hangs, in the thread of the caller, which nothing interrupts. When 
Camel stops, the shutdown strategy forces
+ * the shutdown after its timeout: the stop of the producer must then not wait 
for the upload, but disconnect, and the
+ * upload fail. Outside a forced shutdown, the stop of the producer waits for 
the upload, as before. The same as
+ * {@code SftpProducerStopDuringHungUploadIT} of camel-ftp (CAMEL-27001).
+ */
+@EnabledIf(value = 
"org.apache.camel.test.infra.ftp.services.embedded.SftpUtil#hasRequiredAlgorithms('src/test/resources/hostkey.pem')")
+class MinaSftpProducerStopDuringHungUploadIT extends CamelTestSupport {
+
+    private static final int SHUTDOWN_TIMEOUT_SECONDS = 1;
+    // the shutdown is forced after its timeout: the stop should return well 
within this limit
+    private static final int STOP_LIMIT_SECONDS = 20;
+
+    @RegisterExtension
+    HangingSftpEmbeddedService service = new HangingSftpEmbeddedService();
+
+    // threads that Camel does not manage, so that its shutdown does not 
interrupt them
+    private final ExecutorService executor = Executors.newCachedThreadPool();
+
+    @AfterEach
+    void releaseServer() {
+        service.release();
+        executor.shutdown();
+    }
+
+    /**
+     * The SFTP subsystem of the server stops answering while the SSH 
transport stays alive: the upload waits for the
+     * status of its writes.
+     */
+    @Test
+    void stopDoesNotWaitForUploadWhenServerStopsAnswering() throws Exception {
+        service.hangTransfers();
+        context.getShutdownStrategy().setTimeout(SHUTDOWN_TIMEOUT_SECONDS);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from("direct:upload").to(sftpUri());
+            }
+        });
+
+        Future<Exchange> upload = executor.submit(() -> 
template.send("direct:upload", exchange -> {
+            exchange.getIn().setBody(new byte[64 * 1024]);
+            exchange.getIn().setHeader(Exchange.FILE_NAME, "big.bin");
+        }));
+        assertTrue(service.awaitHang(), "The upload should reach the server");
+
+        assertStopReturns();
+
+        // the upload failed, it did not report success
+        Exchange exchange = upload.get(STOP_LIMIT_SECONDS, TimeUnit.SECONDS);
+        
assertNotNull(exchange.getException(GenericFileOperationFailedException.class),
+                "The hung upload should fail, exception: " + 
exchange.getException());
+    }
+
+    /**
+     * A route whose consumer is neither suspendable nor defers its shutdown 
(such as netty's): the shutdown stops it
+     * right away, and with it the processors of the route, so the producer 
stops while the upload runs, and before the
+     * shutdown is forced. Its stop disconnects once the shutdown is forced.
+     */
+    @Test
+    void stopDoesNotWaitForUploadOfRouteWhoseConsumerStopsRightAway() throws 
Exception {
+        service.hangTransfers();
+        PlainEndpoint plain = 
addUploadRouteFromPlainConsumer(SHUTDOWN_TIMEOUT_SECONDS);
+
+        Future<Exchange> upload = executor.submit(() -> plain.send(new byte[64 
* 1024]));
+        assertTrue(service.awaitHang(), "The upload should reach the server");
+
+        assertStopReturns();
+
+        Exchange exchange = upload.get(STOP_LIMIT_SECONDS, TimeUnit.SECONDS);
+        
assertNotNull(exchange.getException(GenericFileOperationFailedException.class),
+                "The hung upload should fail, exception: " + 
exchange.getException());
+    }
+
+    /**
+     * The same route, with an upload that is healthy but slow: a graceful 
shutdown waits for it up to its timeout, the
+     * stop of the producer does not disconnect under it.
+     */
+    @Test
+    void gracefulStopWaitsForUploadOfRouteWhoseConsumerStopsRightAway() throws 
Exception {
+        service.hangTransfers();
+        PlainEndpoint plain = addUploadRouteFromPlainConsumer(30);
+
+        Future<Exchange> upload = executor.submit(() -> plain.send(new byte[64 
* 1024]));
+        assertTrue(service.awaitHang(), "The upload should reach the server");
+
+        Future<?> stop = executor.submit(context::stop);
+        // the upload completes, the exchange can still be cut off afterwards, 
as the shutdown stopped its route
+        assertStopWaitsForUploadThatThenCompletes(stop, upload);
+    }
+
+    /**
+     * A stop of the producer outside a forced shutdown, here an application 
that stops the ProducerTemplate another
+     * thread still sends with (a producer cache that evicts the producer of a 
dynamic endpoint does the same): the
+     * upload can be healthy but slow, so the stop waits for it rather than 
disconnecting under it.
+     */
+    @Test
+    void stopOutsideForcedShutdownWaitsForUpload() throws Exception {
+        service.hangTransfers();
+        ProducerTemplate producerTemplate = context.createProducerTemplate();
+
+        Future<Exchange> upload = executor.submit(() -> 
producerTemplate.send(sftpUri(), exchange -> {
+            exchange.getIn().setBody(new byte[64 * 1024]);
+            exchange.getIn().setHeader(Exchange.FILE_NAME, "big.bin");
+        }));
+        assertTrue(service.awaitHang(), "The upload should reach the server");
+
+        Future<?> stop = executor.submit(producerTemplate::stop);
+        Exchange exchange = assertStopWaitsForUploadThatThenCompletes(stop, 
upload);
+        assertNull(exchange.getException(), "The exchange should complete");
+    }
+
+    private Exchange assertStopWaitsForUploadThatThenCompletes(Future<?> stop, 
Future<Exchange> upload) throws Exception {
+        // well after the 1 s after which the stop disconnects in a forced 
shutdown
+        try {
+            await().atMost(5, TimeUnit.SECONDS).during(3, TimeUnit.SECONDS)
+                    .until(() -> !stop.isDone() && !upload.isDone());
+        } catch (ConditionTimeoutException e) {
+            fail("The stop should wait for the upload, the stop returned: " + 
stop.isDone() + ", the upload ended: "
+                 + upload.isDone(),
+                    e);
+        }
+
+        // the server answers again: the upload completes, then the stop
+        service.release();
+        Exchange exchange = upload.get(STOP_LIMIT_SECONDS, TimeUnit.SECONDS);
+        
assertNull(exchange.getException(GenericFileOperationFailedException.class),
+                "The upload should complete, exception: " + 
exchange.getException());
+        stop.get(STOP_LIMIT_SECONDS, TimeUnit.SECONDS);
+        assertEquals(64 * 1024, 
Files.size(service.getFtpRootDir().resolve("upload/big.bin")));
+        return exchange;
+    }
+
+    private PlainEndpoint addUploadRouteFromPlainConsumer(int 
shutdownTimeoutSeconds) throws Exception {
+        context.getShutdownStrategy().setTimeout(shutdownTimeoutSeconds);
+        PlainEndpoint plain = new PlainEndpoint(context);
+        context.addRoutes(new RouteBuilder() {
+            @Override
+            public void configure() {
+                from(plain).to(sftpUri());
+            }
+        });
+        return plain;
+    }
+
+    private String sftpUri() {
+        return "mina-sftp://localhost:"; + service.getPort() + 
"/{{ftp.root.dir}}/upload?username=admin&password=admin"
+               + "&strictHostKeyChecking=no&useUserKnownHostsFile=false";
+    }
+
+    private void assertStopReturns() throws Exception {
+        Future<?> stop = executor.submit(context::stop);
+        try {
+            stop.get(STOP_LIMIT_SECONDS, TimeUnit.SECONDS);
+        } catch (TimeoutException e) {
+            fail("CamelContext.stop() should return after the shutdown timeout 
of " + SHUTDOWN_TIMEOUT_SECONDS
+                 + " s, it still waits for the upload after " + 
STOP_LIMIT_SECONDS + " s");
+        } finally {
+            // so that a stop that waits for the upload can complete
+            service.release();
+        }
+    }
+
+    /**
+     * An endpoint whose consumer is neither suspendable nor defers its 
shutdown, such as netty's: the shutdown stops it
+     * right away, before it waits for the in-flight exchanges, and with it 
the processors of its route.
+     */
+    static class PlainEndpoint extends DefaultEndpoint {
+
+        private volatile Consumer consumer;
+
+        PlainEndpoint(CamelContext context) {
+            super("plain://upload", null);
+            setCamelContext(context);
+        }
+
+        @Override
+        public Producer createProducer() {
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        public Consumer createConsumer(Processor processor) {
+            consumer = new DefaultConsumer(this, processor);
+            return consumer;
+        }
+
+        Exchange send(Object body) throws Exception {
+            Exchange exchange = createExchange();
+            exchange.getIn().setBody(body);
+            exchange.getIn().setHeader(Exchange.FILE_NAME, "big.bin");
+            consumer.getProcessor().process(exchange);
+            return exchange;
+        }
+    }
+
+    /**
+     * The embedded SFTP server. Its SFTP subsystem can stop answering at the 
first write of file data, until
+     * {@link #release()}.
+     */
+    static class HangingSftpEmbeddedService extends SftpEmbeddedService {
+
+        private final CountDownLatch hanging = new CountDownLatch(1);
+        private final CountDownLatch released = new CountDownLatch(1);
+        private volatile boolean hangTransfers;
+
+        @Override
+        public void setUpServer() throws Exception {
+            super.setUpServer();
+            SftpSubsystemFactory factory = (SftpSubsystemFactory) 
sshd.getSubsystemFactories().get(0);
+            factory.addSftpEventListener(new SftpEventListener() {
+                @Override
+                public void writing(
+                        ServerSession session, String remoteHandle, FileHandle 
localHandle, long offset, byte[] data,
+                        int dataOffset, int dataLen) {
+                    hang();
+                }
+            });
+        }
+
+        void hangTransfers() {
+            hangTransfers = true;
+        }
+
+        private void hang() {
+            if (!hangTransfers) {
+                return;
+            }
+            hanging.countDown();
+            try {
+                released.await(60, TimeUnit.SECONDS);
+            } catch (InterruptedException e) {
+                Thread.currentThread().interrupt();
+            }
+        }
+
+        boolean awaitHang() throws InterruptedException {
+            return hanging.await(20, TimeUnit.SECONDS);
+        }
+
+        void release() {
+            released.countDown();
+        }
+    }
+}

Reply via email to