private void testGWPropagatesSocketCloseGuts(final int port, AbstractClientConnectionFactory ccf)
      throws Exception {
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final AtomicReference<String> lastReceived = new AtomicReference<String>();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor()
        .execute(
            new Runnable() {

              public void run() {
                try {
                  ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                  latch.countDown();
                  int i = 0;
                  while (!done.get()) {
                    Socket socket = server.accept();
                    i++;
                    while (!socket.isClosed()) {
                      try {
                        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                        String request = (String) ois.readObject();
                        logger.debug("Read " + request + " closing socket");
                        socket.close();
                        lastReceived.set(request);
                        serverLatch.countDown();
                      } catch (IOException e) {
                        socket.close();
                      }
                    }
                  }
                } catch (Exception e) {
                  if (!done.get()) {
                    e.printStackTrace();
                  }
                }
              }
            });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));
    final TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(ccf);
    gateway.setRequestTimeout(Integer.MAX_VALUE);
    QueueChannel replyChannel = new QueueChannel();
    gateway.setRequiresReply(true);
    gateway.setOutputChannel(replyChannel);
    gateway.setRemoteTimeout(5000);
    gateway.afterPropertiesSet();
    gateway.start();
    try {
      gateway.handleMessage(MessageBuilder.withPayload("Test").build());
      fail("expected failure");
    } catch (Exception e) {
      assertTrue(e.getCause() instanceof EOFException);
    }
    assertEquals(0, TestUtils.getPropertyValue(gateway, "pendingReplies", Map.class).size());
    Message<?> reply = replyChannel.receive(0);
    assertNull(reply);
    done.set(true);
    ccf.getConnection();
  }
  @Test
  public void testFailoverCached() throws Exception {
    final int port = SocketUtils.findAvailableServerSocket();
    final CountDownLatch latch = new CountDownLatch(1);
    final AtomicBoolean done = new AtomicBoolean();
    final CountDownLatch serverLatch = new CountDownLatch(1);

    Executors.newSingleThreadExecutor()
        .execute(
            new Runnable() {

              public void run() {
                try {
                  ServerSocket server = ServerSocketFactory.getDefault().createServerSocket(port);
                  latch.countDown();
                  while (!done.get()) {
                    Socket socket = server.accept();
                    while (!socket.isClosed()) {
                      try {
                        ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
                        String request = (String) ois.readObject();
                        logger.debug("Read " + request);
                        ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                        oos.writeObject("bar");
                        logger.debug("Replied to " + request);
                        serverLatch.countDown();
                      } catch (IOException e) {
                        logger.debug("error on write " + e.getClass().getSimpleName());
                        socket.close();
                      }
                    }
                  }
                } catch (Exception e) {
                  if (!done.get()) {
                    e.printStackTrace();
                  }
                }
              }
            });
    assertTrue(latch.await(10000, TimeUnit.MILLISECONDS));

    // Cache
    AbstractClientConnectionFactory factory1 = mock(AbstractClientConnectionFactory.class);
    TcpConnectionSupport mockConn1 = makeMockConnection();
    when(factory1.getConnection()).thenReturn(mockConn1);
    doThrow(new IOException("fail")).when(mockConn1).send(Mockito.any(Message.class));
    CachingClientConnectionFactory cachingFactory1 =
        new CachingClientConnectionFactory(factory1, 1);

    AbstractClientConnectionFactory factory2 = new TcpNetClientConnectionFactory("localhost", port);
    factory2.setSerializer(new DefaultSerializer());
    factory2.setDeserializer(new DefaultDeserializer());
    factory2.setSoTimeout(10000);
    factory2.setSingleUse(false);
    CachingClientConnectionFactory cachingFactory2 =
        new CachingClientConnectionFactory(factory2, 1);

    // Failover
    List<AbstractClientConnectionFactory> factories =
        new ArrayList<AbstractClientConnectionFactory>();
    factories.add(cachingFactory1);
    factories.add(cachingFactory2);
    FailoverClientConnectionFactory failoverFactory =
        new FailoverClientConnectionFactory(factories);
    failoverFactory.start();

    TcpOutboundGateway gateway = new TcpOutboundGateway();
    gateway.setConnectionFactory(failoverFactory);
    PollableChannel outputChannel = new QueueChannel();
    gateway.setOutputChannel(outputChannel);
    gateway.afterPropertiesSet();
    gateway.start();

    GenericMessage<String> message = new GenericMessage<String>("foo");
    gateway.handleMessage(message);
    Message<?> reply = outputChannel.receive(0);
    assertNotNull(reply);
    assertEquals("bar", reply.getPayload());
    done.set(true);
    gateway.stop();
    verify(mockConn1).send(Mockito.any(Message.class));
  }