You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2015/05/19 12:15:15 UTC

[1/2] mina-sshd git commit: [SSHD-467] Close test resources as soon as possible using try-finally and try-with-resource

Repository: mina-sshd
Updated Branches:
  refs/heads/master d9ed7ab21 -> 1c51deb35


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ScpTest.java b/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
index b059aef..8b2a90a 100644
--- a/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
@@ -109,7 +109,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -151,7 +151,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -207,7 +207,7 @@ public class ScpTest extends BaseTestSupport {
 
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
                     scp.upload("target/scp/local/" + zeroLocal.getName(), "target/scp/remote/" + zeroRemote.getName());
@@ -249,7 +249,7 @@ public class ScpTest extends BaseTestSupport {
 
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
                     scp.download("target/scp/remote/" + zeroRemote.getName(), "target/scp/local/" + zeroLocal.getName());
@@ -268,7 +268,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -320,7 +320,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -384,7 +384,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -423,7 +423,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -462,7 +462,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -510,7 +510,7 @@ public class ScpTest extends BaseTestSupport {
             try {
                 try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
                     session.addPasswordIdentity("test");
-                    session.auth().verify();
+                    session.auth().verify(5L, TimeUnit.SECONDS);
 
                     ScpClient scp = createScpClient(session);
 
@@ -564,69 +564,75 @@ public class ScpTest extends BaseTestSupport {
     @Test
     public void testScp() throws Exception {
         session = getJschSession();
-
-        String data = "0123456789\n";
-
-        String unixDir = "target/scp";
-        String fileName = "out.txt";
-        String unixPath = unixDir + File.separator + fileName;
-        File root = new File(unixDir);
-        File target = new File(unixPath);
-        Utils.deleteRecursive(root);
-        root.mkdirs();
-        assertTrue(root.exists());
-
-        target.delete();
-        assertFalse(target.exists());
-        sendFile(unixPath, "out.txt", data);
-        assertFileLength(target, data.length(), 5000);
-
-        target.delete();
-        assertFalse(target.exists());
-        sendFile(unixDir, "out.txt", data);
-        assertFileLength(target, data.length(), 5000);
-
-        sendFileError("target", "scp", "0123456789\n");
-
-        readFileError(unixDir);
-
-        assertEquals(data, readFile(unixPath));
-
-        assertEquals(data, readDir(unixDir));
-
-        target.delete();
-        root.delete();
-
-        sendDir("target", "scp", "out.txt", data);
-        assertFileLength(target, data.length(), 5000);
+        try {
+            String data = "0123456789\n";
+    
+            String unixDir = "target/scp";
+            String fileName = "out.txt";
+            String unixPath = unixDir + File.separator + fileName;
+            File root = new File(unixDir);
+            File target = new File(unixPath);
+            Utils.deleteRecursive(root);
+            root.mkdirs();
+            assertTrue(root.exists());
+    
+            target.delete();
+            assertFalse(target.exists());
+            sendFile(unixPath, "out.txt", data);
+            assertFileLength(target, data.length(), 5000);
+    
+            target.delete();
+            assertFalse(target.exists());
+            sendFile(unixDir, "out.txt", data);
+            assertFileLength(target, data.length(), 5000);
+    
+            sendFileError("target", "scp", "0123456789\n");
+    
+            readFileError(unixDir);
+    
+            assertEquals(data, readFile(unixPath));
+    
+            assertEquals(data, readDir(unixDir));
+    
+            target.delete();
+            root.delete();
+    
+            sendDir("target", "scp", "out.txt", data);
+            assertFileLength(target, data.length(), 5000);
+        } finally {
+            session.disconnect();
+        }
     }
 
     @Test
     public void testWithGanymede() throws Exception {
         // begin client config
         final Connection conn = new Connection("localhost", port);
-        conn.connect(null, 5000, 0);
-        conn.authenticateWithPassword("sshd", "sshd");
-        final SCPClient scp_client = new SCPClient(conn);
-        final Properties props = new Properties();
-        props.setProperty("test", "test-passed");
-        File f = new File("target/scp/gan");
-        Utils.deleteRecursive(f);
-        f.mkdirs();
-        assertTrue(f.exists());
-
-        String name = "test.properties";
-        scp_client.put(toBytes(props, ""), name, "target/scp/gan");
-        assertTrue(new File(f, name).exists());
-        assertTrue(new File(f, name).delete());
-
-        name = "test2.properties";
-        scp_client.put(toBytes(props, ""), name, "target/scp/gan");
-        assertTrue(new File(f, name).exists());
-        assertTrue(new File(f, name).delete());
-
-        assertTrue(f.delete());
-        conn.close();
+        try {
+            conn.connect(null, 5000, 0);
+            conn.authenticateWithPassword("sshd", "sshd");
+            final SCPClient scp_client = new SCPClient(conn);
+            final Properties props = new Properties();
+            props.setProperty("test", "test-passed");
+            File f = new File("target/scp/gan");
+            Utils.deleteRecursive(f);
+            f.mkdirs();
+            assertTrue(f.exists());
+    
+            String name = "test.properties";
+            scp_client.put(toBytes(props, ""), name, "target/scp/gan");
+            assertTrue(new File(f, name).exists());
+            assertTrue(new File(f, name).delete());
+    
+            name = "test2.properties";
+            scp_client.put(toBytes(props, ""), name, "target/scp/gan");
+            assertTrue(new File(f, name).exists());
+            assertTrue(new File(f, name).delete());
+    
+            assertTrue(f.delete());
+        } finally {
+            conn.close();
+        }
     }
 
     private byte[] toBytes(final Properties properties, final String comments) {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/ServerTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ServerTest.java b/sshd-core/src/test/java/org/apache/sshd/ServerTest.java
index 6abbccc..3486b38 100644
--- a/sshd-core/src/test/java/org/apache/sshd/ServerTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/ServerTest.java
@@ -130,6 +130,8 @@ public class ServerTest extends BaseTestSupport {
                 }
             }
             assertTrue("Number trials (" + nbTrials + ") below min.=" + MAX_AUTH_REQUESTS, nbTrials > MAX_AUTH_REQUESTS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -152,13 +154,15 @@ public class ServerTest extends BaseTestSupport {
                 assertTrue(nbTrials < 100);
                 authFuture = s.getService(ClientUserAuthServiceOld.class)
                         .auth(new UserAuthPassword((ClientSessionImpl) s, "ssh-connection", "buggy"));
-                assertTrue(authFuture.await(5000));
-                assertTrue(authFuture.isDone());
-                assertFalse(authFuture.isSuccess());
+                assertTrue("Authentication wait failed", authFuture.await(5000));
+                assertTrue("Authentication not done", authFuture.isDone());
+                assertFalse("Authentication unexpectedly successful", authFuture.isSuccess());
             }
             while (authFuture.isFailure());
             assertNotNull("Missing auth future exception", authFuture.getException());
             assertTrue("Number trials (" + nbTrials + ") below min.=" + MAX_AUTH_REQUESTS, nbTrials > MAX_AUTH_REQUESTS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -172,6 +176,8 @@ public class ServerTest extends BaseTestSupport {
         try(ClientSession s = client.connect("test", "localhost", port).await().getSession()) {
             int res = s.waitFor(ClientSession.CLOSED, 2 * AUTH_TIMEOUT);
             assertEquals("Session should be closed", ClientSession.CLOSED | ClientSession.WAIT_AUTH, res);
+        } finally {
+            client.stop();
         }
     }
 
@@ -213,7 +219,10 @@ public class ServerTest extends BaseTestSupport {
                 int res = s.waitFor(ClientSession.CLOSED, 2 * IDLE_TIMEOUT);
                 assertEquals("Session should be closed", ClientSession.CLOSED | ClientSession.AUTHED, res);
             }
+        } finally {
+            client.stop();
         }
+
         assertTrue(latch.await(1, TimeUnit.SECONDS));
         assertTrue(TestEchoShellFactory.TestEchoShell.latch.await(1, TimeUnit.SECONDS));
     }
@@ -230,8 +239,9 @@ public class ServerTest extends BaseTestSupport {
         final CountDownLatch latch = new CountDownLatch(1);
 
         sshd.setCommandFactory(new StreamCommand.Factory());
-        sshd.getProperties().put(FactoryManager.IDLE_TIMEOUT, "5000");
-        sshd.getProperties().put(FactoryManager.DISCONNECT_TIMEOUT, "2000");
+        
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, 5000);
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.DISCONNECT_TIMEOUT, 2000);
         sshd.getSessionFactory().addListener(new SessionListener() {
             @Override
             public void sessionCreated(Session session) {
@@ -261,11 +271,13 @@ public class ServerTest extends BaseTestSupport {
                 // Create a pipe that will block reading when the buffer is full
                 PipedInputStream pis = new PipedInputStream();
                 PipedOutputStream pos = new PipedOutputStream(pis)) {
+
                 shell.setOut(pos);
-                shell.open().await();
+                shell.open().verify(5L, TimeUnit.SECONDS);
         
                 try(AbstractSession serverSession = sshd.getActiveSessions().iterator().next();
                     Channel channel = serverSession.getService(AbstractConnectionService.class).getChannels().iterator().next()) {
+
                     while (channel.getRemoteWindow().getSize() > 0) {
                         Thread.sleep(1);
                     }
@@ -274,11 +286,13 @@ public class ServerTest extends BaseTestSupport {
             
                     long t0 = System.currentTimeMillis();
                     latch.await(1, TimeUnit.MINUTES);
-                    long t1 = System.currentTimeMillis();
-                    assertTrue(t1 - t0 > 7000);
-                    assertTrue(t1 - t0 < 10000);
+                    long t1 = System.currentTimeMillis(), diff = t1 - t0;
+                    assertTrue("Wait time too low: " + diff, diff > 7000);
+                    assertTrue("Wait time too high: " + diff, diff < 10000);
                 }
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -302,6 +316,8 @@ public class ServerTest extends BaseTestSupport {
         client.start();
         try(ClientSession s = client.connect("test", "localhost", port).await().getSession()) {
             s.close(false);
+        } finally {
+            client.stop();
         }
     }
 
@@ -355,6 +371,8 @@ public class ServerTest extends BaseTestSupport {
             assertEquals("Mismatched client events count", 1, clientEventCount.get());
             assertEquals("Mismatched server events count", 1, serverEventCount.get());
             s.close(false);
+        } finally {
+            client.stop();
         }
     }
 

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java b/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
index 1ad515b..609d5fb 100644
--- a/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
@@ -83,93 +83,92 @@ public class SftpFileSystemTest extends BaseTestSupport {
 
         String uri = "sftp://x:x@localhost:" + port + "/";
 
-        FileSystem fs = FileSystems.newFileSystem(URI.create(uri), null);
-        Iterable<Path> rootDirs = fs.getRootDirectories();
-        for (Path root : rootDirs) {
-            try (DirectoryStream<Path> ds = Files.newDirectoryStream(root)) {
-                for (Path child : ds) {
-                    System.out.println(child);
-                }
-            } catch(IOException | RuntimeException e) {
-                // TODO on Windows one might get share problems for *.sys files
-                // e.g. "C:\hiberfil.sys: The process cannot access the file because it is being used by another process"
-                // for now, Windows is less of a target so we are lenient with it
-                if (OsUtils.isWin32()) {
-                    System.err.println(e.getClass().getSimpleName() + " while accessing children of root=" + root + ": " + e.getMessage());
-                } else {
-                    throw e;
+        try(FileSystem fs = FileSystems.newFileSystem(URI.create(uri), null)) {
+            Iterable<Path> rootDirs = fs.getRootDirectories();
+            for (Path root : rootDirs) {
+                try (DirectoryStream<Path> ds = Files.newDirectoryStream(root)) {
+                    for (Path child : ds) {
+                        System.out.println(child);
+                    }
+                } catch(IOException | RuntimeException e) {
+                    // TODO on Windows one might get share problems for *.sys files
+                    // e.g. "C:\hiberfil.sys: The process cannot access the file because it is being used by another process"
+                    // for now, Windows is less of a target so we are lenient with it
+                    if (OsUtils.isWin32()) {
+                        System.err.println(e.getClass().getSimpleName() + " while accessing children of root=" + root + ": " + e.getMessage());
+                    } else {
+                        throw e;
+                    }
                 }
             }
-        }
-
-        Path current = fs.getPath(".").toRealPath();
-        Path file = fs.getPath("target/sftp/client/test.txt");
-        Files.createDirectories(file.getParent());
-        Files.write(file, "Hello world\n".getBytes());
-        String buf = new String(Files.readAllBytes(file));
-        assertEquals("Hello world\n", buf);
-
-        Path file2 = fs.getPath("target/sftp/client/test2.txt");
-        Path file3 = fs.getPath("target/sftp/client/test3.txt");
-        try {
-            Files.move(file2, file3);
-            fail("Expected an IOException");
-        } catch (NoSuchFileException e) {
-            // expected
-        }
-        Files.write(file2, "h".getBytes());
-        try {
-            Files.move(file, file2);
-            fail("Expected an IOException");
-        } catch (FileAlreadyExistsException e) {
-            // expected
-        }
-        Files.move(file, file2, StandardCopyOption.REPLACE_EXISTING);
-        Files.move(file2, file);
-
-        Map<String, Object> attrs = Files.readAttributes(file, "*");
-        System.out.println(attrs);
-
-        // TODO: symbolic links only work for absolute files
-//        Path link = fs.getPath("target/sftp/client/test2.txt");
-//        Files.createSymbolicLink(link, link.relativize(file));
-//        assertTrue(Files.isSymbolicLink(link));
-//        assertEquals("test.txt", Files.readSymbolicLink(link).toString());
-
-        // TODO there are many issues with Windows and symbolic links - for now they are of a lesser interest
-        if (OsUtils.isUNIX()) {
-            Path link = fs.getPath("target/sftp/client/test2.txt");
-            Files.createSymbolicLink(link, link.getParent().relativize(file));
-            assertTrue("Not a symbolic link: " + link, Files.isSymbolicLink(link));
-            assertEquals("test.txt", Files.readSymbolicLink(link).toString());
-            Files.delete(link);
-        }
-
-        attrs = Files.readAttributes(file, "*", LinkOption.NOFOLLOW_LINKS);
-        System.out.println(attrs);
-
-        buf = new String(Files.readAllBytes(file));
-        assertEquals("Hello world\n", buf);
-
-        try (FileChannel channel = FileChannel.open(file)) {
-            try (FileLock lock = channel.lock()) {
-                System.out.println("Locked " + lock.toString());
-
-                try (FileChannel channel2 = FileChannel.open(file)) {
-                    try (FileLock lock2 = channel2.lock()) {
-                        System.out.println("Locked " + lock2.toString());
-                        fail("Expected an exception");
-                    } catch (OverlappingFileLockException e) {
-                        // expected
+    
+            Path current = fs.getPath(".").toRealPath();
+            Path file = fs.getPath("target/sftp/client/test.txt");
+            Files.createDirectories(file.getParent());
+            Files.write(file, "Hello world\n".getBytes());
+            String buf = new String(Files.readAllBytes(file));
+            assertEquals("Hello world\n", buf);
+    
+            Path file2 = fs.getPath("target/sftp/client/test2.txt");
+            Path file3 = fs.getPath("target/sftp/client/test3.txt");
+            try {
+                Files.move(file2, file3);
+                fail("Expected an IOException");
+            } catch (NoSuchFileException e) {
+                // expected
+            }
+            Files.write(file2, "h".getBytes());
+            try {
+                Files.move(file, file2);
+                fail("Expected an IOException");
+            } catch (FileAlreadyExistsException e) {
+                // expected
+            }
+            Files.move(file, file2, StandardCopyOption.REPLACE_EXISTING);
+            Files.move(file2, file);
+    
+            Map<String, Object> attrs = Files.readAttributes(file, "*");
+            System.out.println(attrs);
+    
+            // TODO: symbolic links only work for absolute files
+    //        Path link = fs.getPath("target/sftp/client/test2.txt");
+    //        Files.createSymbolicLink(link, link.relativize(file));
+    //        assertTrue(Files.isSymbolicLink(link));
+    //        assertEquals("test.txt", Files.readSymbolicLink(link).toString());
+    
+            // TODO there are many issues with Windows and symbolic links - for now they are of a lesser interest
+            if (OsUtils.isUNIX()) {
+                Path link = fs.getPath("target/sftp/client/test2.txt");
+                Files.createSymbolicLink(link, link.getParent().relativize(file));
+                assertTrue("Not a symbolic link: " + link, Files.isSymbolicLink(link));
+                assertEquals("test.txt", Files.readSymbolicLink(link).toString());
+                Files.delete(link);
+            }
+    
+            attrs = Files.readAttributes(file, "*", LinkOption.NOFOLLOW_LINKS);
+            System.out.println(attrs);
+    
+            buf = new String(Files.readAllBytes(file));
+            assertEquals("Hello world\n", buf);
+    
+            try (FileChannel channel = FileChannel.open(file)) {
+                try (FileLock lock = channel.lock()) {
+                    System.out.println("Locked " + lock.toString());
+    
+                    try (FileChannel channel2 = FileChannel.open(file)) {
+                        try (FileLock lock2 = channel2.lock()) {
+                            System.out.println("Locked " + lock2.toString());
+                            fail("Expected an exception");
+                        } catch (OverlappingFileLockException e) {
+                            // expected
+                        }
                     }
+    
                 }
-
             }
+    
+            Files.delete(file);
         }
-
-        Files.delete(file);
-
-        fs.close();
     }
 
     @Test
@@ -214,8 +213,6 @@ public class SftpFileSystemTest extends BaseTestSupport {
         Files.createDirectories(rootNative);
 
         FileSystem fs = FileSystems.newFileSystem(URI.create("root:" + rootNative.toUri().toString() + "!/"), null);
-
         Files.createDirectories(fs.getPath("test/foo"));
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/SftpTest.java b/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
index 7de6da4..b2b0cbd 100644
--- a/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
@@ -22,6 +22,7 @@ import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_FILE_ALREADY_EXIS
 import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_NO_SUCH_FILE;
 import static org.apache.sshd.common.sftp.SftpConstants.S_IRUSR;
 import static org.apache.sshd.common.sftp.SftpConstants.S_IWUSR;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.File;
@@ -32,6 +33,7 @@ import java.net.URI;
 import java.util.Arrays;
 import java.util.EnumSet;
 import java.util.Vector;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.client.SftpClient;
 import org.apache.sshd.common.NamedFactory;
@@ -192,68 +194,66 @@ public class SftpTest extends BaseTestSupport {
     public void testClient() throws Exception {
         SshClient client = SshClient.setUpDefaultClient();
         client.start();
-        try {
-            try (ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
-                session.addPasswordIdentity("x");
-                session.auth().verify();
+        try (ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
+            session.addPasswordIdentity("x");
+            session.auth().verify(5L, TimeUnit.SECONDS);
+    
+            Utils.deleteRecursive(new File("target/sftp"));
+            new File("target/sftp").mkdirs();
+            new File("target/sftp/client/test.txt").delete();
+            new File("target/sftp/client").delete();
+    
+            try (SftpClient sftp = session.createSftpClient()) {
+                sftp.mkdir("target/sftp/client");
         
-                Utils.deleteRecursive(new File("target/sftp"));
-                new File("target/sftp").mkdirs();
-                new File("target/sftp/client/test.txt").delete();
-                new File("target/sftp/client").delete();
+                SftpClient.Handle h = sftp.open("target/sftp/client/test.txt", EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
+                byte[] d = "0123456789\n".getBytes();
+                sftp.write(h, 0, d, 0, d.length);
+                sftp.write(h, d.length, d, 0, d.length);
         
-                try (SftpClient sftp = session.createSftpClient()) {
-                    sftp.mkdir("target/sftp/client");
-            
-                    SftpClient.Handle h = sftp.open("target/sftp/client/test.txt", EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
-                    byte[] d = "0123456789\n".getBytes();
-                    sftp.write(h, 0, d, 0, d.length);
-                    sftp.write(h, d.length, d, 0, d.length);
-            
-                    SftpClient.Attributes attrs = sftp.stat(h);
-                    assertNotNull("No handle attributes", attrs);
-            
-                    sftp.close(h);
-            
-                    h = sftp.openDir("target/sftp/client");
-                    SftpClient.DirEntry[] dir = sftp.readDir(h);
-                    assertNotNull("No dir entries", dir);
-                    assertEquals("Mismatced number of dir entries", 1, dir.length);
-                    assertNull("Unexpected entry read", sftp.readDir(h));
-                    sftp.close(h);
-            
-                    sftp.remove("target/sftp/client/test.txt");
+                SftpClient.Attributes attrs = sftp.stat(h);
+                assertNotNull("No handle attributes", attrs);
+        
+                sftp.close(h);
+        
+                h = sftp.openDir("target/sftp/client");
+                SftpClient.DirEntry[] dir = sftp.readDir(h);
+                assertNotNull("No dir entries", dir);
+                assertEquals("Mismatced number of dir entries", 1, dir.length);
+                assertNull("Unexpected entry read", sftp.readDir(h));
+                sftp.close(h);
+        
+                sftp.remove("target/sftp/client/test.txt");
 
-                    byte[] workBuf = new byte[1024 * 128];
-                    try (OutputStream os = sftp.write("target/sftp/client/test.txt")) {
-                        os.write(workBuf);
-                    }
-            
-                    try (InputStream is = sftp.read("target/sftp/client/test.txt")) {
-                        int readLen = is.read(workBuf);
-                        assertEquals("Mismatched read data length", workBuf.length, readLen);
+                byte[] workBuf = new byte[1024 * 128];
+                try (OutputStream os = sftp.write("target/sftp/client/test.txt")) {
+                    os.write(workBuf);
+                }
         
-                        int i = is.read();
-                        assertEquals("Unexpected read past EOF", -1, i);
-                    }
+                try (InputStream is = sftp.read("target/sftp/client/test.txt")) {
+                    int readLen = is.read(workBuf);
+                    assertEquals("Mismatched read data length", workBuf.length, readLen);
+    
+                    int i = is.read();
+                    assertEquals("Unexpected read past EOF", -1, i);
+                }
+    
+                SftpClient.Attributes attributes = sftp.stat("target/sftp/client/test.txt");
+                assertTrue("Test file not detected as regular", attributes.isRegularFile());
         
-                    SftpClient.Attributes attributes = sftp.stat("target/sftp/client/test.txt");
-                    assertTrue("Test file not detected as regular", attributes.isRegularFile());
-            
-                    attributes = sftp.stat("target/sftp/client");
-                    assertTrue("Test directory not reported as such", attributes.isDirectory());
-            
-                    int nb = 0;
-                    for (SftpClient.DirEntry entry : sftp.readDir("target/sftp/client")) {
-                        assertNotNull("Unexpected null entry", entry);
-                        nb++;
-                    }
-                    assertEquals("Mismatched read dir entries", 1, nb);
-            
-                    sftp.remove("target/sftp/client/test.txt");
-            
-                    sftp.rmdir("target/sftp/client/");
+                attributes = sftp.stat("target/sftp/client");
+                assertTrue("Test directory not reported as such", attributes.isDirectory());
+        
+                int nb = 0;
+                for (SftpClient.DirEntry entry : sftp.readDir("target/sftp/client")) {
+                    assertNotNull("Unexpected null entry", entry);
+                    nb++;
                 }
+                assertEquals("Mismatched read dir entries", 1, nb);
+        
+                sftp.remove("target/sftp/client/test.txt");
+        
+                sftp.rmdir("target/sftp/client/");
             }
         } finally {
             client.stop();
@@ -268,39 +268,42 @@ public class SftpTest extends BaseTestSupport {
      */
     @Test
     public void testWriteChunking() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.start();
-        ClientSession session = client.connect("x", "localhost", port).await().getSession();
-        session.addPasswordIdentity("x");
-        session.auth().verify();
-
-        Utils.deleteRecursive(new File("target/sftp"));
-        new File("target/sftp").mkdirs();
-        new File("target/sftp/client").delete();
-
-        SftpClient sftp = session.createSftpClient();
-
-        sftp.mkdir("target/sftp/client");
-
-        uploadAndVerifyFile(sftp, 0, "emptyFile.txt");
-        uploadAndVerifyFile(sftp, 1000, "smallFile.txt");
-        uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN - 1, "bufferMaxLenMinusOneFile.txt");
-        uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN, "bufferMaxLenFile.txt");
-        // were chunking not implemented, these would fail. these sizes should invoke our internal chunking mechanism
-        uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN + 1, "bufferMaxLenPlusOneFile.txt");
-        uploadAndVerifyFile(sftp, (int)(1.5 * ByteArrayBuffer.MAX_LEN), "1point5BufferMaxLenFile.txt");
-        uploadAndVerifyFile(sftp, (2 * ByteArrayBuffer.MAX_LEN) - 1, "2TimesBufferMaxLenMinusOneFile.txt");
-        uploadAndVerifyFile(sftp, 2 * ByteArrayBuffer.MAX_LEN, "2TimesBufferMaxLenFile.txt");
-        uploadAndVerifyFile(sftp, (2 * ByteArrayBuffer.MAX_LEN) + 1, "2TimesBufferMaxLenPlusOneFile.txt");
-        uploadAndVerifyFile(sftp, 200000, "largerFile.txt");
-
-        // test erroneous calls that check for negative values
-        testInvalidParams(sftp);
-
-        // cleanup
-        sftp.rmdir("target/sftp/client");
-        sftp.close();
-        client.stop();
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.start();
+            
+            try(ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
+                session.addPasswordIdentity("x");
+                session.auth().verify(5L, TimeUnit.SECONDS);
+        
+                Utils.deleteRecursive(new File("target/sftp"));
+                new File("target/sftp").mkdirs();
+                new File("target/sftp/client").delete();
+        
+                try(SftpClient sftp = session.createSftpClient()) {
+                    sftp.mkdir("target/sftp/client");
+            
+                    uploadAndVerifyFile(sftp, 0, "emptyFile.txt");
+                    uploadAndVerifyFile(sftp, 1000, "smallFile.txt");
+                    uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN - 1, "bufferMaxLenMinusOneFile.txt");
+                    uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN, "bufferMaxLenFile.txt");
+                    // were chunking not implemented, these would fail. these sizes should invoke our internal chunking mechanism
+                    uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN + 1, "bufferMaxLenPlusOneFile.txt");
+                    uploadAndVerifyFile(sftp, (int)(1.5 * ByteArrayBuffer.MAX_LEN), "1point5BufferMaxLenFile.txt");
+                    uploadAndVerifyFile(sftp, (2 * ByteArrayBuffer.MAX_LEN) - 1, "2TimesBufferMaxLenMinusOneFile.txt");
+                    uploadAndVerifyFile(sftp, 2 * ByteArrayBuffer.MAX_LEN, "2TimesBufferMaxLenFile.txt");
+                    uploadAndVerifyFile(sftp, (2 * ByteArrayBuffer.MAX_LEN) + 1, "2TimesBufferMaxLenPlusOneFile.txt");
+                    uploadAndVerifyFile(sftp, 200000, "largerFile.txt");
+            
+                    // test erroneous calls that check for negative values
+                    testInvalidParams(sftp);
+            
+                    // cleanup
+                    sftp.rmdir("target/sftp/client");
+                }
+            } finally {
+                client.stop();
+            }
+        }
     }
 
     private void testInvalidParams(SftpClient sftp) throws Exception {
@@ -401,15 +404,18 @@ public class SftpTest extends BaseTestSupport {
 
         ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
         c.connect();
-        c.put(new ByteArrayInputStream("0123456789".getBytes()), unixPath);
-
-        assertTrue("Target not created after initial write: " + target.getAbsolutePath(), target.exists());
-        assertEquals("0123456789", readFile(unixPath));
-
-        try(OutputStream os = c.put(unixPath, null, ChannelSftp.APPEND, -5)) {
-            os.write("a".getBytes());
+        try {
+            c.put(new ByteArrayInputStream("0123456789".getBytes()), unixPath);
+    
+            assertTrue("Target not created after initial write: " + target.getAbsolutePath(), target.exists());
+            assertEquals("0123456789", readFile(unixPath));
+    
+            try(OutputStream os = c.put(unixPath, null, ChannelSftp.APPEND, -5)) {
+                os.write("a".getBytes());
+            }
+        } finally {
+            c.disconnect();
         }
-        c.disconnect();
 
         assertTrue("Target not created after data update: " + target.getAbsolutePath(), target.exists());
         assertEquals("Mismatched file data", "01234a6789", readFile(unixPath));
@@ -423,14 +429,17 @@ public class SftpTest extends BaseTestSupport {
     public void testReadDir() throws Exception {
         ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
         c.connect();
-
-        URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
-        URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
-        String path = new File(base.relativize(url).getPath()).getParent() + "/";
-        path = path.replace('\\', '/');
-        Vector<?> res = c.ls(path);
-        for (Object f : res) {
-            System.out.println(f.toString());
+        try {
+            URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
+            URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
+            String path = new File(base.relativize(url).getPath()).getParent() + "/";
+            path = path.replace('\\', '/');
+            Vector<?> res = c.ls(path);
+            for (Object f : res) {
+                System.out.println(f.toString());
+            }
+        } finally {
+            c.disconnect();
         }
     }
 
@@ -439,56 +448,66 @@ public class SftpTest extends BaseTestSupport {
         ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
         c.connect();
 
-        URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
-        URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
-        String path = new File(base.relativize(url).getPath()).getParent() + "/";
-        path = path.replace('\\', '/');
-        String real = c.realpath(path);
-        System.out.println(real);
         try {
-            real = c.realpath(path + "/foobar");
+            URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
+            URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
+            String path = new File(base.relativize(url).getPath()).getParent() + "/";
+            path = path.replace('\\', '/');
+            String real = c.realpath(path);
             System.out.println(real);
-            fail("Expected SftpException");
-        } catch (SftpException e) {
-            // ok
+            try {
+                real = c.realpath(path + "/foobar");
+                System.out.println(real);
+                fail("Expected SftpException");
+            } catch (SftpException e) {
+                // ok
+            }
+        } finally {
+            c.disconnect();
         }
     }
 
     @Test
     public void testRename() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.start();
-        ClientSession session = client.connect("x", "localhost", port).await().getSession();
-        session.addPasswordIdentity("x");
-        session.auth().verify();
-
-        Utils.deleteRecursive(new File("target/sftp"));
-        new File("target/sftp").mkdirs();
-        new File("target/sftp/client").delete();
-
-        SftpClient sftp = session.createSftpClient();
-        try (OutputStream os = sftp.write("target/sftp/test.txt")) {
-            os.write("Hello world!\n".getBytes());
-        }
-
-        try {
-            sftp.rename("target/sftp/test2.txt", "target/sftp/test3.txt");
-            fail("Expected an SftpException");
-        } catch (org.apache.sshd.client.SftpException e) {
-            assertEquals(SSH_FX_NO_SUCH_FILE, e.getStatus());
-        }
-
-        try (OutputStream os = sftp.write("target/sftp/test2.txt")) {
-            os.write("H".getBytes());
-        }
-
-        try {
-            sftp.rename("target/sftp/test.txt", "target/sftp/test2.txt");
-            fail("Expected an SftpException");
-        } catch (org.apache.sshd.client.SftpException e) {
-            assertEquals(SSH_FX_FILE_ALREADY_EXISTS, e.getStatus());
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.start();
+            
+            try(ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
+                session.addPasswordIdentity("x");
+                session.auth().verify(5L, TimeUnit.SECONDS);
+        
+                Utils.deleteRecursive(new File("target/sftp"));
+                new File("target/sftp").mkdirs();
+                new File("target/sftp/client").delete();
+        
+                try(SftpClient sftp = session.createSftpClient()) {
+                    try (OutputStream os = sftp.write("target/sftp/test.txt")) {
+                        os.write("Hello world!\n".getBytes());
+                    }
+            
+                    try {
+                        sftp.rename("target/sftp/test2.txt", "target/sftp/test3.txt");
+                        fail("Expected an SftpException");
+                    } catch (org.apache.sshd.client.SftpException e) {
+                        assertEquals(SSH_FX_NO_SUCH_FILE, e.getStatus());
+                    }
+            
+                    try (OutputStream os = sftp.write("target/sftp/test2.txt")) {
+                        os.write("H".getBytes());
+                    }
+            
+                    try {
+                        sftp.rename("target/sftp/test.txt", "target/sftp/test2.txt");
+                        fail("Expected an SftpException");
+                    } catch (org.apache.sshd.client.SftpException e) {
+                        assertEquals(SSH_FX_FILE_ALREADY_EXISTS, e.getStatus());
+                    }
+                    sftp.rename("target/sftp/test.txt", "target/sftp/test2.txt", SftpClient.CopyMode.Overwrite);
+                }
+            } finally {
+                client.stop();
+            }
         }
-        sftp.rename("target/sftp/test.txt", "target/sftp/test2.txt", SftpClient.CopyMode.Overwrite);
     }
 
     @Test
@@ -509,19 +528,23 @@ public class SftpTest extends BaseTestSupport {
 
         ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
         c.connect();
-        c.put(new ByteArrayInputStream("0123456789".getBytes()), unixPath);
-
-        assertTrue(target.exists());
-        assertEquals("0123456789", readFile(unixPath));
-
-        c.symlink(unixPath, linkUnixPath);
-
-        assertTrue(link.exists());
-        assertEquals("0123456789", readFile(linkUnixPath));
-
-        String str1 = c.readlink(linkUnixPath);
-        String str2 = c.realpath(unixPath);
-        assertEquals(str1, str2);
+        try {
+            c.put(new ByteArrayInputStream("0123456789".getBytes()), unixPath);
+    
+            assertTrue(target.exists());
+            assertEquals("0123456789", readFile(unixPath));
+    
+            c.symlink(unixPath, linkUnixPath);
+    
+            assertTrue(link.exists());
+            assertEquals("0123456789", readFile(linkUnixPath));
+    
+            String str1 = c.readlink(linkUnixPath);
+            String str2 = c.realpath(unixPath);
+            assertEquals(str1, str2);
+        } finally {
+            c.disconnect();
+        }
     }
 
     protected void assertFileLength(File file, long length, long timeout) throws Exception {
@@ -546,27 +569,30 @@ public class SftpTest extends BaseTestSupport {
     protected String readFile(String path) throws Exception {
         ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
         c.connect();
-        ByteArrayOutputStream bos = new ByteArrayOutputStream();
-        InputStream is = c.get(path);
-        try {
+        
+        try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
+            InputStream is = c.get(path)) {
+
             byte[] buffer = new byte[256];
             int count;
             while (-1 != (count = is.read(buffer))) {
                 bos.write(buffer, 0, count);
             }
+
+            return bos.toString();
         } finally {
-            is.close();
+            c.disconnect();
         }
-
-        c.disconnect();
-        return new String(bos.toByteArray());
     }
 
     protected void sendFile(String path, String data) throws Exception {
         ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
         c.connect();
-        c.put(new ByteArrayInputStream(data.getBytes()), path);
-        c.disconnect();
+        try {
+            c.put(new ByteArrayInputStream(data.getBytes()), path);
+        } finally {
+            c.disconnect();
+        }
     }
 
     private String randomString(int size) {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java b/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java
index aa288a9..0474b04 100644
--- a/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java
@@ -65,6 +65,7 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport {
         });
         sshd.getProperties().put(ServerFactoryManager.AUTH_METHODS, "publickey");
         sshd.setPublickeyAuthenticator(new PublickeyAuthenticator() {
+            @SuppressWarnings("synthetic-access")
             @Override
             public boolean authenticate(String username, PublicKey key, ServerSession session) {
                 return delegate.authenticate(username, key, session);
@@ -85,6 +86,7 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport {
     public void testPublicKeyAuthWithCache() throws Exception {
         final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
         TestCachingPublicKeyAuthenticator auth = new TestCachingPublicKeyAuthenticator(new PublickeyAuthenticator() {
+            @SuppressWarnings("synthetic-access")
             @Override
             public boolean authenticate(String username, PublicKey key,
                                         ServerSession session) {
@@ -94,18 +96,25 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport {
             }
         });
         delegate = auth;
-        SshClient client = SshClient.setUpDefaultClient();
-        client.start();
-        ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-        session.addPublicKeyIdentity(pairRsaBad);
-        session.addPublicKeyIdentity(pairRsa);
-        assertTrue(session.auth().await().isSuccess());
-        assertEquals(2, count.size());
-        assertTrue(count.containsKey(KeyUtils.getFingerPrint(pairRsaBad.getPublic())));
-        assertTrue(count.containsKey(KeyUtils.getFingerPrint(pairRsa.getPublic())));
-        assertEquals(1, count.get(KeyUtils.getFingerPrint(pairRsaBad.getPublic())).get());
-        assertEquals(1, count.get(KeyUtils.getFingerPrint(pairRsa.getPublic())).get());
-        client.close(false).await();
+        
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.start();
+            
+            try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+                session.addPublicKeyIdentity(pairRsaBad);
+                session.addPublicKeyIdentity(pairRsa);
+                assertTrue(session.auth().await().isSuccess());
+                assertEquals(2, count.size());
+                assertTrue(count.containsKey(KeyUtils.getFingerPrint(pairRsaBad.getPublic())));
+                assertTrue(count.containsKey(KeyUtils.getFingerPrint(pairRsa.getPublic())));
+                assertEquals(1, count.get(KeyUtils.getFingerPrint(pairRsaBad.getPublic())).get());
+                assertEquals(1, count.get(KeyUtils.getFingerPrint(pairRsa.getPublic())).get());
+                client.close(false).await();
+            } finally {
+                client.stop();
+            }
+        }
+
         Thread.sleep(100);
         assertTrue(auth.getCache().isEmpty());
     }
@@ -114,6 +123,7 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport {
     public void testPublicKeyAuthWithoutCache() throws Exception {
         final ConcurrentHashMap<String, AtomicInteger> count = new ConcurrentHashMap<String, AtomicInteger>();
         delegate = new PublickeyAuthenticator() {
+            @SuppressWarnings("synthetic-access")
             @Override
             public boolean authenticate(String username, PublicKey key,
                                         ServerSession session) {
@@ -122,12 +132,19 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport {
                 return key.equals(pairRsa.getPublic());
             }
         };
-        SshClient client = SshClient.setUpDefaultClient();
-        client.start();
-        ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-        session.addPublicKeyIdentity(pairRsaBad);
-        session.addPublicKeyIdentity(pairRsa);
-        assertTrue(session.auth().await().isSuccess());
+        
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.start();
+            
+            try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+                session.addPublicKeyIdentity(pairRsaBad);
+                session.addPublicKeyIdentity(pairRsa);
+                assertTrue(session.auth().await().isSuccess());
+            } finally {
+                client.stop();
+            }
+        }
+
         assertEquals(2, count.size());
         assertTrue(count.containsKey(KeyUtils.getFingerPrint(pairRsaBad.getPublic())));
         assertTrue(count.containsKey(KeyUtils.getFingerPrint(pairRsa.getPublic())));
@@ -143,7 +160,4 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport {
             return cache;
         }
     }
-
-}
-
-
+}
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/SpringConfigTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/SpringConfigTest.java b/sshd-core/src/test/java/org/apache/sshd/SpringConfigTest.java
index 0c197db..cc89709 100644
--- a/sshd-core/src/test/java/org/apache/sshd/SpringConfigTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/SpringConfigTest.java
@@ -60,15 +60,20 @@ public class SpringConfigTest extends BaseTestSupport {
         com.jcraft.jsch.Session s = sch.getSession("smx", "localhost", port);
         s.setUserInfo(new SimpleUserInfo("smx"));
         s.connect();
-        Channel c = s.openChannel("shell");
-        c.connect();
-        OutputStream os = c.getOutputStream();
-        os.write("this is my command".getBytes());
-        os.flush();
-        Thread.sleep(100);
-        c.disconnect();
-        s.disconnect();
+        
+        try {
+            Channel c = s.openChannel("shell");
+            c.connect();
+        
+            try(OutputStream os = c.getOutputStream()) {
+                os.write("this is my command".getBytes());
+                os.flush();
+                Thread.sleep(100);
+            } finally {
+                c.disconnect();
+            }
+        } finally {
+            s.disconnect();
+        }
     }
-
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java b/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java
index eccd879..9c5ad46 100644
--- a/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java
@@ -18,6 +18,7 @@
  */
 package org.apache.sshd;
 
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicReference;
 
 import org.apache.sshd.client.UserInteraction;
@@ -58,22 +59,28 @@ public class WelcomeBannerTest extends BaseTestSupport {
     @Test
     public void testBanner() throws Exception {
         final AtomicReference<String> welcome = new AtomicReference<String>();
-        SshClient client = SshClient.setUpDefaultClient();
-        client.setUserInteraction(new UserInteraction() {
-            @Override
-            public void welcome(String banner) {
-                welcome.set(banner);
+        
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.setUserInteraction(new UserInteraction() {
+                @Override
+                public void welcome(String banner) {
+                    welcome.set(banner);
+                }
+                @Override
+                public String[] interactive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
+                    return null;
+                }
+            });
+            client.start();
+            
+            try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+                session.addPasswordIdentity("smx");
+                session.auth().verify(5L, TimeUnit.SECONDS);
+                assertEquals(WELCOME, welcome.get());
+                session.close(true);
+            } finally {
+                client.stop();
             }
-            @Override
-            public String[] interactive(String destination, String name, String instruction, String[] prompt, boolean[] echo) {
-                return null;
-            }
-        });
-        client.start();
-        ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-        session.addPasswordIdentity("smx");
-        session.auth().verify();
-        assertEquals(WELCOME, welcome.get());
-        session.close(true);
+        }
     }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
index 1b33f48..f71775e 100644
--- a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java
@@ -79,27 +79,34 @@ public class WindowAdjustTest {
 
     @After
     public void tearDown() throws Exception {
-        sshServer.stop();
-        sshServer.close(true);
+        if (sshServer != null) {
+            sshServer.stop();
+            sshServer.close(true);
+        }
     }
 
     @Test(timeout=60*1000L)
     public void testTrafficHeavyLoad() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.start();
-
-        final ClientSession session = client.connect("admin", "localhost", port).await().getSession();
-        session.addPasswordIdentity("admin");
-        session.auth().verify();
-
-        final ClientChannel channel = session.createShellChannel();
-
-        channel.setOut(new VerifyingOutputStream(channel, END_FILE));
-        channel.setErr(new NoCloseOutputStream(System.err));
-        channel.open();
-
-        channel.waitFor(ClientChannel.CLOSED, 0);
-        session.close(true);
+        
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.start();
+    
+            try(final ClientSession session = client.connect("admin", "localhost", port).await().getSession()) {
+                session.addPasswordIdentity("admin");
+                session.auth().verify();
+        
+                try(final ClientChannel channel = session.createShellChannel()) {
+                    channel.setOut(new VerifyingOutputStream(channel, END_FILE));
+                    channel.setErr(new NoCloseOutputStream(System.err));
+                    channel.open();
+            
+                    channel.waitFor(ClientChannel.CLOSED, 0);
+                }
+                session.close(true);
+            } finally {
+                client.stop();
+            }
+        }
     }
 
     /**

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/WindowTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/WindowTest.java b/sshd-core/src/test/java/org/apache/sshd/WindowTest.java
index f964208..d04dc1d 100644
--- a/sshd-core/src/test/java/org/apache/sshd/WindowTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/WindowTest.java
@@ -27,11 +27,13 @@ import java.io.PipedInputStream;
 import java.io.PipedOutputStream;
 import java.util.Arrays;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.client.channel.ChannelShell;
 import org.apache.sshd.client.future.OpenFuture;
 import org.apache.sshd.common.Channel;
 import org.apache.sshd.common.FactoryManager;
+import org.apache.sshd.common.FactoryManagerUtils;
 import org.apache.sshd.common.NamedFactory;
 import org.apache.sshd.common.RuntimeSshException;
 import org.apache.sshd.common.Service;
@@ -91,6 +93,7 @@ public class WindowTest extends BaseTestSupport {
                     @Override
                     public Service create(Session session) throws IOException {
                         return new ServerUserAuthService(session) {
+                            @SuppressWarnings("synthetic-access")
                             @Override
                             public void process(byte cmd, Buffer buffer) throws Exception {
                                 authLatch.await();
@@ -106,6 +109,7 @@ public class WindowTest extends BaseTestSupport {
                     @Override
                     public Channel create() {
                         return new ChannelSession() {
+                            @SuppressWarnings("synthetic-access")
                             @Override
                             public OpenFuture open(int recipient, int rwsize, int rmpsize, Buffer buffer) {
                                 try {
@@ -143,130 +147,149 @@ public class WindowTest extends BaseTestSupport {
     @Test
     public void testWindowConsumptionWithInvertedStreams() throws Exception {
         sshd.setShellFactory(new AsyncEchoShellFactory());
-        sshd.getProperties().put(FactoryManager.WINDOW_SIZE, "1024");
-        client.getProperties().put(FactoryManager.WINDOW_SIZE, "1024");
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
+        FactoryManagerUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);
         client.start();
-        ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-        session.addPasswordIdentity("smx");
-        session.auth().verify();
-        final ChannelShell channel = session.createShellChannel();
-        channel.open().verify();
-
-        final Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class)
-                .getChannels().iterator().next();
-
-        Window clientLocal = channel.getLocalWindow();
-        Window clientRemote = channel.getRemoteWindow();
-        Window serverLocal = serverChannel.getLocalWindow();
-        Window serverRemote = serverChannel.getRemoteWindow();
-
-        final String message = "0123456789";
-        final int nbMessages = 500;
-
-        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(channel.getInvertedIn()));
-        BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInvertedOut()));
-        for (int i = 0; i < nbMessages; i++) {
-            writer.write(message);
-            writer.write("\n");
-            writer.flush();
-
-            waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote");
-
-            String line = reader.readLine();
-            assertEquals(message, line);
-
-            waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
-            waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local");
+        
+        try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+            session.addPasswordIdentity("smx");
+            session.auth().verify(5L, TimeUnit.SECONDS);
+
+            try(ChannelShell channel = session.createShellChannel()) {
+                channel.open().verify(5L, TimeUnit.SECONDS);
+        
+                try(Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
+                    Window clientLocal = channel.getLocalWindow();
+                    Window clientRemote = channel.getRemoteWindow();
+                    Window serverLocal = serverChannel.getLocalWindow();
+                    Window serverRemote = serverChannel.getRemoteWindow();
+            
+                    final String message = "0123456789";
+                    final int nbMessages = 500;
+            
+                    try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(channel.getInvertedIn()));
+                        BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInvertedOut()))) {
+
+                        for (int i = 0; i < nbMessages; i++) {
+                            writer.write(message);
+                            writer.write("\n");
+                            writer.flush();
+                
+                            waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote");
+                
+                            String line = reader.readLine();
+                            assertEquals("Mismatched message at line #" + i, message, line);
+                
+                            waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
+                            waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local");
+                        }
+                    }
+                }
+            }
+        } finally {
+            client.stop();
         }
     }
 
     @Test
     public void testWindowConsumptionWithDirectStreams() throws Exception {
         sshd.setShellFactory(new AsyncEchoShellFactory());
-        sshd.getProperties().put(FactoryManager.WINDOW_SIZE, "1024");
-        client.getProperties().put(FactoryManager.WINDOW_SIZE, "1024");
-        client.start();
-        ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-        session.addPasswordIdentity("smx");
-        session.auth().verify();
-        final ChannelShell channel = session.createShellChannel();
-
-        PipedInputStream inPis = new PipedInputStream();
-        PipedOutputStream inPos = new PipedOutputStream(inPis);
-        channel.setIn(inPis);
-        PipedInputStream outPis = new PipedInputStream();
-        PipedOutputStream outPos = new PipedOutputStream(outPis);
-        channel.setOut(outPos);
-        channel.open().verify();
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
+        FactoryManagerUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);
 
-        final Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class)
-                .getChannels().iterator().next();
-
-        Window clientLocal = channel.getLocalWindow();
-        Window clientRemote = channel.getRemoteWindow();
-        Window serverLocal = serverChannel.getLocalWindow();
-        Window serverRemote = serverChannel.getRemoteWindow();
-
-        final String message = "0123456789";
-        final int nbMessages = 500;
-
-        try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(inPos));
-            BufferedReader reader = new BufferedReader(new InputStreamReader(outPis))) {
-            for (int i = 0; i < nbMessages; i++) {
-                writer.write(message);
-                writer.write("\n");
-                writer.flush();
-    
-                waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
-    
-                String line = reader.readLine();
-                assertEquals(message, line);
-    
-                waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
-                waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local");
+        client.start();
+        
+        try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+            session.addPasswordIdentity("smx");
+            session.auth().verify(5L, TimeUnit.SECONDS);
+            
+            try(ChannelShell channel = session.createShellChannel();
+                PipedInputStream inPis = new PipedInputStream();
+                PipedOutputStream inPos = new PipedOutputStream(inPis);
+                PipedInputStream outPis = new PipedInputStream();
+                PipedOutputStream outPos = new PipedOutputStream(outPis)) {
+
+                channel.setIn(inPis);
+                channel.setOut(outPos);
+                channel.open().verify();
+        
+                try(Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
+                    Window clientLocal = channel.getLocalWindow();
+                    Window clientRemote = channel.getRemoteWindow();
+                    Window serverLocal = serverChannel.getLocalWindow();
+                    Window serverRemote = serverChannel.getRemoteWindow();
+            
+                    final String message = "0123456789";
+                    final int nbMessages = 500;
+            
+                    try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(inPos));
+                        BufferedReader reader = new BufferedReader(new InputStreamReader(outPis))) {
+                        for (int i = 0; i < nbMessages; i++) {
+                            writer.write(message);
+                            writer.write("\n");
+                            writer.flush();
+                
+                            waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
+                
+                            String line = reader.readLine();
+                            assertEquals("Mismatched message at line #" + i, message, line);
+                
+                            waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
+                            waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local");
+                        }
+                    }
+                }
             }
+        } finally {
+            client.stop();
         }
     }
 
     @Test
     public void testWindowConsumptionWithAsyncStreams() throws Exception {
         sshd.setShellFactory(new AsyncEchoShellFactory());
-        sshd.getProperties().put(FactoryManager.WINDOW_SIZE, "1024");
-        client.getProperties().put(FactoryManager.WINDOW_SIZE, "1024");
-        client.start();
-        ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-        session.addPasswordIdentity("smx");
-        session.auth().verify();
-        final ChannelShell channel = session.createShellChannel();
-        channel.setStreaming(ClientChannel.Streaming.Async);
-        channel.open().verify();
-
-        final Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class)
-                .getChannels().iterator().next();
-
-        Window clientLocal = channel.getLocalWindow();
-        Window clientRemote = channel.getRemoteWindow();
-        Window serverLocal = serverChannel.getLocalWindow();
-        Window serverRemote = serverChannel.getRemoteWindow();
-
-        final String message = "0123456789";
-        final int nbMessages = 500;
-
-        for (int i = 0; i < nbMessages; i++) {
-
-            Buffer buffer = new ByteArrayBuffer((message + "\n").getBytes());
-            channel.getAsyncIn().write(buffer).verify();
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 1024);
+        FactoryManagerUtils.updateProperty(client, FactoryManager.WINDOW_SIZE, 1024);
 
-            waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote");
-
-            Buffer buf = new ByteArrayBuffer(16);
-            IoReadFuture future = channel.getAsyncOut().read(buf);
-            future.verify();
-            assertEquals(11, buf.available());
-            assertEquals(message + "\n", new String(buf.array(), buf.rpos(), buf.available()));
-
-            waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
-            waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local");
+        client.start();
+        
+        try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+            session.addPasswordIdentity("smx");
+            session.auth().verify(5L, TimeUnit.SECONDS);
+
+            try(ChannelShell channel = session.createShellChannel()) {
+                channel.setStreaming(ClientChannel.Streaming.Async);
+                channel.open().verify(5L, TimeUnit.SECONDS);
+        
+                try(Channel serverChannel = sshd.getActiveSessions().iterator().next().getService(ServerConnectionService.class).getChannels().iterator().next()) {
+                    Window clientLocal = channel.getLocalWindow();
+                    Window clientRemote = channel.getRemoteWindow();
+                    Window serverLocal = serverChannel.getLocalWindow();
+                    Window serverRemote = serverChannel.getRemoteWindow();
+            
+                    final String message = "0123456789\n";
+                    final byte[] bytes=message.getBytes();
+                    final int nbMessages = 500;
+                    for (int i = 0; i < nbMessages; i++) {
+            
+                        Buffer buffer = new ByteArrayBuffer(bytes);
+                        channel.getAsyncIn().write(buffer).verify();
+            
+                        waitForWindowNotEquals(clientLocal, serverRemote, "client local", "server remote");
+            
+                        Buffer buf = new ByteArrayBuffer(16);
+                        IoReadFuture future = channel.getAsyncOut().read(buf);
+                        future.verify();
+                        assertEquals("Mismatched available data at line #" + i, message.length(), buf.available());
+                        assertEquals("Mismatched data at line #" + i, message, new String(buf.array(), buf.rpos(), buf.available()));
+            
+                        waitForWindowEquals(clientLocal, serverRemote, "client local", "server remote");
+                        waitForWindowEquals(clientRemote, serverLocal, "client remote", "server local");
+                    }
+                }
+            }
+        } finally {
+            client.stop();
         }
     }
 
@@ -308,5 +331,4 @@ public class WindowTest extends BaseTestSupport {
             }
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java b/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
index 51d6371..c166805 100644
--- a/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/client/kex/KexTest.java
@@ -19,10 +19,12 @@
 package org.apache.sshd.client.kex;
 
 import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
 import java.io.OutputStream;
 import java.io.PipedInputStream;
 import java.io.PipedOutputStream;
 import java.util.Collections;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.ClientChannel;
 import org.apache.sshd.ClientSession;
@@ -96,49 +98,49 @@ public class KexTest extends BaseTestSupport {
     private void testClient(NamedFactory<KeyExchange> kex) throws Exception {
         System.out.println("testClient - KEX=" + kex.getName());
 
-        ByteArrayOutputStream sent = new ByteArrayOutputStream();
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        try(SshClient client = SshClient.setUpDefaultClient()) {
-            client.setKeyExchangeFactories(Collections.singletonList(kex));
-            client.start();
-            
-            try {
-                ClientSession session = client.connect("smx", "localhost", port).await().getSession();
-                session.addPasswordIdentity("smx");
-                session.auth().verify();
-                ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
-                
-                try(PipedOutputStream pipedIn = new PipedOutputStream();
-                    ByteArrayOutputStream err = new ByteArrayOutputStream();
-                    OutputStream teeOut = new TeeOutputStream(sent, pipedIn)) {
+        try(ByteArrayOutputStream sent = new ByteArrayOutputStream();
+            ByteArrayOutputStream out = new ByteArrayOutputStream()) {
 
-                    channel.setIn(new PipedInputStream(pipedIn));
-                    channel.setOut(out);
-                    channel.setErr(err);
-                    assertTrue(channel.open().await().isOpened());
-        
-                    teeOut.write("this is my command\n".getBytes());
-                    teeOut.flush();
-        
-                    StringBuilder sb = new StringBuilder();
-                    for (int i = 0; i < 10; i++) {
-                        sb.append("0123456789");
+            try(SshClient client = SshClient.setUpDefaultClient()) {
+                client.setKeyExchangeFactories(Collections.singletonList(kex));
+                client.start();
+                
+                try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
+                    session.addPasswordIdentity("smx");
+                    session.auth().verify(5L, TimeUnit.SECONDS);
+                    
+                    try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
+                        PipedOutputStream pipedIn = new PipedOutputStream();
+                        InputStream inPipe = new PipedInputStream(pipedIn);
+                        ByteArrayOutputStream err = new ByteArrayOutputStream();
+                        OutputStream teeOut = new TeeOutputStream(sent, pipedIn)) {
+    
+                        channel.setIn(inPipe);
+                        channel.setOut(out);
+                        channel.setErr(err);
+                        assertTrue("Channel not opened", channel.open().await().isOpened());
+            
+                        teeOut.write("this is my command\n".getBytes());
+                        teeOut.flush();
+            
+                        StringBuilder sb = new StringBuilder();
+                        for (int i = 0; i < 10; i++) {
+                            sb.append("0123456789");
+                        }
+                        sb.append("\n");
+                        teeOut.write(sb.toString().getBytes());
+            
+                        teeOut.write("exit\n".getBytes());
+                        teeOut.flush();
+            
+                        channel.waitFor(ClientChannel.CLOSED, 0);
                     }
-                    sb.append("\n");
-                    teeOut.write(sb.toString().getBytes());
-        
-                    teeOut.write("exit\n".getBytes());
-                    teeOut.flush();
-        
-                    channel.waitFor(ClientChannel.CLOSED, 0);
-                } finally {    
-                    channel.close(false);
+                } finally {
+                    client.stop();
                 }
-            } finally {
-                client.stop();
             }
+    
+            assertArrayEquals(kex.getName(), sent.toByteArray(), out.toByteArray());
         }
-
-        assertArrayEquals(kex.getName(), sent.toByteArray(), out.toByteArray());
     }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java
index a91bcb0..3b5e5c4 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/channel/ChannelPipedInputStreamTest.java
@@ -54,5 +54,4 @@ public class ChannelPipedInputStreamTest extends BaseTestSupport {
             }
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java b/sshd-core/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java
index 778bcde..09dd42c 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/util/EventListenerUtilsTest.java
@@ -44,7 +44,7 @@ public class EventListenerUtilsTest extends BaseTestSupport {
 
         ProxyListener listener = EventListenerUtils.proxyWrapper(ProxyListener.class, impls);
         String expStr = getCurrentTestName();
-        Number expNum = System.currentTimeMillis();
+        Number expNum = Long.valueOf(System.currentTimeMillis());
         listener.callMeWithString(expStr);
         listener.callMeWithNumber(expNum);
 

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java b/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
index 40922cc..c3046ec 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/shell/InvertedShellWrapperTest.java
@@ -33,23 +33,24 @@ public class InvertedShellWrapperTest extends BaseTestSupport {
     public void testStreamsAreFlushedBeforeClosing() throws Exception {
         BogusInvertedShell shell = newShell("out", "err");
         shell.setAlive(false);
-        ByteArrayInputStream in = new ByteArrayInputStream("in".getBytes());
-        ByteArrayOutputStream out = new ByteArrayOutputStream(50);
-        ByteArrayOutputStream err = new ByteArrayOutputStream();
-
-        InvertedShellWrapper wrapper = new InvertedShellWrapper(shell);
-        wrapper.setInputStream(in);
-        wrapper.setOutputStream(out);
-        wrapper.setErrorStream(err);
-        wrapper.setExitCallback(new BogusExitCallback());
-        wrapper.start(new BogusEnvironment());
-
-        wrapper.pumpStreams();
-
-        // check the streams were flushed before exiting
-        assertEquals("in", shell.getInputStream().toString());
-        assertEquals("out", out.toString());
-        assertEquals("err", err.toString());
+        try(ByteArrayInputStream in = new ByteArrayInputStream("in".getBytes());
+            ByteArrayOutputStream out = new ByteArrayOutputStream(50);
+            ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+            InvertedShellWrapper wrapper = new InvertedShellWrapper(shell);
+            wrapper.setInputStream(in);
+            wrapper.setOutputStream(out);
+            wrapper.setErrorStream(err);
+            wrapper.setExitCallback(new BogusExitCallback());
+            wrapper.start(new BogusEnvironment());
+    
+            wrapper.pumpStreams();
+    
+            // check the streams were flushed before exiting
+            assertEquals("in", shell.getInputStream().toString());
+            assertEquals("out", out.toString());
+            assertEquals("err", err.toString());
+        }
     }
 
     private BogusInvertedShell newShell(String contentOut, String contentErr) {
@@ -58,5 +59,4 @@ public class InvertedShellWrapperTest extends BaseTestSupport {
         ByteArrayInputStream err = new ByteArrayInputStream(contentErr.getBytes());
         return new BogusInvertedShell(in, out, err);
     }
-
 }


[2/2] mina-sshd git commit: [SSHD-467] Close test resources as soon as possible using try-finally and try-with-resource

Posted by lg...@apache.org.
[SSHD-467] Close test resources as soon as possible using try-finally and try-with-resource


Project: http://git-wip-us.apache.org/repos/asf/mina-sshd/repo
Commit: http://git-wip-us.apache.org/repos/asf/mina-sshd/commit/1c51deb3
Tree: http://git-wip-us.apache.org/repos/asf/mina-sshd/tree/1c51deb3
Diff: http://git-wip-us.apache.org/repos/asf/mina-sshd/diff/1c51deb3

Branch: refs/heads/master
Commit: 1c51deb35e8986d80f310ae175020d3ea833badb
Parents: d9ed7ab
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Tue May 19 13:15:02 2015 +0300
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Tue May 19 13:15:02 2015 +0300

----------------------------------------------------------------------
 .../java/org/apache/sshd/client/SftpClient.java |  18 +-
 .../sshd/client/sftp/SftpFileChannel.java       |   1 +
 .../common/channel/ChannelOutputStream.java     |  39 +-
 .../sshd/common/io/nio2/Nio2Acceptor.java       |   5 +-
 .../test/java/org/apache/sshd/AgentTest.java    | 154 ++++----
 .../org/apache/sshd/AuthenticationTest.java     | 139 +++----
 .../test/java/org/apache/sshd/ClientTest.java   |  38 ++
 .../test/java/org/apache/sshd/EcdsaTest.java    |   4 +
 .../java/org/apache/sshd/KeyReExchangeTest.java |  42 ++-
 .../src/test/java/org/apache/sshd/LoadTest.java |  44 +--
 .../src/test/java/org/apache/sshd/MacTest.java  |   9 +-
 .../org/apache/sshd/PortForwardingLoadTest.java | 362 ++++++++++--------
 .../org/apache/sshd/PortForwardingTest.java     | 222 ++++++-----
 .../test/java/org/apache/sshd/ProxyTest.java    |  31 +-
 .../src/test/java/org/apache/sshd/ScpTest.java  | 140 +++----
 .../test/java/org/apache/sshd/ServerTest.java   |  36 +-
 .../org/apache/sshd/SftpFileSystemTest.java     | 163 ++++-----
 .../src/test/java/org/apache/sshd/SftpTest.java | 364 ++++++++++---------
 .../apache/sshd/SinglePublicKeyAuthTest.java    |  58 +--
 .../java/org/apache/sshd/SpringConfigTest.java  |  25 +-
 .../java/org/apache/sshd/WelcomeBannerTest.java |  39 +-
 .../java/org/apache/sshd/WindowAdjustTest.java  |  41 ++-
 .../test/java/org/apache/sshd/WindowTest.java   | 240 ++++++------
 .../org/apache/sshd/client/kex/KexTest.java     |  80 ++--
 .../channel/ChannelPipedInputStreamTest.java    |   1 -
 .../common/util/EventListenerUtilsTest.java     |   2 +-
 .../server/shell/InvertedShellWrapperTest.java  |  36 +-
 27 files changed, 1314 insertions(+), 1019 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
index ce1b00e..b4282b5 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
@@ -18,6 +18,12 @@
  */
 package org.apache.sshd.client;
 
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFDIR;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFLNK;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFMT;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IFREG;
+
+import java.io.Closeable;
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
@@ -26,15 +32,10 @@ import java.util.Collection;
 import java.util.EnumSet;
 import java.util.concurrent.TimeUnit;
 
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFDIR;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFLNK;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFMT;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IFREG;
-
 /**
  * @author <a href="http://mina.apache.org">Apache MINA Project</a>
  */
-public interface SftpClient extends AutoCloseable {
+public interface SftpClient extends Closeable {
 
     enum OpenMode {
         Read,
@@ -184,11 +185,6 @@ public interface SftpClient extends AutoCloseable {
 
     int getVersion();
 
-    /**
-     * Close the client.
-     */
-    void close() throws IOException;
-
     boolean isClosing();
 
     //

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
index e599793..5f651c2 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
@@ -204,6 +204,7 @@ public class SftpFileChannel extends FileChannel {
 
     @Override
     public void force(boolean metaData) throws IOException {
+        // ignored
     }
 
     @Override

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
index 19d0bb2..fdc4215 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/channel/ChannelOutputStream.java
@@ -43,7 +43,7 @@ public class ChannelOutputStream extends OutputStream {
     private boolean closed;
     private int bufferLength;
     private int lastSize;
-    private boolean noDelay = false;
+    private boolean noDelay;
 
     public ChannelOutputStream(AbstractChannel channel, Window remoteWindow, Logger log, byte cmd) {
         this.channel = channel;
@@ -61,15 +61,18 @@ public class ChannelOutputStream extends OutputStream {
         return noDelay;
     }
 
+    @Override
     public synchronized void write(int w) throws IOException {
         b[0] = (byte) w;
         write(b, 0, 1);
     }
 
+    @Override
     public synchronized void write(byte[] buf, int s, int l) throws IOException {
         if (closed) {
-            throw new SshException("Already closed");
+            throw new SshException("write(len=" + l + ") channel already closed");
         }
+
         while (l > 0) {
             // The maximum amount we should admit without flushing again
             // is enough to make up one full packet within our allowed
@@ -107,15 +110,16 @@ public class ChannelOutputStream extends OutputStream {
     @Override
     public synchronized void flush() throws IOException {
         if (closed) {
-            throw new SshException("Already closed");
+            throw new SshException("flush(length=" + bufferLength + ") - stream is already closed");
         }
+
         try {
             while (bufferLength > 0) {
                 Buffer buf = buffer;
                 int total = bufferLength;
                 int length = Math.min(Math.min(remoteWindow.waitForSpace(), total), remoteWindow.getPacketSize());
                 int pos = buf.wpos();
-                buf.wpos(cmd == SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA ? 14 : 10);
+                buf.wpos((cmd == SshConstants.SSH_MSG_CHANNEL_EXTENDED_DATA) ? 14 : 10);
                 buf.putInt(length);
                 buf.wpos(buf.wpos() + length);
                 if (total == length) {
@@ -128,23 +132,34 @@ public class ChannelOutputStream extends OutputStream {
                 }
                 lastSize = length;
                 remoteWindow.waitAndConsume(length);
-                log.debug("Send {} on channel {}", cmd == SshConstants.SSH_MSG_CHANNEL_DATA ? "SSH_MSG_CHANNEL_DATA" : "SSH_MSG_CHANNEL_EXTENDED_DATA", channel.getId());
+                if (log.isDebugEnabled()) {
+                    log.debug("Send {} on channel {}",
+                              (cmd == SshConstants.SSH_MSG_CHANNEL_DATA) ? "SSH_MSG_CHANNEL_DATA" : "SSH_MSG_CHANNEL_EXTENDED_DATA",
+                              Integer.valueOf(channel.getId()));
+                }
                 channel.writePacket(buf);
             }
-        } catch (WindowClosedException e) {
+        } catch(WindowClosedException e) {
             closed = true;
             throw e;
-        } catch (SshException e) {
-            throw e;
-        } catch (Exception e) {
-            throw new SshException(e);
+        } catch(Exception e) {
+            if (e instanceof IOException) {
+                throw (IOException) e;
+            } else {
+                throw new SshException(e);
+            }
         }
     }
 
     @Override
     public synchronized void close() throws IOException {
-        flush();
-        closed = true;
+        if (!closed) {
+            try {
+                flush();
+            } finally {
+                closed = true;
+            }
+        }
     }
 
     private void newBuffer(int size) {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java b/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
index b38e549..29ba7cf 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/io/nio2/Nio2Acceptor.java
@@ -86,10 +86,13 @@ public class Nio2Acceptor extends Nio2Service implements IoAcceptor {
             AsynchronousServerSocketChannel channel = channels.remove(address);
             if (channel != null) {
                 try {
+                    log.trace("unbind({})", address);
                     channel.close();
                 } catch (IOException e) {
-                    log.warn("Error unbinding socket", e);
+                    log.warn("Error unbinding channel for " + address, e);
                 }
+            } else {
+                log.trace("No active channel to unbind {}", address);
             }
         }
     }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/AgentTest.java b/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
index 041ac15..9424c14 100644
--- a/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/AgentTest.java
@@ -28,6 +28,7 @@ import java.io.OutputStream;
 import java.security.KeyPair;
 import java.security.PublicKey;
 import java.util.List;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.agent.SshAgent;
 import org.apache.sshd.agent.local.LocalAgentFactory;
@@ -44,6 +45,7 @@ import org.apache.sshd.util.BogusPasswordAuthenticator;
 import org.apache.sshd.util.BogusPublickeyAuthenticator;
 import org.apache.sshd.util.EchoShellFactory;
 import org.apache.sshd.util.Utils;
+import org.junit.Assume;
 import org.junit.Test;
 
 public class AgentTest extends BaseTestSupport {
@@ -51,9 +53,7 @@ public class AgentTest extends BaseTestSupport {
     @Test
     public void testAgent() throws Exception {
         // TODO: revisit this test to work without BC
-        if (!SecurityUtils.isBouncyCastleRegistered()) {
-            return;
-        }
+        Assume.assumeTrue("BoncyCastle not registered", SecurityUtils.isBouncyCastleRegistered());
 
         try(AgentServer agent = new AgentServer()) {
             String authSocket;
@@ -89,12 +89,7 @@ public class AgentTest extends BaseTestSupport {
     @Test
     public void testAgentForwarding() throws Exception {
         // TODO: revisit this test to work without BC
-        if (!SecurityUtils.isBouncyCastleRegistered()) {
-            return;
-        }
-
-        int port1;
-        int port2;
+        Assume.assumeTrue("BoncyCastle not registered", SecurityUtils.isBouncyCastleRegistered());
 
         TestEchoShellFactory shellFactory = new TestEchoShellFactory();
         ProxyAgentFactory agentFactory = new ProxyAgentFactory();
@@ -103,71 +98,84 @@ public class AgentTest extends BaseTestSupport {
         KeyPair pair = createTestKeyPairProvider("dsaprivkey.pem").loadKey(KeyPairProvider.SSH_DSS);
         localAgentFactory.getAgent().addIdentity(pair, "smx");
 
-        SshServer sshd1 = SshServer.setUpDefaultServer();
-        sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider());
-        sshd1.setShellFactory(shellFactory);
-        sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator());
-        sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
-        sshd1.setAgentFactory(agentFactory);
-        sshd1.start();
-        port1 = sshd1.getPort();
-
-        SshServer sshd2 = SshServer.setUpDefaultServer();
-        sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider());
-        sshd2.setShellFactory(new TestEchoShellFactory());
-        sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator());
-        sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
-        sshd2.setAgentFactory(new ProxyAgentFactory());
-        sshd2.start();
-        port2 = sshd2.getPort();
-
-        SshClient client1 = SshClient.setUpDefaultClient();
-        client1.setAgentFactory(localAgentFactory);
-        client1.start();
-        ClientSession session1 = client1.connect("smx", "localhost", port1).await().getSession();
-        session1.auth().verify();
-        ChannelShell channel1 = session1.createShellChannel();
-        ByteArrayOutputStream out = new ByteArrayOutputStream();
-        ByteArrayOutputStream err = new ByteArrayOutputStream();
-        channel1.setOut(out);
-        channel1.setErr(err);
-        channel1.setAgentForwarding(true);
-        channel1.open().await();
-        OutputStream pipedIn = channel1.getInvertedIn();
-
-        synchronized (shellFactory.shell) {
-            System.out.println("Possibly waiting for remote shell to start");
-            if (!shellFactory.shell.started) {
-                shellFactory.shell.wait();
+        try(SshServer sshd1 = SshServer.setUpDefaultServer()) {
+            sshd1.setKeyPairProvider(Utils.createTestHostKeyProvider());
+            sshd1.setShellFactory(shellFactory);
+            sshd1.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+            sshd1.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
+            sshd1.setAgentFactory(agentFactory);
+            sshd1.start();
+            int port1 = sshd1.getPort();
+    
+            try(SshServer sshd2 = SshServer.setUpDefaultServer()) {
+                sshd2.setKeyPairProvider(Utils.createTestHostKeyProvider());
+                sshd2.setShellFactory(new TestEchoShellFactory());
+                sshd2.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+                sshd2.setPublickeyAuthenticator(new BogusPublickeyAuthenticator());
+                sshd2.setAgentFactory(new ProxyAgentFactory());
+                sshd2.start();
+                int port2 = sshd2.getPort();
+    
+                try(SshClient client1 = SshClient.setUpDefaultClient()) {
+                    client1.setAgentFactory(localAgentFactory);
+                    client1.start();
+                    
+                    try(ClientSession session1 = client1.connect("smx", "localhost", port1).await().getSession()) {
+                        session1.auth().verify(5L, TimeUnit.SECONDS);
+
+                        try(ChannelShell channel1 = session1.createShellChannel();
+                            ByteArrayOutputStream out = new ByteArrayOutputStream();
+                            ByteArrayOutputStream err = new ByteArrayOutputStream()) {
+
+                            channel1.setOut(out);
+                            channel1.setErr(err);
+                            channel1.setAgentForwarding(true);
+                            channel1.open().await();
+                            
+                            try(OutputStream pipedIn = channel1.getInvertedIn()) {
+                                synchronized (shellFactory.shell) {
+                                    System.out.println("Possibly waiting for remote shell to start");
+                                    if (!shellFactory.shell.started) {
+                                        shellFactory.shell.wait();
+                                    }
+                                }
+                        
+                                try(SshClient client2 = SshClient.setUpDefaultClient()) {
+                                    client2.setAgentFactory(agentFactory);
+                                    client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv());
+                                    client2.start();
+                                    
+                                    try(ClientSession session2 = client2.connect("smx", "localhost", port2).await().getSession()) {
+                                        session2.auth().verify(5L, TimeUnit.SECONDS);
+
+                                        try(ChannelShell channel2 = session2.createShellChannel()) {
+                                            channel2.setIn(shellFactory.shell.getIn());
+                                            channel2.setOut(shellFactory.shell.getOut());
+                                            channel2.setErr(shellFactory.shell.getErr());
+                                            channel2.setAgentForwarding(true);
+                                            channel2.open().await();
+                                    
+                                            pipedIn.write("foo\n".getBytes());
+                                            pipedIn.flush();
+                                        }
+                                
+                                        Thread.sleep(1000);
+                                
+                                        System.out.println(out.toString());
+                                        System.err.println(err.toString());
+                            
+                                        sshd1.stop(true);
+                                        sshd2.stop(true);
+                                        client1.stop();
+                                        client2.stop();
+                                    }
+                                }
+                            }
+                        }
+                    }
+                }
             }
         }
-
-        SshClient client2 = SshClient.setUpDefaultClient();
-        client2.setAgentFactory(agentFactory);
-        client2.getProperties().putAll(shellFactory.shell.getEnvironment().getEnv());
-        client2.start();
-        ClientSession session2 = client2.connect("smx", "localhost", port2).await().getSession();
-        session2.auth().verify();
-        ChannelShell channel2 = session2.createShellChannel();
-        channel2.setIn(shellFactory.shell.getIn());
-        channel2.setOut(shellFactory.shell.getOut());
-        channel2.setErr(shellFactory.shell.getErr());
-        channel2.setAgentForwarding(true);
-        channel2.open().await();
-
-        pipedIn.write("foo\n".getBytes());
-        pipedIn.flush();
-
-        Thread.sleep(1000);
-
-        System.out.println(out.toString());
-        System.err.println(err.toString());
-
-        sshd1.stop(true);
-        sshd2.stop(true);
-        client1.stop();
-        client2.stop();
-
     }
 
     public static class TestEchoShellFactory extends EchoShellFactory {
@@ -189,8 +197,6 @@ public class AgentTest extends BaseTestSupport {
                 started = true;
                 notifyAll();
             }
-
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java b/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
index 5a3752e..41ad906 100644
--- a/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java
@@ -78,79 +78,95 @@ public class AuthenticationTest extends BaseTestSupport {
 
     @Test
     public void testChangeUser() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.setServiceFactories(Arrays.asList(
-                new ClientUserAuthServiceOld.Factory(),
-                new ClientConnectionService.Factory()
-        ));
-        client.start();
-        ClientSession s = client.connect(null, "localhost", port).await().getSession();
-        s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
-        assertFalse(authPassword(s, "user1", "the-password").await().isSuccess());
-        assertFalse(authPassword(s, "user2", "the-password").await().isSuccess());
-
-        // Note that WAIT_AUTH flag should be false, but since the internal
-        // authentication future is not updated, it's still returned
-        assertEquals(ClientSession.CLOSED | ClientSession.WAIT_AUTH, s.waitFor(ClientSession.CLOSED, 1000));
-        client.stop();
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.setServiceFactories(Arrays.asList(
+                    new ClientUserAuthServiceOld.Factory(),
+                    new ClientConnectionService.Factory()
+            ));
+
+            client.start();
+                
+            try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+                s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+        
+                assertFalse(authPassword(s, "user1", "the-password").await().isSuccess());
+                assertFalse(authPassword(s, "user2", "the-password").await().isSuccess());
+        
+                // Note that WAIT_AUTH flag should be false, but since the internal
+                // authentication future is not updated, it's still returned
+                assertEquals(ClientSession.CLOSED | ClientSession.WAIT_AUTH, s.waitFor(ClientSession.CLOSED, 1000));
+            } finally {
+                client.stop();
+            }
+        }
     }
 
     @Test
     public void testAuthPasswordOnly() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.setServiceFactories(Arrays.asList(
-                new ClientUserAuthServiceOld.Factory(),
-                new ClientConnectionService.Factory()
-        ));
-        client.start();
-        ClientSession s = client.connect(null, "localhost", port).await().getSession();
-        s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
-        assertFalse(authPassword(s, "smx", "smx").await().isSuccess());
-
-        s.close(true);
-        client.stop();
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.setServiceFactories(Arrays.asList(
+                    new ClientUserAuthServiceOld.Factory(),
+                    new ClientConnectionService.Factory()
+            ));
+            client.start();
+            
+            try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+                s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+        
+                assertFalse(authPassword(s, "smx", "smx").await().isSuccess());
+        
+                s.close(true);
+            } finally {
+                client.stop();
+            }
+        }
     }
 
     @Test
     public void testAuthKeyPassword() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.setServiceFactories(Arrays.asList(
-                new ClientUserAuthServiceOld.Factory(),
-                new ClientConnectionService.Factory()
-        ));
-        client.start();
-        ClientSession s = client.connect(null, "localhost", port).await().getSession();
-        s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
-        KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
-        assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
-
-        assertTrue(authPassword(s, "smx", "smx").await().isSuccess());
-
-        s.close(true);
-        client.stop();
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.setServiceFactories(Arrays.asList(
+                    new ClientUserAuthServiceOld.Factory(),
+                    new ClientConnectionService.Factory()
+            ));
+            client.start();
+            
+            try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+                s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+        
+                KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
+                assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
+        
+                assertTrue(authPassword(s, "smx", "smx").await().isSuccess());
+                s.close(true);
+            } finally {
+                client.stop();
+            }
+        }
     }
 
     @Test
     public void testAuthKeyInteractive() throws Exception {
-        SshClient client = SshClient.setUpDefaultClient();
-        client.setServiceFactories(Arrays.asList(
-                new ClientUserAuthServiceOld.Factory(),
-                new ClientConnectionService.Factory()
-        ));
-        client.start();
-        ClientSession s = client.connect(null, "localhost", port).await().getSession();
-        s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
-
-        KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
-        assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
-
-        assertTrue(authInteractive(s, "smx", "smx").await().isSuccess());
-
-        s.close(true);
-        client.stop();
+        try(SshClient client = SshClient.setUpDefaultClient()) {
+            client.setServiceFactories(Arrays.asList(
+                    new ClientUserAuthServiceOld.Factory(),
+                    new ClientConnectionService.Factory()
+            ));
+            client.start();
+            
+            try(ClientSession s = client.connect(null, "localhost", port).await().getSession()) {
+                s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0);
+        
+                KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
+                assertFalse(authPublicKey(s, "smx", pair).await().isSuccess());
+        
+                assertTrue(authInteractive(s, "smx", "smx").await().isSuccess());
+        
+                s.close(true);
+            } finally {
+                client.stop();
+            }
+        }
     }
 
     private AuthFuture authPassword(ClientSession s, String user, String pswd) throws IOException {
@@ -180,5 +196,4 @@ public class AuthenticationTest extends BaseTestSupport {
             super.handleMessage(buffer);
         }
     }
-
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ClientTest.java b/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
index 872ae6c..2be4a59 100644
--- a/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/ClientTest.java
@@ -266,6 +266,8 @@ public class ClientTest extends BaseTestSupport {
             }    
 
             client.close(true);
+        } finally {
+            client.stop();
         }
     }
 
@@ -344,6 +346,8 @@ public class ClientTest extends BaseTestSupport {
                     assertArrayEquals(sent.toByteArray(), out.toByteArray());
                 }
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -386,6 +390,8 @@ public class ClientTest extends BaseTestSupport {
         
                 assertArrayEquals(sent.toByteArray(), out.toByteArray());
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -452,6 +458,8 @@ public class ClientTest extends BaseTestSupport {
         
                 assertArrayEquals(sent.toByteArray(), out.toByteArray());
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -510,6 +518,8 @@ public class ClientTest extends BaseTestSupport {
                 assertArrayEquals(sent.toByteArray(), out.toByteArray());
                 //assertArrayEquals(sent.toByteArray(), out.toByteArray());
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -553,6 +563,8 @@ public class ClientTest extends BaseTestSupport {
             closeFuture.await();
             assertNotNull("No authentication exception", authFuture.getException());
             assertTrue("Future not closed", closeFuture.isClosed());
+        } finally {
+            client.stop();
         }
     }
 
@@ -580,6 +592,8 @@ public class ClientTest extends BaseTestSupport {
                 assertTrue("Not open", openFuture.isOpened());
                 assertTrue("Not closed", closeFuture.isClosed());
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -609,6 +623,8 @@ public class ClientTest extends BaseTestSupport {
                 assertNotNull("No open exception", openFuture.getException());
                 assertTrue("Not closed", closeFuture.isClosed());
             }
+        } finally {
+            client.stop();
         }
     }
 
@@ -620,6 +636,8 @@ public class ClientTest extends BaseTestSupport {
             KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA);
             session.addPublicKeyIdentity(pair);
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -631,6 +649,8 @@ public class ClientTest extends BaseTestSupport {
         try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
             session.addPublicKeyIdentity(Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA));
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -650,6 +670,8 @@ public class ClientTest extends BaseTestSupport {
             session.addPublicKeyIdentity(new SimpleGeneratorHostKeyProvider(null, "RSA").loadKey(KeyPairProvider.SSH_RSA));
             session.addPublicKeyIdentity(pair);
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -661,6 +683,8 @@ public class ClientTest extends BaseTestSupport {
         try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
             session.addPasswordIdentity("smx");
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -673,6 +697,8 @@ public class ClientTest extends BaseTestSupport {
             session.addPasswordIdentity("bad");
             session.addPasswordIdentity("smx");
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -684,6 +710,8 @@ public class ClientTest extends BaseTestSupport {
         try(ClientSession session = client.connect("smx", "localhost", port).await().getSession()) {
             session.addPasswordIdentity("smx");
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -696,6 +724,8 @@ public class ClientTest extends BaseTestSupport {
             session.addPasswordIdentity("bad");
             session.addPasswordIdentity("smx");
             session.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -724,6 +754,8 @@ public class ClientTest extends BaseTestSupport {
             future.await();
             assertTrue("Unexpected authentication success", future.isFailure());
             assertEquals("Mismatched authentication retry count", MAX_PROMPTS, count.get());
+        } finally {
+            client.stop();
         }
     }
 
@@ -756,6 +788,8 @@ public class ClientTest extends BaseTestSupport {
             assertTrue("Authentication not marked as success", future.isSuccess());
             assertFalse("Authentication marked as failure", future.isFailure());
             assertEquals("Mismatched authentication attempts count", 1, count.get());
+        } finally {
+            client.stop();
         }
     }
 
@@ -786,6 +820,8 @@ public class ClientTest extends BaseTestSupport {
             future.await();
             assertTrue("Authentication not, marked as failure", future.isFailure());
             assertEquals("Mismatched authentication retry count", MAX_PROMPTS, count.get());
+        } finally {
+            client.stop();
         }
     }
 
@@ -822,6 +858,8 @@ public class ClientTest extends BaseTestSupport {
     
                     TestEchoShellFactory.TestEchoShell.latch.await();
                 }
+            } finally {
+                client.stop();
             }
         } finally {
             TestEchoShellFactory.TestEchoShell.latch = null;

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java b/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
index 9e59b7a..1111d28 100644
--- a/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/EcdsaTest.java
@@ -101,6 +101,8 @@ public class EcdsaTest extends BaseTestSupport {
         try(ClientSession s = client.connect("smx", "localhost", port).await().getSession()) {
             s.addPasswordIdentity("smx");
             s.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 
@@ -129,6 +131,8 @@ public class EcdsaTest extends BaseTestSupport {
         try(ClientSession s = client.connect("smx", "localhost", port).await().getSession()) {
             s.addPublicKeyIdentity(kp);
             s.auth().verify(5L, TimeUnit.SECONDS);
+        } finally {
+            client.stop();
         }
     }
 }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
index 5acf117..be798a5 100644
--- a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java
@@ -80,23 +80,33 @@ public class KeyReExchangeTest extends BaseTestSupport {
         JSch.setConfig("kex", "diffie-hellman-group-exchange-sha1");
         JSch sch = new JSch();
         com.jcraft.jsch.Session s = sch.getSession("smx", "localhost", port);
-        s.setUserInfo(new SimpleUserInfo("smx"));
-        s.connect();
-        com.jcraft.jsch.Channel c = s.openChannel("shell");
-        c.connect();
-        OutputStream os = c.getOutputStream();
-        InputStream is = c.getInputStream();
-        for (int i = 0; i < 10; i++) {
-            os.write("this is my command\n".getBytes());
-            os.flush();
-            byte[] data = new byte[512];
-            int len = is.read(data);
-            String str = new String(data, 0, len);
-            assertEquals("this is my command\n", str);
-            s.rekey();
+        try {
+            s.setUserInfo(new SimpleUserInfo("smx"));
+            s.connect();
+
+            com.jcraft.jsch.Channel c = s.openChannel("shell");
+            c.connect();
+            try(OutputStream os = c.getOutputStream();
+                InputStream is = c.getInputStream()) {
+
+                String expected = "this is my command\n";
+                byte[] bytes = expected.getBytes();
+                byte[] data = new byte[bytes.length + Long.SIZE];
+                for (int i = 0; i < 10; i++) {
+                    os.write(bytes);
+                    os.flush();
+
+                    int len = is.read(data);
+                    String str = new String(data, 0, len);
+                    assertEquals("Mismatched data at iteration " + i,expected, str);
+                    s.rekey();
+                }
+            } finally {
+                c.disconnect();
+            }
+        } finally {
+            s.disconnect();
         }
-        c.disconnect();
-        s.disconnect();
     }
 
     @Test

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
index 4a4e2ca..a756ef6 100644
--- a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java
@@ -25,6 +25,7 @@ import java.util.Arrays;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.sshd.common.Cipher;
 import org.apache.sshd.common.FactoryManager;
@@ -118,30 +119,31 @@ public class LoadTest extends BaseTestSupport {
                     SshBuilder.ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1)));
             client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc));
             client.start();
-            try {
-                ClientSession session = client.connect("sshd", "localhost", port).await().getSession();
+            try(ClientSession session = client.connect("sshd", "localhost", port).await().getSession()) {
                 session.addPasswordIdentity("sshd");
-                session.auth().verify();
+                session.auth().verify(5L, TimeUnit.SECONDS);
     
-                ByteArrayOutputStream out = new ByteArrayOutputStream();
-                ByteArrayOutputStream err = new ByteArrayOutputStream();
-                ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL);
-                channel.setOut(out);
-                channel.setErr(err);
-                try {
-                    channel.open().await();
-                    OutputStream pipedIn = channel.getInvertedIn();
-        
-                    msg += "\nexit\n";
-                    pipedIn.write(msg.getBytes());
-                    pipedIn.flush();
-        
-                    channel.waitFor(ClientChannel.CLOSED, 0);
-                } finally {    
-                    channel.close(false);
-                }
+                try(ByteArrayOutputStream out = new ByteArrayOutputStream();
+                    ByteArrayOutputStream err = new ByteArrayOutputStream();
+                    ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) {
+                    channel.setOut(out);
+                    channel.setErr(err);
 
-                assertArrayEquals("Mismatched message data", msg.getBytes(), out.toByteArray());
+                    try {
+                        channel.open().await();
+                        try(OutputStream pipedIn = channel.getInvertedIn()) {
+                            msg += "\nexit\n";
+                            pipedIn.write(msg.getBytes());
+                            pipedIn.flush();
+                        }
+            
+                        channel.waitFor(ClientChannel.CLOSED, 0);
+                    } finally {    
+                        channel.close(false);
+                    }
+    
+                    assertArrayEquals("Mismatched message data", msg.getBytes(), out.toByteArray());
+                }
             } finally {
                 client.stop();
             }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/MacTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/MacTest.java b/sshd-core/src/test/java/org/apache/sshd/MacTest.java
index bba527a..dfd2dc0 100644
--- a/sshd-core/src/test/java/org/apache/sshd/MacTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/MacTest.java
@@ -145,16 +145,19 @@ public class MacTest extends BaseTestSupport {
             s.connect();
             com.jcraft.jsch.Channel c = s.openChannel("shell");
             c.connect();
+
             try(OutputStream os = c.getOutputStream();
                 InputStream is = c.getInputStream()) {
 
-                byte[] data = new byte[512];
+                String  expected = "this is my command\n";
+                byte[] bytes = expected.getBytes();
+                byte[] data = new byte[bytes.length + Long.SIZE];
                 for (int i = 0; i < 10; i++) {
-                    os.write("this is my command\n".getBytes());
+                    os.write(bytes);
                     os.flush();
                     int len = is.read(data);
                     String str = new String(data, 0, len);
-                    assertEquals("this is my command\n", str);
+                    assertEquals("Mismatched data at iteration " + i, expected, str);
                 }
             } finally {
                 c.disconnect();

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
index e6d6b41..649eace 100644
--- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java
@@ -18,6 +18,8 @@
  */
 package org.apache.sshd;
 
+import static org.apache.sshd.util.Utils.getFreePort;
+
 import java.io.ByteArrayInputStream;
 import java.io.ByteArrayOutputStream;
 import java.io.IOException;
@@ -31,11 +33,9 @@ import java.net.URL;
 import java.util.List;
 import java.util.concurrent.CopyOnWriteArrayList;
 import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
 import java.util.concurrent.atomic.AtomicInteger;
 
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.JSchException;
-import com.jcraft.jsch.Session;
 import org.apache.commons.httpclient.HostConfiguration;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpVersion;
@@ -56,22 +56,27 @@ import org.apache.sshd.util.Utils;
 import org.junit.After;
 import org.junit.Before;
 import org.junit.Test;
+import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
-import static org.apache.sshd.util.Utils.getFreePort;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
 
 /**
  * Port forwarding tests
  */
 public class PortForwardingLoadTest extends BaseTestSupport {
-
-    private final org.slf4j.Logger log = LoggerFactory.getLogger(getClass());
-
+    private final Logger log = LoggerFactory.getLogger(getClass());
     private SshServer sshd;
     private int sshPort;
     private int echoPort;
     private IoAcceptor acceptor;
 
+    public PortForwardingLoadTest() {
+        super();
+    }
+
     @Before
     public void setUp() throws Exception {
         sshd = SshServer.setUpDefaultServer();
@@ -119,74 +124,91 @@ public class PortForwardingLoadTest extends BaseTestSupport {
                 "longer Test Data. This is significantly longer Test Data. This is significantly "+
                 "longer Test Data. This is significantly longer Test Data. This is significantly "+
                 "longer Test Data. ";
-        StringBuilder sb = new StringBuilder();
+        StringBuilder sb = new StringBuilder(PAYLOAD_TMP.length() * 1000);
         for (int i = 0; i < 1000; i++) {
             sb.append(PAYLOAD_TMP);
         }
         final String PAYLOAD = sb.toString();
-        Session session = createSession();
-        final ServerSocket ss = new ServerSocket();
-        ss.setReuseAddress(true);
-        ss.bind(new InetSocketAddress((InetAddress) null, 0));
-        int forwardedPort = ss.getLocalPort();
-        int sinkPort = session.setPortForwardingL(0, "localhost", forwardedPort);
-        final AtomicInteger conCount = new AtomicInteger(0);
 
-        new Thread() {
-            @Override
-            public void run() {
-                try {
-                    for (int i = 0; i < NUM_ITERATIONS; ++i) {
-                        try(Socket s = ss.accept()) {
-                            conCount.incrementAndGet();
-                            InputStream is = s.getInputStream();
-                            ByteArrayOutputStream baos = new ByteArrayOutputStream();
+        Session session = createSession();        
+        try(final ServerSocket ss = new ServerSocket()) {
+            ss.setReuseAddress(true);
+            ss.bind(new InetSocketAddress((InetAddress) null, 0));
+            int forwardedPort = ss.getLocalPort();
+            int sinkPort = session.setPortForwardingL(0, "localhost", forwardedPort);
+            final AtomicInteger conCount = new AtomicInteger(0);
+    
+            Thread tAcceptor = new Thread(getCurrentTestName() + "Acceptor") {
+                    @SuppressWarnings("synthetic-access")
+                    @Override
+                    public void run() {
+                        try {
                             byte[] buf = new byte[8192];
-                            int l;
-                            while (baos.size() < PAYLOAD.length() && (l = is.read(buf)) > 0) {
-                                baos.write(buf, 0, l);
-                            }
-                            if (!PAYLOAD.equals(baos.toString())) {
-                                assertEquals(PAYLOAD, baos.toString());
-                            }
-                            is = new ByteArrayInputStream(baos.toByteArray());
-                            OutputStream os = s.getOutputStream();
-                            while ((l = is.read(buf)) > 0) {
-                                os.write(buf, 0, l);
+                            log.info("Started...");
+                            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                                try(Socket s = ss.accept()) {
+                                    conCount.incrementAndGet();
+                                    
+                                    try(InputStream sockIn = s.getInputStream();
+                                        ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+                                    
+                                        int l;
+                                        while ((baos.size() < PAYLOAD.length()) && ((l = sockIn.read(buf)) > 0)) {
+                                            baos.write(buf, 0, l);
+                                        }
+                                    
+                                        assertEquals("Mismatched received data at iteration #" + i, PAYLOAD, baos.toString());
+        
+                                        try(InputStream inputCopy = new ByteArrayInputStream(baos.toByteArray());
+                                            OutputStream sockOut = s.getOutputStream()) {
+                                            
+                                            while ((l = sockIn.read(buf)) > 0) {
+                                                sockOut.write(buf, 0, l);
+                                            }
+                                        }
+                                    }
+                                }
                             }
+                            log.info("Done");
+                        } catch (Exception e) {
+                            log.error("Failed to complete run loop", e);
                         }
                     }
-                } catch (Exception e) {
-                    e.printStackTrace();
-                }
-            }
-        }.start();
-        Thread.sleep(50);
+                };
+            tAcceptor.start();
+            Thread.sleep(50);
+    
+            byte[]  buf = new byte[8192];
+            byte[]  bytes = PAYLOAD.getBytes();
+            for (int i = 0; i < NUM_ITERATIONS; i++) {
+                log.info("Iteration {}", Integer.valueOf(i));
+                try(Socket s = new Socket("localhost", sinkPort);
+                    OutputStream sockOut = s.getOutputStream()) {
 
-        for ( int i = 0; i < NUM_ITERATIONS; i++) {
-            Socket s = null;
-            try {
-                LoggerFactory.getLogger(getClass()).info("Iteration {}", i);
-                s = new Socket("localhost", sinkPort);
-                s.getOutputStream().write(PAYLOAD.getBytes());
-                s.getOutputStream().flush();
-                ByteArrayOutputStream baos = new ByteArrayOutputStream();
-                byte[] buf = new byte[8192];
-                int l;
-                while (baos.size() < PAYLOAD.length() && (l = s.getInputStream().read(buf)) > 0) {
-                    baos.write(buf, 0, l);
-                }
-                assertEquals(PAYLOAD, baos.toString());
-            } catch (Exception e) {
-                e.printStackTrace();
-            } finally {
-                if (s != null) {
-                    s.close();
+                    s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+                    sockOut.write(bytes);
+                    sockOut.flush();
+    
+                    try(InputStream sockIn = s.getInputStream();
+                        ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length)) {
+                        int l;
+                        while ((baos.size() < PAYLOAD.length()) && ((l = sockIn.read(buf)) > 0)) {
+                            baos.write(buf, 0, l);
+                        }
+                        assertEquals("Mismatched payload at iteration #" + i, PAYLOAD, baos.toString());
+                    }
+                } catch (Exception e) {
+                    log.error("Error in iteration #" + i, e);
                 }
             }
+            session.delPortForwardingL(sinkPort);
+            
+            ss.close();
+            tAcceptor.join(TimeUnit.SECONDS.toMillis(5L));
+        } finally {
+            session.disconnect();
         }
-        session.delPortForwardingL(sinkPort);
-        ss.close();
     }
 
     @Test
@@ -199,72 +221,91 @@ public class PortForwardingLoadTest extends BaseTestSupport {
                 "longer Test Data. This is significantly longer Test Data. This is significantly "+
                 "longer Test Data. ";
         Session session = createSession();
-        final ServerSocket ss = new ServerSocket();
-        ss.setReuseAddress(true);
-        ss.bind(new InetSocketAddress((InetAddress) null, 0));
-        int forwardedPort = ss.getLocalPort();
-        int sinkPort = getFreePort();
-        session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
-        final boolean started[] = new boolean[1];
-        started[0] = false;
-        final AtomicInteger conCount = new AtomicInteger(0);
-
-        new Thread() {
-            @Override
-            public void run() {
-                started[0] = true;
-                try {
-                    for (int i = 0; i < NUM_ITERATIONS; ++i) {
-                        try(Socket s = ss.accept()) {
-                            conCount.incrementAndGet();
-                            s.getOutputStream().write(PAYLOAD.getBytes());
-                            s.getOutputStream().flush();
+        try (final ServerSocket ss = new ServerSocket()) {
+            ss.setReuseAddress(true);
+            ss.bind(new InetSocketAddress((InetAddress) null, 0));
+            int forwardedPort = ss.getLocalPort();
+            int sinkPort = getFreePort();
+            session.setPortForwardingR(sinkPort, "localhost", forwardedPort);
+            final boolean started[] = new boolean[1];
+            started[0] = false;
+            final AtomicInteger conCount = new AtomicInteger(0);
+    
+            Thread tWriter = new Thread(getCurrentTestName() + "Writer") {
+                    @SuppressWarnings("synthetic-access")
+                    @Override
+                    public void run() {
+                        started[0] = true;
+                        try {
+                            byte[]  bytes=PAYLOAD.getBytes();
+                            for (int i = 0; i < NUM_ITERATIONS; ++i) {
+                                try(Socket s = ss.accept()) {
+                                    conCount.incrementAndGet();
+                                    
+                                    try(OutputStream sockOut=s.getOutputStream()) {
+                                        sockOut.write(bytes);
+                                        sockOut.flush();
+                                    }
+                                }
+                            }
+                        } catch (Exception e) {
+                            log.error("Failed to complete run loop", e);
                         }
                     }
+                };
+            tWriter.start();
+            Thread.sleep(50);
+            assertTrue("Server not started", started[0]);
+    
+            final boolean lenOK[] = new boolean[NUM_ITERATIONS];
+            final boolean dataOK[] = new boolean[NUM_ITERATIONS];
+            byte b2[] = new byte[PAYLOAD.length()];
+            byte b1[] = new byte[b2.length / 2];
+
+            for (int i = 0; i < NUM_ITERATIONS; i++) {
+                final int ii = i;
+                try(Socket s = new Socket("localhost", sinkPort);
+                    InputStream sockIn = s.getInputStream()) {
+
+                    s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+                    int read1 = sockIn.read(b1);
+                    String part1 = new String(b1, 0, read1);
+                    Thread.sleep(50);
+
+                    int read2 = sockIn.read(b2);
+                    String part2 = new String(b2, 0, read2);
+                    int totalRead = read1 + read2;
+                    lenOK[ii] = PAYLOAD.length() == totalRead;
+
+                    String readData = part1 + part2;
+                    dataOK[ii] = PAYLOAD.equals(readData);
+                    if (!lenOK[ii]) {
+                        throw new IndexOutOfBoundsException("Mismatched length: expected=" + PAYLOAD.length() + ", actual=" + totalRead);
+                    }
+                    
+                    if (!dataOK[ii]) {
+                        throw new IllegalStateException("Mismatched content");
+                    }
                 } catch (Exception e) {
-                    e.printStackTrace();
+                    log.error("Failed to complete iteration #" + i, e);
                 }
             }
-        }.start();
-        Thread.sleep(50);
-        assertTrue("Server not started", started[0]);
-
-        final boolean lenOK[] = new boolean[NUM_ITERATIONS];
-        final boolean dataOK[] = new boolean[NUM_ITERATIONS];
-        for ( int i = 0; i < NUM_ITERATIONS; i++) {
-            final int ii = i;
-            Socket s = null;
-            try {
-                s = new Socket("localhost", sinkPort);
-                byte b1[] = new byte[PAYLOAD.length() / 2];
-                byte b2[] = new byte[PAYLOAD.length()];
-                int read1 = s.getInputStream().read(b1);
-                Thread.sleep(50);
-                int read2 = s.getInputStream().read(b2);
-                lenOK[ii] = PAYLOAD.length() == read1 + read2;
-                dataOK[ii] = PAYLOAD.equals(new String(b1, 0, read1) + new String(b2, 0, read2));
-                if (!lenOK[ii] || !dataOK[ii] ) {
-                    throw new Exception("Bad data");
-                }
-            } catch (Exception e) {
-                e.printStackTrace();
-            } finally {
-                if (s != null) {
-                    s.close();
-                }
+            int ok = 0;
+            for (int i = 0; i < NUM_ITERATIONS; i++) {
+                ok += lenOK[i] ? 1 : 0;
             }
+            Thread.sleep(50);
+            for (int i = 0; i < NUM_ITERATIONS; i++) {
+                assertTrue("Bad length at iteration " + i, lenOK[i]);
+                assertTrue("Bad data at iteration " + i, dataOK[i]);
+            }
+            session.delPortForwardingR(forwardedPort);
+            ss.close();
+            tWriter.join(TimeUnit.SECONDS.toMillis(5L));
+        } finally {
+            session.disconnect();
         }
-        int ok = 0;
-        for (int i = 0; i < NUM_ITERATIONS; i++) {
-            ok += lenOK[i] ? 1 : 0;
-        }
-        Thread.sleep(50);
-        for (int i = 0; i < NUM_ITERATIONS; i++) {
-            assertTrue(lenOK[i]);
-            assertTrue(dataOK[i]);
-        }
-        session.delPortForwardingR(forwardedPort);
-        ss.close();
     }
 
     @Test
@@ -303,49 +344,50 @@ public class PortForwardingLoadTest extends BaseTestSupport {
         final int port = acceptor.getLocalAddress().getPort();
 
         Session session = createSession();
-
-        final int forwardedPort1 = session.setPortForwardingL(0, host, port);
-        final int forwardedPort2 = getFreePort();
-        session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);
-        System.err.println("URL: http://localhost:" + forwardedPort2);
-
-
-        final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);
-
-        final Thread[] threads = new Thread[nbThread];
-        final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
-        for (int i = 0; i < threads.length; i++) {
-            threads[i] = new Thread() {
-                @Override
-                public void run() {
-                    for (int j = 0; j < nbLoops; j++)  {
-                        final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
-                        final HttpClient client = new HttpClient(mgr);
-                        client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
-                        client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
-                        for (int i = 0; i < nbDownloads; i++) {
-                            try {
-                                checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
-                            } catch (Throwable e) {
-                                errors.add(e);
-                            } finally {
-                                latch.countDown();
-                                System.err.println("Remaining: " + latch.getCount());
+        try {
+            final int forwardedPort1 = session.setPortForwardingL(0, host, port);
+            final int forwardedPort2 = getFreePort();
+            session.setPortForwardingR(forwardedPort2, "localhost", forwardedPort1);
+            System.err.println("URL: http://localhost:" + forwardedPort2);
+    
+            final CountDownLatch latch = new CountDownLatch(nbThread * nbDownloads * nbLoops);
+            final Thread[] threads = new Thread[nbThread];
+            final List<Throwable> errors = new CopyOnWriteArrayList<Throwable>();
+            for (int i = 0; i < threads.length; i++) {
+                threads[i] = new Thread(getCurrentTestName() + "[" + i + "]") {
+                    @Override
+                    public void run() {
+                        for (int j = 0; j < nbLoops; j++)  {
+                            final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
+                            final HttpClient client = new HttpClient(mgr);
+                            client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100);
+                            client.getHttpConnectionManager().getParams().setMaxTotalConnections(1000);
+                            for (int i = 0; i < nbDownloads; i++) {
+                                try {
+                                    checkHtmlPage(client, new URL("http://localhost:" + forwardedPort2 + path));
+                                } catch (Throwable e) {
+                                    errors.add(e);
+                                } finally {
+                                    latch.countDown();
+                                    System.err.println("Remaining: " + latch.getCount());
+                                }
                             }
+                            mgr.shutdown();
                         }
-                        mgr.shutdown();
                     }
-                }
-            };
-        }
-        for (int i = 0; i < threads.length; i++) {
-            threads[i].start();
-        }
-        latch.await();
-        for (Throwable t : errors) {
-            t.printStackTrace();
+                };
+            }
+            for (int i = 0; i < threads.length; i++) {
+                threads[i].start();
+            }
+            latch.await();
+            for (Throwable t : errors) {
+                t.printStackTrace();
+            }
+            assertEquals(0, errors.size());
+        } finally {
+            session.disconnect();
         }
-        assertEquals(0, errors.size());
     }
 
     protected Session createSession() throws JSchException {

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
index 7f85d08..b70c973 100644
--- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java
@@ -19,11 +19,13 @@
 package org.apache.sshd;
 
 import static org.apache.sshd.util.Utils.getFreePort;
+
 import java.lang.reflect.Field;
 import java.net.InetSocketAddress;
 import java.net.Socket;
 import java.util.HashSet;
 import java.util.Set;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.mina.core.buffer.IoBuffer;
 import org.apache.mina.core.service.IoAcceptor;
@@ -32,6 +34,7 @@ import org.apache.mina.core.session.IoSession;
 import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
 import org.apache.sshd.client.channel.ChannelDirectTcpip;
 import org.apache.sshd.common.FactoryManager;
+import org.apache.sshd.common.FactoryManagerUtils;
 import org.apache.sshd.common.SshdSocketAddress;
 import org.apache.sshd.util.BaseTestSupport;
 import org.apache.sshd.util.BogusForwardingFilter;
@@ -65,8 +68,8 @@ public class PortForwardingTest extends BaseTestSupport {
     @Before
     public void setUp() throws Exception {
         sshd = SshServer.setUpDefaultServer();
-        sshd.getProperties().put(FactoryManager.WINDOW_SIZE, "2048");
-        sshd.getProperties().put(FactoryManager.MAX_PACKET_SIZE, "256");
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.WINDOW_SIZE, 2048);
+        FactoryManagerUtils.updateProperty(sshd, FactoryManager.MAX_PACKET_SIZE, 256);
         sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
         sshd.setShellFactory(new EchoShellFactory());
         sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
@@ -89,7 +92,6 @@ public class PortForwardingTest extends BaseTestSupport {
         acceptor.bind(new InetSocketAddress(0));
         echoPort = acceptor.getLocalAddress().getPort();
         this.acceptor = acceptor;
-
     }
 
     @After
@@ -108,22 +110,29 @@ public class PortForwardingTest extends BaseTestSupport {
     @Test
     public void testRemoteForwarding() throws Exception {
         Session session = createSession();
+        try {
+            int forwardedPort = getFreePort();
+            session.setPortForwardingR(forwardedPort, "localhost", echoPort);
+            Thread.sleep(100);
+    
+            try(Socket s = new Socket("localhost", forwardedPort)) {
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
 
-        int forwardedPort = getFreePort();
-        session.setPortForwardingR(forwardedPort, "localhost", echoPort);
-        Thread.sleep(100);
-
-        try(Socket s = new Socket("localhost", forwardedPort)) {
-            s.getOutputStream().write("Hello".getBytes());
-            s.getOutputStream().flush();
-            byte[] buf = new byte[1024];
-            int n = s.getInputStream().read(buf);
-            String res = new String(buf, 0, n);
-            assertEquals("Hello", res);
-        }
+                String  expected = getCurrentTestName();
+                byte[]  bytes = expected.getBytes();
+                s.getOutputStream().write(bytes);
+                s.getOutputStream().flush();
 
-        session.delPortForwardingR(forwardedPort);
-        session.disconnect();
+                byte[]  buf = new byte[bytes.length + Long.SIZE];
+                int     n = s.getInputStream().read(buf);
+                String  res = new String(buf, 0, n);
+                assertEquals("Mismatched data", expected, res);
+            }
+    
+            session.delPortForwardingR(forwardedPort);
+        } finally {
+            session.disconnect();
+        }
     }
 
     @Test
@@ -134,12 +143,17 @@ public class PortForwardingTest extends BaseTestSupport {
             SshdSocketAddress bound = session.startRemotePortForwarding(remote, local);
     
             try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
-                s.getOutputStream().write("Hello".getBytes());
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+                String  expected = getCurrentTestName();
+                byte[]  bytes = expected.getBytes();
+                s.getOutputStream().write(bytes);
                 s.getOutputStream().flush();
-                byte[] buf = new byte[1024];
-                int n = s.getInputStream().read(buf);
-                String res = new String(buf, 0, n);
-                assertEquals("Hello", res);
+
+                byte[]  buf = new byte[bytes.length + Long.SIZE];
+                int     n = s.getInputStream().read(buf);
+                String  res = new String(buf, 0, n);
+                assertEquals("Mismatched data", expected, res);
             }
 
             session.stopRemotePortForwarding(remote);
@@ -154,15 +168,20 @@ public class PortForwardingTest extends BaseTestSupport {
             SshdSocketAddress local = new SshdSocketAddress("localhost", echoPort);
             SshdSocketAddress bound = session.startRemotePortForwarding(remote, local);
 
-            byte[] buf = new byte[1024];
-    
             try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+                String  expected = getCurrentTestName();
+                byte[]  bytes = expected.getBytes();
+                byte[]  buf = new byte[bytes.length + Long.SIZE];
+
                 for (int i = 0; i < 1000; i++) {
-                    s.getOutputStream().write("0123456789".getBytes());
+                    s.getOutputStream().write(bytes);
                     s.getOutputStream().flush();
-                    int n = s.getInputStream().read(buf);
-                    String res = new String(buf, 0, n);
-                    assertEquals("0123456789", res);
+
+                    int     n = s.getInputStream().read(buf);
+                    String  res = new String(buf, 0, n);
+                    assertEquals("Mismatched data at iteration #" + i, expected, res);
                 }
             }
     
@@ -174,21 +193,29 @@ public class PortForwardingTest extends BaseTestSupport {
     @Test
     public void testLocalForwarding() throws Exception {
         Session session = createSession();
+        try {
+            int forwardedPort = getFreePort();
+            session.setPortForwardingL(forwardedPort, "localhost", echoPort);
+    
+            try(Socket s = new Socket("localhost", forwardedPort)) {
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
 
-        int forwardedPort = getFreePort();
-        session.setPortForwardingL(forwardedPort, "localhost", echoPort);
+                String  expected = getCurrentTestName();
+                byte[]  bytes = expected.getBytes();
 
-        try(Socket s = new Socket("localhost", forwardedPort)) {
-            s.getOutputStream().write("Hello".getBytes());
-            s.getOutputStream().flush();
-            byte[] buf = new byte[1024];
-            int n = s.getInputStream().read(buf);
-            String res = new String(buf, 0, n);
-            assertEquals("Hello", res);
-        }
+                s.getOutputStream().write(bytes);
+                s.getOutputStream().flush();
 
-        session.delPortForwardingL(forwardedPort);
-        session.disconnect();
+                byte[]  buf = new byte[bytes.length + Long.SIZE];
+                int     n = s.getInputStream().read(buf);
+                String  res = new String(buf, 0, n);
+                assertEquals("Mismatched data", expected, res);
+            }
+    
+            session.delPortForwardingL(forwardedPort);
+        } finally {
+            session.disconnect();
+        }
     }
 
     @Test
@@ -199,12 +226,18 @@ public class PortForwardingTest extends BaseTestSupport {
             SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);
 
             try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
-                s.getOutputStream().write("Hello".getBytes());
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+                String  expected = getCurrentTestName();
+                byte[]  bytes = expected.getBytes();
+
+                s.getOutputStream().write(bytes);
                 s.getOutputStream().flush();
-                byte[] buf = new byte[1024];
-                int n = s.getInputStream().read(buf);
-                String res = new String(buf, 0, n);
-                assertEquals("Hello", res);
+
+                byte[]  buf = new byte[bytes.length + Long.SIZE];
+                int     n = s.getInputStream().read(buf);
+                String  res = new String(buf, 0, n);
+                assertEquals("Mismatched data", expected, res);
             }
 
             session.stopLocalPortForwarding(bound);
@@ -235,14 +268,19 @@ public class PortForwardingTest extends BaseTestSupport {
             SshdSocketAddress remote = new SshdSocketAddress("localhost", echoPort);
             SshdSocketAddress bound = session.startLocalPortForwarding(local, remote);
 
-            byte[] buf = new byte[1024];
+            String  expected = getCurrentTestName();
+            byte[]  bytes = expected.getBytes();
+            byte[]  buf = new byte[bytes.length + Long.SIZE];
             try(Socket s = new Socket(bound.getHostName(), bound.getPort())) {
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
                 for (int i = 0; i < 1000; i++) {
-                    s.getOutputStream().write("Hello".getBytes());
+                    s.getOutputStream().write(bytes);
                     s.getOutputStream().flush();
-                    int n = s.getInputStream().read(buf);
-                    String res = new String(buf, 0, n);
-                    assertEquals("Hello", res);
+
+                    int     n = s.getInputStream().read(buf);
+                    String  res = new String(buf, 0, n);
+                    assertEquals("Mismatched data at iteration #" + i, expected, res);
                 }
             }
     
@@ -259,13 +297,17 @@ public class PortForwardingTest extends BaseTestSupport {
 
             try(ChannelDirectTcpip channel = session.createDirectTcpipChannel(local, remote)) {
                 channel.open().await();
-        
-                channel.getInvertedIn().write("Hello".getBytes());
+
+                String  expected = getCurrentTestName();
+                byte[]  bytes = expected.getBytes();
+
+                channel.getInvertedIn().write(bytes);
                 channel.getInvertedIn().flush();
-                byte[] buf = new byte[1024];
-                int n = channel.getInvertedOut().read(buf);
-                String res = new String(buf, 0, n);
-                assertEquals("Hello", res);
+
+                byte[]  buf = new byte[bytes.length + Long.SIZE];
+                int     n = channel.getInvertedOut().read(buf);
+                String  res = new String(buf, 0, n);
+                assertEquals("Mismatched data", expected, res);
                 channel.close(false);
             }
 
@@ -276,41 +318,45 @@ public class PortForwardingTest extends BaseTestSupport {
     @Test(timeout = 20000)
     public void testRemoteForwardingWithDisconnect() throws Exception {
         Session session = createSession();
-
-        // 1. Create a Port Forward
-        int forwardedPort = getFreePort();
-        session.setPortForwardingR(forwardedPort, "localhost", echoPort);
-
-        // 2. Establish a connection through it
-        try(Socket s = new Socket("localhost", forwardedPort)) {
-            // 3. Simulate the client going away
-            rudelyDisconnectJschSession(session);
+        try {
+            // 1. Create a Port Forward
+            int forwardedPort = getFreePort();
+            session.setPortForwardingR(forwardedPort, "localhost", echoPort);
     
-            // 4. Make sure the NIOprocessor is not stuck
-            {
-                Thread.sleep(1000);
-                // from here, we need to check all the threads running and find a
-                // "NioProcessor-"
-                // that is stuck on a PortForward.dispose
-                ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
-                while (root.getParent() != null) {
-                    root = root.getParent();
-                }
-                boolean stuck;
-                do {
-                    stuck = false;
-                    for (Thread t : findThreads(root, "NioProcessor-")) {
-                        stuck = true;
-                    }
-                    try {
-                        Thread.sleep(1000);
-                    } catch (InterruptedException e) {
-                        // ignored
+            // 2. Establish a connection through it
+            try(Socket s = new Socket("localhost", forwardedPort)) {
+                s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+
+                // 3. Simulate the client going away
+                rudelyDisconnectJschSession(session);
+        
+                // 4. Make sure the NIOprocessor is not stuck
+                {
+                    Thread.sleep(1000);
+                    // from here, we need to check all the threads running and find a
+                    // "NioProcessor-"
+                    // that is stuck on a PortForward.dispose
+                    ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
+                    while (root.getParent() != null) {
+                        root = root.getParent();
                     }
-                } while (stuck);
+                    boolean stuck;
+                    do {
+                        stuck = false;
+                        for (Thread t : findThreads(root, "NioProcessor-")) {
+                            stuck = true;
+                        }
+                        try {
+                            Thread.sleep(1000);
+                        } catch (InterruptedException e) {
+                            // ignored
+                        }
+                    } while (stuck);
+                }
+        
+                session.delPortForwardingR(forwardedPort);
             }
-    
-            session.delPortForwardingR(forwardedPort);
+        } finally {
             session.disconnect();
         }
     }

http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/1c51deb3/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
index ad073ec..dd1bc2f 100644
--- a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java
@@ -19,9 +19,12 @@
 package org.apache.sshd;
 
 import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
 import java.net.InetSocketAddress;
 import java.net.Proxy;
 import java.net.Socket;
+import java.util.concurrent.TimeUnit;
 
 import org.apache.mina.core.buffer.IoBuffer;
 import org.apache.mina.core.service.IoAcceptor;
@@ -97,15 +100,24 @@ public class ProxyTest extends BaseTestSupport {
         try(ClientSession session = createNativeSession()) {
             SshdSocketAddress dynamic = session.startDynamicPortForwarding(new SshdSocketAddress("localhost", 0));
 
-            byte[] buf = new byte[1024];
-            for (int i = 0, l = 0; i < 10; i++) {
+            String  expected = getCurrentTestName();
+            byte[]  bytes = expected.getBytes();
+            byte[]  buf = new byte[bytes.length + Long.SIZE];
+            for (int i = 0; i < 10; i++) {
                 try(Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) {
                     s.connect(new InetSocketAddress("localhost", echoPort));
-                    s.getOutputStream().write("foo".getBytes());
-                    s.getOutputStream().flush();
-                    l = s.getInputStream().read(buf);
+                    s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+                    
+                    try(OutputStream sockOut = s.getOutputStream();
+                        InputStream sockIn = s.getInputStream()) {
+                        
+                        sockOut.write(bytes);
+                        sockOut.flush();
+                    
+                        int l = sockIn.read(buf);
+                        assertEquals("Mismatched data at iteration " + i, expected, new String(buf, 0, l));
+                    }
                 }
-                assertEquals("foo", new String(buf, 0, l));
             }
 
             session.stopDynamicPortForwarding(dynamic);
@@ -113,8 +125,9 @@ public class ProxyTest extends BaseTestSupport {
             try {
                 try(Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) {
                     s.connect(new InetSocketAddress("localhost", echoPort));
-                    s.getOutputStream().write("foo".getBytes());
-                    fail("Expected IOException");
+                    s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L));
+                    s.getOutputStream().write(bytes);
+                    fail("Unexpected success to write proxy data");
                 }
             } catch (IOException e) {
                 // expected
@@ -137,5 +150,3 @@ public class ProxyTest extends BaseTestSupport {
         return session;
     }
 }
-
-