http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java b/sshd-core/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java index 1359253..7515328 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/util/ThreadUtilsTest.java @@ -40,23 +40,23 @@ public class ThreadUtilsTest extends BaseTestSupport { @Test public void testProtectExecutorServiceShutdown() { - for (boolean shutdownOnExit : new boolean[] { true, false }) { + for (boolean shutdownOnExit : new boolean[]{true, false}) { assertNull("Unexpected instance for shutdown=" + shutdownOnExit, ThreadUtils.protectExecutorServiceShutdown(null, shutdownOnExit)); } - ExecutorService service=Executors.newSingleThreadExecutor(); + ExecutorService service = Executors.newSingleThreadExecutor(); try { assertSame("Unexpected wrapped instance", service, ThreadUtils.protectExecutorServiceShutdown(service, true)); - - ExecutorService wrapped=ThreadUtils.protectExecutorServiceShutdown(service, false); + + ExecutorService wrapped = ThreadUtils.protectExecutorServiceShutdown(service, false); try { assertNotSame("No wrapping occurred", service, wrapped); wrapped.shutdown(); assertTrue("Wrapped service not shutdown", wrapped.isShutdown()); assertFalse("Protected service is shutdown", service.isShutdown()); - - Collection<?> running=wrapped.shutdownNow(); + + Collection<?> running = wrapped.shutdownNow(); assertTrue("Non-empty runners list", running.isEmpty()); assertTrue("Wrapped service not shutdownNow", wrapped.isShutdown()); assertFalse("Protected service is shutdownNow", service.isShutdown());
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java b/sshd-core/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java index ee60971..6a5f563 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/util/ValidateUtilsTest.java @@ -33,7 +33,7 @@ public class ValidateUtilsTest extends BaseTestSupport { super(); } - @Test(expected=IllegalArgumentException.class) + @Test(expected = IllegalArgumentException.class) public void checkNotNull() { ValidateUtils.checkNotNull(getClass(), getCurrentTestName()); ValidateUtils.checkNotNull(null, getCurrentTestName()); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/common/util/io/EmptyInputStreamTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/util/io/EmptyInputStreamTest.java b/sshd-core/src/test/java/org/apache/sshd/common/util/io/EmptyInputStreamTest.java index f7c1e56..ba88534 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/util/io/EmptyInputStreamTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/util/io/EmptyInputStreamTest.java @@ -39,14 +39,14 @@ public class EmptyInputStreamTest extends BaseTestSupport { @Test public void testEmptyInputStream() throws IOException { - try(EmptyInputStream in = new EmptyInputStream()) { + try (EmptyInputStream in = new EmptyInputStream()) { testEmptyInputStream(in, false); } } @Test public void testCloseableEmptyInputStream() throws IOException { - try(EmptyInputStream in = new CloseableEmptyInputStream()) { + try (EmptyInputStream in = new CloseableEmptyInputStream()) { testEmptyInputStream(in, true); } } @@ -62,7 +62,7 @@ public class EmptyInputStreamTest extends BaseTestSupport { try { in.mark(Long.SIZE); fail(message + ": unexpected mark success"); - } catch(UnsupportedOperationException e) { + } catch (UnsupportedOperationException e) { // expected } @@ -70,7 +70,7 @@ public class EmptyInputStreamTest extends BaseTestSupport { int len = in.available(); assertFalse(message + ": Unexpected success in available(): " + len, errorExpected); assertEquals(message + ": Mismatched available() result", 0, len); - } catch(IOException e) { + } catch (IOException e) { assertTrue(message + ": Unexpected error on available(): " + e.getMessage(), errorExpected); } @@ -78,7 +78,7 @@ public class EmptyInputStreamTest extends BaseTestSupport { int data = in.read(); assertFalse(message + ": Unexpected success in read(): " + data, errorExpected); assertEquals(message + ": Mismatched read() result", (-1), data); - } catch(IOException e) { + } catch (IOException e) { assertTrue(message + ": Unexpected error on read(): " + e.getMessage(), errorExpected); } @@ -87,7 +87,7 @@ public class EmptyInputStreamTest extends BaseTestSupport { int len = in.read(bytes); assertFalse(message + ": Unexpected success in read([]): " + BufferUtils.printHex(':', bytes), errorExpected); assertEquals(message + ": Mismatched read([]) result", (-1), len); - } catch(IOException e) { + } catch (IOException e) { assertTrue(message + ": Unexpected error on read([]): " + e.getMessage(), errorExpected); } @@ -95,7 +95,7 @@ public class EmptyInputStreamTest extends BaseTestSupport { int len = in.read(bytes, 0, bytes.length); assertFalse(message + ": Unexpected success in read([],int,int): " + BufferUtils.printHex(':', bytes), errorExpected); assertEquals(message + ": Mismatched read([],int,int) result", (-1), len); - } catch(IOException e) { + } catch (IOException e) { assertTrue(message + ": Unexpected error on read([],int,int): " + e.getMessage(), errorExpected); } @@ -103,14 +103,14 @@ public class EmptyInputStreamTest extends BaseTestSupport { long len = in.skip(Byte.MAX_VALUE); assertFalse(message + ": Unexpected success in skip(): " + len, errorExpected); assertEquals(message + ": Mismatched skip() result", 0L, len); - } catch(IOException e) { + } catch (IOException e) { assertTrue(message + ": Unexpected error on skip(): " + e.getMessage(), errorExpected); } try { in.reset(); assertFalse(message + ": Unexpected success in reset()", errorExpected); - } catch(IOException e) { + } catch (IOException e) { assertTrue(message + ": Unexpected error on reset(): " + e.getMessage(), errorExpected); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/common/util/io/LimitInputStreamTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/common/util/io/LimitInputStreamTest.java b/sshd-core/src/test/java/org/apache/sshd/common/util/io/LimitInputStreamTest.java index ee9e06e..45ed9e3 100644 --- a/sshd-core/src/test/java/org/apache/sshd/common/util/io/LimitInputStreamTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/common/util/io/LimitInputStreamTest.java @@ -43,17 +43,17 @@ public class LimitInputStreamTest extends BaseTestSupport { public void testReadLimit() throws IOException { Path targetPath = detectTargetFolder().toPath(); Path rootFolder = assertHierarchyTargetFolderExists(targetPath.resolve(getClass().getSimpleName())); - Path inputFile = rootFolder.resolve(getCurrentTestName() + ".bin"); + Path inputFile = rootFolder.resolve(getCurrentTestName() + ".bin"); byte[] data = (getClass().getName() + "#" + getCurrentTestName()).getBytes(StandardCharsets.UTF_8); Files.write(inputFile, data); - try(InputStream in = Files.newInputStream(inputFile)) { + try (InputStream in = Files.newInputStream(inputFile)) { int maxLen = data.length / 2; byte[] expected = new byte[maxLen]; System.arraycopy(data, 0, expected, 0, expected.length); byte[] actual = new byte[expected.length]; - try(LimitInputStream limited = new LimitInputStream(in, expected.length)) { + try (LimitInputStream limited = new LimitInputStream(in, expected.length)) { assertTrue("Limited stream not marked as open", limited.isOpen()); assertEquals("Mismatched initial available data size", expected.length, limited.available()); @@ -61,52 +61,52 @@ public class LimitInputStreamTest extends BaseTestSupport { assertEquals("Incomplete actual data read", actual.length, readLen); assertArrayEquals("Mismatched read data", expected, actual); assertEquals("Mismatched remaining available data size", 0, limited.available()); - + readLen = limited.read(); assertTrue("Unexpected success to read one more byte: " + readLen, readLen < 0); readLen = limited.read(actual); assertTrue("Unexpected success to read extra buffer: " + readLen, readLen < 0); - + limited.close(); assertFalse("Limited stream still marked as open", limited.isOpen()); - + try { readLen = limited.read(); fail("Unexpected one byte read success after close"); - } catch(IOException e) { + } catch (IOException e) { // expected } try { readLen = limited.read(actual); fail("Unexpected buffer read success after close: " + readLen); - } catch(IOException e) { + } catch (IOException e) { // expected } try { readLen = limited.read(actual); fail("Unexpected buffer read success after close: " + readLen); - } catch(IOException e) { + } catch (IOException e) { // expected } try { readLen = (int) limited.skip(Byte.SIZE); fail("Unexpected skip success after close: " + readLen); - } catch(IOException e) { + } catch (IOException e) { // expected } try { readLen = limited.available(); fail("Unexpected available success after close: " + readLen); - } catch(IOException e) { + } catch (IOException e) { // expected } } - + // make sure underlying stream not closed int readLen = in.read(actual); assertEquals("Incomplete extra data read", Math.min(actual.length, data.length - expected.length), readLen); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java b/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java index 98602fa..6d4ccd4 100644 --- a/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java +++ b/sshd-core/src/test/java/org/apache/sshd/deprecated/ClientUserAuthServiceOld.java @@ -52,6 +52,7 @@ public class ClientUserAuthServiceOld extends CloseableUtils.AbstractCloseable i return new ClientUserAuthServiceOld(session); } } + /** * When !authFuture.isDone() the current authentication */ @@ -113,6 +114,7 @@ public class ClientUserAuthServiceOld extends CloseableUtils.AbstractCloseable i /** * return true if/when ready for auth; false if never ready. + * * @return server is ready and waiting for auth */ private boolean readyForAuth(UserAuth userAuth) { @@ -130,7 +132,7 @@ public class ClientUserAuthServiceOld extends CloseableUtils.AbstractCloseable i log.debug("already authenticated"); throw new IllegalStateException("Already authenticated"); } - + Throwable err = this.authFuture.getException(); if (err != null) { log.debug("probably closed", err); @@ -154,13 +156,14 @@ public class ClientUserAuthServiceOld extends CloseableUtils.AbstractCloseable i /** * execute one step in user authentication. + * * @param buffer * @throws java.io.IOException */ private void processUserAuth(Buffer buffer) throws IOException { log.debug("processing {}", userAuth); - Result result = userAuth.next(buffer); - switch(result) { + Result result = userAuth.next(buffer); + switch (result) { case Success: log.debug("succeeded with {}", userAuth); session.setAuthenticated(); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthAgent.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthAgent.java b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthAgent.java index 74e1935..e4eed68 100644 --- a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthAgent.java +++ b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthAgent.java @@ -98,7 +98,8 @@ public class UserAuthAgent extends AbstractUserAuth { log.info("Received SSH_MSG_USERAUTH_SUCCESS"); agent.close(); return Result.Success; - } if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) { + } + if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) { log.info("Received SSH_MSG_USERAUTH_FAILURE"); if (keys.hasNext()) { sendNextKey(keys.next().getFirst()); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthKeyboardInteractive.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthKeyboardInteractive.java b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthKeyboardInteractive.java index 947d125..666a88d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthKeyboardInteractive.java +++ b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthKeyboardInteractive.java @@ -18,11 +18,6 @@ */ package org.apache.sshd.deprecated; -import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_FAILURE; -import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_INFO_REQUEST; -import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_INFO_RESPONSE; -import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_SUCCESS; - import java.io.IOException; import java.util.Arrays; @@ -31,6 +26,11 @@ import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.SshConstants; import org.apache.sshd.common.util.buffer.Buffer; +import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_FAILURE; +import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_INFO_REQUEST; +import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_INFO_RESPONSE; +import static org.apache.sshd.common.SshConstants.SSH_MSG_USERAUTH_SUCCESS; + /** * Userauth with keyboard-interactive method. * @@ -81,7 +81,7 @@ public class UserAuthKeyboardInteractive extends AbstractUserAuth { if (num == 0) { rep = new String[0]; } else if (num == 1 && password != null && !echo[0] && prompt[0].toLowerCase().startsWith("password:")) { - rep = new String[] { password }; + rep = new String[]{password}; } else { UserInteraction ui = session.getFactoryManager().getUserInteraction(); if (ui != null) { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPassword.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPassword.java b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPassword.java index 26cefa4..d2149d4 100644 --- a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPassword.java +++ b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPassword.java @@ -54,7 +54,8 @@ public class UserAuthPassword extends AbstractUserAuth { if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) { log.debug("Received SSH_MSG_USERAUTH_SUCCESS"); return Result.Success; - } if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) { + } + if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) { log.debug("Received SSH_MSG_USERAUTH_FAILURE"); return Result.Failure; } else { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPublicKey.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPublicKey.java b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPublicKey.java index e90a33a..d977265 100644 --- a/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPublicKey.java +++ b/sshd-core/src/test/java/org/apache/sshd/deprecated/UserAuthPublicKey.java @@ -94,7 +94,8 @@ public class UserAuthPublicKey extends AbstractUserAuth { if (cmd == SshConstants.SSH_MSG_USERAUTH_SUCCESS) { log.debug("Received SSH_MSG_USERAUTH_SUCCESS"); return Result.Success; - } if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) { + } + if (cmd == SshConstants.SSH_MSG_USERAUTH_FAILURE) { log.debug("Received SSH_MSG_USERAUTH_FAILURE"); return Result.Failure; } else { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java index f57ac08..aa878c8 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/PasswordAuthenticatorTest.java @@ -53,21 +53,21 @@ public class PasswordAuthenticatorTest extends BaseTestSupport { } private void testStaticPasswordAuthenticator(StaticPasswordAuthenticator authenticator) throws Exception { - Method method = PasswordAuthenticator.class.getMethod("authenticate", String.class, String.class, ServerSession.class); - Object[] args = { getCurrentTestName(), getClass().getName(), null /* ServerSession */ }; - Object[] invArgs = new Object[args.length]; - Random rnd = new Random(System.nanoTime()); - boolean expected = authenticator.isAccepted(); - for (int index=0; index < Long.SIZE; index++) { - for (int j=0; j < args.length; j++) { + Method method = PasswordAuthenticator.class.getMethod("authenticate", String.class, String.class, ServerSession.class); + Object[] args = {getCurrentTestName(), getClass().getName(), null /* ServerSession */}; + Object[] invArgs = new Object[args.length]; + Random rnd = new Random(System.nanoTime()); + boolean expected = authenticator.isAccepted(); + for (int index = 0; index < Long.SIZE; index++) { + for (int j = 0; j < args.length; j++) { if (rnd.nextBoolean()) { invArgs[j] = args[j]; } else { invArgs[j] = null; } } - - Object result = method.invoke(authenticator, invArgs); + + Object result = method.invoke(authenticator, invArgs); assertTrue("No boolean result", result instanceof Boolean); assertEquals("Mismatched result for " + Arrays.toString(invArgs), expected, ((Boolean) result).booleanValue()); } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java index cbd5ac7..36889ee 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/PublickeyAuthenticatorTest.java @@ -56,26 +56,26 @@ public class PublickeyAuthenticatorTest extends BaseTestSupport { } private void testStaticPublickeyAuthenticator(StaticPublickeyAuthenticator authenticator) throws Exception { - Method method = PublickeyAuthenticator.class.getMethod("authenticate", String.class, PublicKey.class, ServerSession.class); - PublicKey key = Mockito.mock(PublicKey.class); + Method method = PublickeyAuthenticator.class.getMethod("authenticate", String.class, PublicKey.class, ServerSession.class); + PublicKey key = Mockito.mock(PublicKey.class); Mockito.when(key.getAlgorithm()).thenReturn(getCurrentTestName()); Mockito.when(key.getEncoded()).thenReturn(GenericUtils.EMPTY_BYTE_ARRAY); Mockito.when(key.getFormat()).thenReturn(getCurrentTestName()); - Object[] args = { getCurrentTestName(), key, null /* ServerSession */ }; - Object[] invArgs = new Object[args.length]; - Random rnd = new Random(System.nanoTime()); - boolean expected = authenticator.isAccepted(); - for (int index=0; index < Long.SIZE; index++) { - for (int j=0; j < args.length; j++) { + Object[] args = {getCurrentTestName(), key, null /* ServerSession */}; + Object[] invArgs = new Object[args.length]; + Random rnd = new Random(System.nanoTime()); + boolean expected = authenticator.isAccepted(); + for (int index = 0; index < Long.SIZE; index++) { + for (int j = 0; j < args.length; j++) { if (rnd.nextBoolean()) { invArgs[j] = args[j]; } else { invArgs[j] = null; } } - - Object result = method.invoke(authenticator, invArgs); + + Object result = method.invoke(authenticator, invArgs); assertTrue("No boolean result", result instanceof Boolean); assertEquals("Mismatched result for " + Arrays.toString(invArgs), expected, ((Boolean) result).booleanValue()); } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/ServerMain.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerMain.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerMain.java index 78dcc94..144ea0a 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerMain.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerMain.java @@ -22,6 +22,7 @@ package org.apache.sshd.server; /** * An activator for the {@link SshServer#main(String[])} - the reason it is * here is because the logging configuration is available only for test scope + * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public class ServerMain { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java index db3e706..a750200 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/ServerTest.java @@ -112,11 +112,12 @@ public class ServerTest extends BaseTestSupport { /** * Send bad password. The server should disconnect after a few attempts + * * @throws Exception */ @Test public void testFailAuthenticationWithWaitFor() throws Exception { - final int MAX_AUTH_REQUESTS=10; + final int MAX_AUTH_REQUESTS = 10; FactoryManagerUtils.updateProperty(sshd, ServerFactoryManager.MAX_AUTH_REQUESTS, MAX_AUTH_REQUESTS); client = SshClient.setUpDefaultClient(); @@ -125,15 +126,15 @@ public class ServerTest extends BaseTestSupport { ClientConnectionServiceFactory.INSTANCE )); client.start(); - - try(ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { int nbTrials = 0; int res = 0; while ((res & ClientSession.CLOSED) == 0) { - nbTrials ++; + nbTrials++; s.getService(ClientUserAuthServiceOld.class) - .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy")) - ; + .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy")) + ; res = s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 5000); if (res == ClientSession.TIMEOUT) { throw new TimeoutException(); @@ -147,7 +148,7 @@ public class ServerTest extends BaseTestSupport { @Test public void testFailAuthenticationWithFuture() throws Exception { - final int MAX_AUTH_REQUESTS=10; + final int MAX_AUTH_REQUESTS = 10; FactoryManagerUtils.updateProperty(sshd, ServerFactoryManager.MAX_AUTH_REQUESTS, MAX_AUTH_REQUESTS); client = SshClient.setUpDefaultClient(); @@ -156,15 +157,15 @@ public class ServerTest extends BaseTestSupport { ClientConnectionServiceFactory.INSTANCE )); client.start(); - try(ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { int nbTrials = 0; AuthFuture authFuture; do { nbTrials++; assertTrue(nbTrials < 100); authFuture = s.getService(ClientUserAuthServiceOld.class) - .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy")) - ; + .auth(new org.apache.sshd.deprecated.UserAuthPassword(s, "ssh-connection", "buggy")) + ; assertTrue("Authentication wait failed", authFuture.await(5000)); assertTrue("Authentication not done", authFuture.isDone()); assertFalse("Authentication unexpectedly successful", authFuture.isSuccess()); @@ -179,12 +180,12 @@ public class ServerTest extends BaseTestSupport { @Test public void testAuthenticationTimeout() throws Exception { - final int AUTH_TIMEOUT=5000; + final int AUTH_TIMEOUT = 5000; FactoryManagerUtils.updateProperty(sshd, FactoryManager.AUTH_TIMEOUT, AUTH_TIMEOUT); client = SshClient.setUpDefaultClient(); client.start(); - try(ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { int res = s.waitFor(ClientSession.CLOSED, 2 * AUTH_TIMEOUT); assertEquals("Session should be closed", ClientSession.CLOSED | ClientSession.WAIT_AUTH, res); } finally { @@ -196,7 +197,7 @@ public class ServerTest extends BaseTestSupport { public void testIdleTimeout() throws Exception { final CountDownLatch latch = new CountDownLatch(1); TestEchoShellFactory.TestEchoShell.latch = new CountDownLatch(1); - final int IDLE_TIMEOUT=2500; + final int IDLE_TIMEOUT = 2500; FactoryManagerUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, IDLE_TIMEOUT); sshd.getSessionFactory().addListener(new SessionListener() { @@ -204,10 +205,12 @@ public class ServerTest extends BaseTestSupport { public void sessionCreated(Session session) { System.out.println("Session created"); } + @Override public void sessionEvent(Session session, Event event) { System.out.println("Session event: " + event); } + @Override public void sessionClosed(Session session) { System.out.println("Session closed"); @@ -217,13 +220,13 @@ public class ServerTest extends BaseTestSupport { client = SshClient.setUpDefaultClient(); client.start(); - try(ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity("test"); s.auth().verify(5L, TimeUnit.SECONDS); - try(ChannelShell shell = s.createShellChannel(); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream()) { + try (ChannelShell shell = s.createShellChannel(); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream()) { shell.setOut(out); shell.setErr(err); shell.open().verify(9L, TimeUnit.SECONDS); @@ -240,17 +243,17 @@ public class ServerTest extends BaseTestSupport { /** * The scenario is the following: - * - create a command that sends continuous data to the client - * - the client does not read the data, filling the ssh window and the tcp socket - * - the server session becomes idle, but the ssh disconnect message can't be written - * - the server session is forcibly closed + * - create a command that sends continuous data to the client + * - the client does not read the data, filling the ssh window and the tcp socket + * - the server session becomes idle, but the ssh disconnect message can't be written + * - the server session is forcibly closed */ @Test public void testServerIdleTimeoutWithForce() throws Exception { final CountDownLatch latch = new CountDownLatch(1); sshd.setCommandFactory(new StreamCommand.Factory()); - + FactoryManagerUtils.updateProperty(sshd, FactoryManager.IDLE_TIMEOUT, 5000); FactoryManagerUtils.updateProperty(sshd, FactoryManager.DISCONNECT_TIMEOUT, 2000); sshd.getSessionFactory().addListener(new SessionListener() { @@ -274,27 +277,27 @@ public class ServerTest extends BaseTestSupport { client = SshClient.setUpDefaultClient(); client.start(); - try(ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity(getCurrentTestName()); s.auth().verify(5L, TimeUnit.SECONDS); - try(ChannelExec shell = s.createExecChannel("normal"); - // Create a pipe that will block reading when the buffer is full - PipedInputStream pis = new PipedInputStream(); - PipedOutputStream pos = new PipedOutputStream(pis)) { + try (ChannelExec shell = s.createExecChannel("normal"); + // 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().verify(5L, TimeUnit.SECONDS); - - try(AbstractSession serverSession = sshd.getActiveSessions().iterator().next(); - Channel channel = serverSession.getService(AbstractConnectionService.class).getChannels().iterator().next()) { + + try (AbstractSession serverSession = sshd.getActiveSessions().iterator().next(); + Channel channel = serverSession.getService(AbstractConnectionService.class).getChannels().iterator().next()) { while (channel.getRemoteWindow().getSize() > 0) { Thread.sleep(1); } - + LoggerFactory.getLogger(getClass()).info("Waiting for session idle timeouts"); - + long t0 = System.currentTimeMillis(); latch.await(1, TimeUnit.MINUTES); long t1 = System.currentTimeMillis(), diff = t1 - t0; @@ -315,8 +318,8 @@ public class ServerTest extends BaseTestSupport { protected AbstractSession createSession(IoSession ioSession) throws Exception { return new ClientSessionImpl(client, ioSession) { @Override - protected Map<KexProposalOption,String> createProposal(String hostKeyTypes) { - Map<KexProposalOption,String> proposal = super.createProposal(hostKeyTypes); + protected Map<KexProposalOption, String> createProposal(String hostKeyTypes) { + Map<KexProposalOption, String> proposal = super.createProposal(hostKeyTypes); proposal.put(KexProposalOption.S2CLANG, "en-US"); proposal.put(KexProposalOption.C2SLANG, "en-US"); return proposal; @@ -325,7 +328,7 @@ public class ServerTest extends BaseTestSupport { } }); client.start(); - try(ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.close(false); } finally { client.stop(); @@ -334,49 +337,49 @@ public class ServerTest extends BaseTestSupport { @Test public void testKexCompletedEvent() throws Exception { - final AtomicInteger serverEventCount=new AtomicInteger(0); + final AtomicInteger serverEventCount = new AtomicInteger(0); sshd.getSessionFactory().addListener(new SessionListener() { - @Override - public void sessionCreated(Session session) { - // ignored - } - - @Override - public void sessionEvent(Session session, Event event) { - if (event == Event.KexCompleted) { - serverEventCount.incrementAndGet(); - } - } - - @Override - public void sessionClosed(Session session) { - // ignored - } - }); + @Override + public void sessionCreated(Session session) { + // ignored + } + + @Override + public void sessionEvent(Session session, Event event) { + if (event == Event.KexCompleted) { + serverEventCount.incrementAndGet(); + } + } + + @Override + public void sessionClosed(Session session) { + // ignored + } + }); client = SshClient.setUpDefaultClient(); client.start(); - final AtomicInteger clientEventCount=new AtomicInteger(0); + final AtomicInteger clientEventCount = new AtomicInteger(0); client.getSessionFactory().addListener(new SessionListener() { - @Override - public void sessionCreated(Session session) { - // ignored - } - - @Override - public void sessionEvent(Session session, Event event) { - if (event == Event.KexCompleted) { - clientEventCount.incrementAndGet(); - } - } - - @Override - public void sessionClosed(Session session) { - // ignored - } - }); - - try(ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + @Override + public void sessionCreated(Session session) { + // ignored + } + + @Override + public void sessionEvent(Session session, Event event) { + if (event == Event.KexCompleted) { + clientEventCount.incrementAndGet(); + } + } + + @Override + public void sessionClosed(Session session) { + // ignored + } + }); + + try (ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity("test"); s.auth().verify(5L, TimeUnit.SECONDS); assertEquals("Mismatched client events count", 1, clientEventCount.get()); @@ -389,9 +392,10 @@ public class ServerTest extends BaseTestSupport { @Test // see https://issues.apache.org/jira/browse/SSHD-456 public void testServerStillListensIfSessionListenerThrowsException() throws InterruptedException { - final Map<String,SocketAddress> eventsMap = new TreeMap<String, SocketAddress>(String.CASE_INSENSITIVE_ORDER); + final Map<String, SocketAddress> eventsMap = new TreeMap<String, SocketAddress>(String.CASE_INSENSITIVE_ORDER); sshd.getSessionFactory().addListener(new SessionListener() { - private final Logger log=LoggerFactory.getLogger(getClass()); + private final Logger log = LoggerFactory.getLogger(getClass()); + @Override public void sessionCreated(Session session) { throwException("SessionCreated", session); @@ -406,51 +410,51 @@ public class ServerTest extends BaseTestSupport { public void sessionClosed(Session session) { throwException("SessionClosed", session); } - + private void throwException(String phase, Session session) { - IoSession ioSession = session.getIoSession(); - SocketAddress addr = ioSession.getRemoteAddress(); + IoSession ioSession = session.getIoSession(); + SocketAddress addr = ioSession.getRemoteAddress(); synchronized (eventsMap) { if (eventsMap.put(phase, addr) != null) { return; // already generated an event for this phase } } - + RuntimeException e = new RuntimeException("Synthetic exception at phase=" + phase + ": " + addr); log.info(e.getMessage()); throw e; } }); - + client = SshClient.setUpDefaultClient(); client.start(); - - int curCount=0; - for (int retryCount=0; retryCount < Byte.SIZE; retryCount++){ - synchronized(eventsMap) { - if ((curCount=eventsMap.size()) >= 3) { + + int curCount = 0; + for (int retryCount = 0; retryCount < Byte.SIZE; retryCount++) { + synchronized (eventsMap) { + if ((curCount = eventsMap.size()) >= 3) { return; } } - + try { - try(ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect("test", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity("test"); s.auth().verify(5L, TimeUnit.SECONDS); } - - synchronized(eventsMap) { + + synchronized (eventsMap) { assertTrue("Unexpected premature success: " + eventsMap, eventsMap.size() >= 3); } - } catch(IOException e) { + } catch (IOException e) { // expected - ignored - synchronized(eventsMap) { - int nextCount=eventsMap.size(); + synchronized (eventsMap) { + int nextCount = eventsMap.size(); assertTrue("No session event generated", nextCount > curCount); } } } - + fail("No success to authenticate"); } @@ -458,55 +462,55 @@ public class ServerTest extends BaseTestSupport { public void testEnvironmentVariablesPropagationToServer() throws Exception { final AtomicReference<Environment> envHolder = new AtomicReference<Environment>(null); sshd.setCommandFactory(new CommandFactory() { - @Override - public Command createCommand(final String command) { - ValidateUtils.checkTrue(String.CASE_INSENSITIVE_ORDER.compare(command, getCurrentTestName()) == 0, "Unexpected command: %s", command); - - return new Command() { - private ExitCallback cb; - - @Override - public void setOutputStream(OutputStream out) { - // ignored - } - - @Override - public void setInputStream(InputStream in) { - // ignored - } - - @Override - public void setExitCallback(ExitCallback callback) { - cb = callback; - } - - @Override - public void setErrorStream(OutputStream err) { - // ignored - } - - @Override - public void destroy() { - // ignored - } - - @Override - public void start(Environment env) throws IOException { - if (envHolder.getAndSet(env) != null) { - throw new StreamCorruptedException("Multiple starts for command=" + command); - } - - cb.onExit(0, command); - } - }; + @Override + public Command createCommand(final String command) { + ValidateUtils.checkTrue(String.CASE_INSENSITIVE_ORDER.compare(command, getCurrentTestName()) == 0, "Unexpected command: %s", command); + + return new Command() { + private ExitCallback cb; + + @Override + public void setOutputStream(OutputStream out) { + // ignored } - }); + + @Override + public void setInputStream(InputStream in) { + // ignored + } + + @Override + public void setExitCallback(ExitCallback callback) { + cb = callback; + } + + @Override + public void setErrorStream(OutputStream err) { + // ignored + } + + @Override + public void destroy() { + // ignored + } + + @Override + public void start(Environment env) throws IOException { + if (envHolder.getAndSet(env) != null) { + throw new StreamCorruptedException("Multiple starts for command=" + command); + } + + cb.onExit(0, command); + } + }; + } + }); @SuppressWarnings("synthetic-access") - Map<String,String> expected = new TreeMap<String,String>(String.CASE_INSENSITIVE_ORDER) { + Map<String, String> expected = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) { private static final long serialVersionUID = 1L; // we're not serializing it - + { put("test", getCurrentTestName()); put("port", Integer.toString(port)); @@ -516,17 +520,17 @@ public class ServerTest extends BaseTestSupport { client = SshClient.setUpDefaultClient(); client.start(); - try(ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity(getCurrentTestName()); s.auth().verify(5L, TimeUnit.SECONDS); - try(ChannelExec shell = s.createExecChannel(getCurrentTestName())) { - for (Map.Entry<String,String> ee : expected.entrySet()) { + try (ChannelExec shell = s.createExecChannel(getCurrentTestName())) { + for (Map.Entry<String, String> ee : expected.entrySet()) { shell.setEnv(ee.getKey(), ee.getValue()); } shell.open().verify(5L, TimeUnit.SECONDS); shell.waitFor(ClientChannel.CLOSED, TimeUnit.SECONDS.toMillis(17L)); - + Integer status = shell.getExitStatus(); assertNotNull("No exit status", status); assertEquals("Bad exit status", 0, status.intValue()); @@ -534,10 +538,10 @@ public class ServerTest extends BaseTestSupport { Environment cmdEnv = envHolder.get(); assertNotNull("No environment set", cmdEnv); - - Map<String,String> vars = cmdEnv.getEnv(); + + Map<String, String> vars = cmdEnv.getEnv(); assertTrue("Mismatched vars count", GenericUtils.size(vars) >= GenericUtils.size(expected)); - for (Map.Entry<String,String> ee : expected.entrySet()) { + for (Map.Entry<String, String> ee : expected.entrySet()) { String key = ee.getKey(), expValue = ee.getValue(), actValue = vars.get(key); assertEquals("Mismatched value for " + key, expValue, actValue); } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/SshServerMain.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/SshServerMain.java b/sshd-core/src/test/java/org/apache/sshd/server/SshServerMain.java index c5d9f0e..ffb3d3d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/SshServerMain.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/SshServerMain.java @@ -22,6 +22,7 @@ package org.apache.sshd.server; /** * Just a test class used to invoke {@link SshServer#main(String[])} in * order to have logging - which is in {@code test} scope + * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public class SshServerMain { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java b/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java index 8b56414..7890c4d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/SshServerTest.java @@ -38,7 +38,7 @@ public class SshServerTest extends BaseTestSupport { @Test public void stopMethodShouldBeIdempotent() throws Exception { - try(SshServer sshd = new SshServer()) { + try (SshServer sshd = new SshServer()) { sshd.stop(); sshd.stop(); sshd.stop(); @@ -49,12 +49,12 @@ public class SshServerTest extends BaseTestSupport { public void testExecutorShutdownFalse() throws Exception { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - try(SshServer sshd = createTestServer()) { + try (SshServer sshd = createTestServer()) { sshd.setScheduledExecutorService(executorService); - + sshd.start(); sshd.stop(); - + assertFalse(executorService.isShutdown()); executorService.shutdownNow(); } @@ -64,24 +64,24 @@ public class SshServerTest extends BaseTestSupport { public void testExecutorShutdownTrue() throws Exception { ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor(); - try(SshServer sshd = createTestServer()) { + try (SshServer sshd = createTestServer()) { sshd.setScheduledExecutorService(executorService, true); - + sshd.start(); sshd.stop(); - + assertTrue(executorService.isShutdown()); } } @Test public void testDynamicPort() throws Exception { - try(SshServer sshd = createTestServer()) { + try (SshServer sshd = createTestServer()) { sshd.setHost("localhost"); sshd.start(); - + assertNotEquals(0, sshd.getPort()); - + sshd.stop(); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java b/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java index 00f4fb9..e38c413 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/channel/ChannelSessionTest.java @@ -45,7 +45,7 @@ public class ChannelSessionTest extends BaseTestSupport { final Buffer buffer = new ByteArrayBuffer(); buffer.putInt(1234); - try(ChannelSession channelSession = new ChannelSession()) { + try (ChannelSession channelSession = new ChannelSession()) { channelSession.asyncOut = new ChannelAsyncOutputStream(new BogusChannel(), (byte) 0) { @SuppressWarnings("synthetic-access") @Override http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/command/ScpCommandFactoryTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/command/ScpCommandFactoryTest.java b/sshd-core/src/test/java/org/apache/sshd/server/command/ScpCommandFactoryTest.java index f66cdc5..7cea385 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/command/ScpCommandFactoryTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/command/ScpCommandFactoryTest.java @@ -44,7 +44,7 @@ public class ScpCommandFactoryTest extends BaseTestSupport { */ @Test public void testBuilderDefaultFactoryValues() { - ScpCommandFactory factory = new ScpCommandFactory.Builder().build(); + ScpCommandFactory factory = new ScpCommandFactory.Builder().build(); assertNull("Mismatched delegate", factory.getDelegateCommandFactory()); assertNull("Mismatched executor", factory.getExecutorService()); assertEquals("Mismatched send size", ScpHelper.MIN_SEND_BUFFER_SIZE, factory.getSendBufferSize()); @@ -57,16 +57,16 @@ public class ScpCommandFactoryTest extends BaseTestSupport { */ @Test public void testBuilderCorrectlyInitializesFactory() { - CommandFactory delegate = dummyFactory(); - ExecutorService service = dummyExecutor(); - int receiveSize = Short.MAX_VALUE, sendSize = receiveSize + Long.SIZE; - ScpCommandFactory factory = new ScpCommandFactory.Builder() - .withDelegate(delegate) - .withExecutorService(service) - .withSendBufferSize(sendSize) - .withReceiveBufferSize(receiveSize) - .withShutdownOnExit(true) - .build(); + CommandFactory delegate = dummyFactory(); + ExecutorService service = dummyExecutor(); + int receiveSize = Short.MAX_VALUE, sendSize = receiveSize + Long.SIZE; + ScpCommandFactory factory = new ScpCommandFactory.Builder() + .withDelegate(delegate) + .withExecutorService(service) + .withSendBufferSize(sendSize) + .withReceiveBufferSize(receiveSize) + .withShutdownOnExit(true) + .build(); assertSame("Mismatched delegate", delegate, factory.getDelegateCommandFactory()); assertSame("Mismatched executor", service, factory.getExecutorService()); assertEquals("Mismatched send size", sendSize, factory.getSendBufferSize()); @@ -76,26 +76,26 @@ public class ScpCommandFactoryTest extends BaseTestSupport { /** * <UL> - * <LI> - * Make sure the builder returns new instances on every call to - * {@link ScpCommandFactory.Builder#build()} method - * </LI> - * - * <LI> - * Make sure values are preserved between successive invocations - * of the {@link ScpCommandFactory.Builder#build()} method - * </LI> + * <LI> + * Make sure the builder returns new instances on every call to + * {@link ScpCommandFactory.Builder#build()} method + * </LI> + * <p/> + * <LI> + * Make sure values are preserved between successive invocations + * of the {@link ScpCommandFactory.Builder#build()} method + * </LI> * </UL */ @Test public void testBuilderUniqueInstance() { - ScpCommandFactory.Builder builder = new ScpCommandFactory.Builder(); - ScpCommandFactory f1 = builder.withDelegate(dummyFactory()).build(); - ScpCommandFactory f2 = builder.build(); + ScpCommandFactory.Builder builder = new ScpCommandFactory.Builder(); + ScpCommandFactory f1 = builder.withDelegate(dummyFactory()).build(); + ScpCommandFactory f2 = builder.build(); assertNotSame("No new instance built", f1, f2); assertSame("Mismatched delegate", f1.getDelegateCommandFactory(), f2.getDelegateCommandFactory()); - - ScpCommandFactory f3=builder.withDelegate(dummyFactory()).build(); + + ScpCommandFactory f3 = builder.withDelegate(dummyFactory()).build(); assertNotSame("Delegate not changed", f1.getDelegateCommandFactory(), f3.getDelegateCommandFactory()); } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeyEntryTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeyEntryTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeyEntryTest.java index ceef2eb..5dd1feb 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeyEntryTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeyEntryTest.java @@ -55,7 +55,7 @@ public class AuthorizedKeyEntryTest extends BaseTestSupport { public void testReadAuthorizedKeysFile() throws Exception { URL url = getClass().getResource(AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME); assertNotNull("Missing " + AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME + " resource", url); - + runAuthorizedKeysTests(AuthorizedKeyEntry.readAuthorizedKeys(url)); } @@ -63,22 +63,22 @@ public class AuthorizedKeyEntryTest extends BaseTestSupport { public void testEncodePublicKeyEntry() throws Exception { URL url = getClass().getResource(AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME); assertNotNull("Missing " + AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME + " resource", url); - - StringBuilder sb = new StringBuilder(Byte.MAX_VALUE); - try(BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { + + StringBuilder sb = new StringBuilder(Byte.MAX_VALUE); + try (BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { for (String line = rdr.readLine(); line != null; line = rdr.readLine()) { line = GenericUtils.trimToEmpty(line); if (GenericUtils.isEmpty(line) || (line.charAt(0) == PublicKeyEntry.COMMENT_CHAR)) { continue; } - + int pos = line.indexOf(' '); String keyType = line.substring(0, pos), data = line; // assume this happens if starts with login options if (KeyUtils.getPublicKeyEntryDecoder(keyType) == null) { data = line.substring(pos + 1).trim(); } - + AuthorizedKeyEntry entry = AuthorizedKeyEntry.parseAuthorizedKeyEntry(data); if (sb.length() > 0) { sb.setLength(0); @@ -86,7 +86,7 @@ public class AuthorizedKeyEntryTest extends BaseTestSupport { PublicKey key = entry.appendPublicKey(sb); assertNotNull("No key for line=" + line, key); - + String encoded = sb.toString(); assertEquals("Mismatched encoded form for line=" + line, data, encoded); } @@ -118,15 +118,15 @@ public class AuthorizedKeyEntryTest extends BaseTestSupport { private static Collection<AuthorizedKeyEntry> testReadAuthorizedKeys(Collection<AuthorizedKeyEntry> entries) throws Exception { assertFalse("No entries read", GenericUtils.isEmpty(entries)); - + Exception err = null; for (AuthorizedKeyEntry entry : entries) { try { ValidateUtils.checkNotNull(entry.resolvePublicKey(), "No public key resolved from %s", entry); - } catch(Exception e) { + } catch (Exception e) { System.err.append("Failed (").append(e.getClass().getSimpleName()).append(')') - .append(" to resolve key of entry=").append(entry.toString()) - .append(": ").println(e.getMessage()); + .append(" to resolve key of entry=").append(entry.toString()) + .append(": ").println(e.getMessage()); err = e; } } @@ -134,17 +134,17 @@ public class AuthorizedKeyEntryTest extends BaseTestSupport { if (err != null) { throw err; } - + return entries; } - + private PublickeyAuthenticator testAuthorizedKeysAuth(Collection<AuthorizedKeyEntry> entries) throws Exception { - Collection<PublicKey> keySet = AuthorizedKeyEntry.resolveAuthorizedKeys(entries); + Collection<PublicKey> keySet = AuthorizedKeyEntry.resolveAuthorizedKeys(entries); PublickeyAuthenticator auth = AuthorizedKeyEntry.fromAuthorizedEntries(entries); for (PublicKey key : keySet) { assertTrue("Failed to authenticate with key=" + key.getAlgorithm(), auth.authenticate(getCurrentTestName(), key, null)); } - + return auth; } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java index b7b81cd..f32810b 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/AuthorizedKeysAuthenticatorTest.java @@ -56,27 +56,27 @@ public class AuthorizedKeysAuthenticatorTest extends BaseTestSupport { @Test public void testAutomaticReload() throws Exception { - final Path file=new File(new File(detectTargetFolder(), TEMP_SUBFOLDER_NAME), getCurrentTestName()).toPath(); + final Path file = new File(new File(detectTargetFolder(), TEMP_SUBFOLDER_NAME), getCurrentTestName()).toPath(); if (Files.exists(file)) { Files.delete(file); } final AtomicInteger reloadCount = new AtomicInteger(0); - PublickeyAuthenticator auth = new AuthorizedKeysAuthenticator(file) { - @Override - protected Collection<AuthorizedKeyEntry> reloadAuthorizedKeys(Path path, String username, ServerSession session) throws IOException { - assertSame("Mismatched reload path", file, path); - reloadCount.incrementAndGet(); - return super.reloadAuthorizedKeys(path, username, session); - } - }; + PublickeyAuthenticator auth = new AuthorizedKeysAuthenticator(file) { + @Override + protected Collection<AuthorizedKeyEntry> reloadAuthorizedKeys(Path path, String username, ServerSession session) throws IOException { + assertSame("Mismatched reload path", file, path); + reloadCount.incrementAndGet(); + return super.reloadAuthorizedKeys(path, username, session); + } + }; assertFalse("Unexpected authentication success for missing file " + file, auth.authenticate(getCurrentTestName(), Mockito.mock(PublicKey.class), null)); URL url = getClass().getResource(AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME); assertNotNull("Missing " + AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME + " resource", url); List<String> lines = new ArrayList<String>(); - try(BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { + try (BufferedReader rdr = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { for (String l = rdr.readLine(); l != null; l = rdr.readLine()) { l = GenericUtils.trimToEmpty(l); // filter out empty and comment lines @@ -89,19 +89,19 @@ public class AuthorizedKeysAuthenticatorTest extends BaseTestSupport { } assertHierarchyTargetFolderExists(file.getParent()); - + final String EOL = System.getProperty("line.separator"); Random rnd = new Random(System.nanoTime()); List<String> removed = new ArrayList<String>(lines.size()); - for ( ; ; ) { - try(Writer w = Files.newBufferedWriter(file)) { + for (; ; ) { + try (Writer w = Files.newBufferedWriter(file)) { for (String l : lines) { w.append(l).append(EOL); } } Collection<AuthorizedKeyEntry> entries = AuthorizedKeyEntry.readAuthorizedKeys(file); - Collection<PublicKey> keySet = AuthorizedKeyEntry.resolveAuthorizedKeys(entries); + Collection<PublicKey> keySet = AuthorizedKeyEntry.resolveAuthorizedKeys(entries); reloadCount.set(0); for (PublicKey k : keySet) { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java index 40b92dc..4f3ab04 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/DefaultAuthorizedKeysAuthenticatorTest.java @@ -46,20 +46,20 @@ public class DefaultAuthorizedKeysAuthenticatorTest extends BaseTestSupport { @Test public void testUsernameValidation() throws Exception { - Path file=new File(new File(detectTargetFolder(), TEMP_SUBFOLDER_NAME), getCurrentTestName()).toPath(); + Path file = new File(new File(detectTargetFolder(), TEMP_SUBFOLDER_NAME), getCurrentTestName()).toPath(); URL url = getClass().getResource(AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME); assertNotNull("Missing " + AuthorizedKeyEntry.STD_AUTHORIZED_KEYS_FILENAME + " resource", url); - try(InputStream input = url.openStream(); - OutputStream output = Files.newOutputStream(file)) { + try (InputStream input = url.openStream(); + OutputStream output = Files.newOutputStream(file)) { IoUtils.copy(input, output); } - + Collection<AuthorizedKeyEntry> entries = AuthorizedKeyEntry.readAuthorizedKeys(file); - Collection<PublicKey> keySet = AuthorizedKeyEntry.resolveAuthorizedKeys(entries); + Collection<PublicKey> keySet = AuthorizedKeyEntry.resolveAuthorizedKeys(entries); PublickeyAuthenticator auth = new DefaultAuthorizedKeysAuthenticator(file, false); String thisUser = System.getProperty("user.name"); - for (String username : new String[] { null, "", thisUser, getClass().getName() + "#" + getCurrentTestName() }) { + for (String username : new String[]{null, "", thisUser, getClass().getName() + "#" + getCurrentTestName()}) { boolean expected = thisUser.equals(username); for (PublicKey key : keySet) { boolean actual = auth.authenticate(username, key, null); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java index f8cea3d..6a7c2ae 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/config/keys/ServerIdentityTest.java @@ -53,7 +53,7 @@ public class ServerIdentityTest extends BaseTestSupport { @Test public void testLoadServerIdentities() throws Exception { Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); - + Path resFolder = getClassResourcesFolder(TEST_SUBFOLDER, getClass()).toPath(); Collection<Path> paths = new ArrayList<Path>(BuiltinIdentities.VALUES.size()); LinkOption[] options = IoUtils.getLinkOptions(false); @@ -65,7 +65,7 @@ public class ServerIdentityTest extends BaseTestSupport { System.out.println("Skip non-existing identity file " + file); continue; } - + if (!type.isSupported()) { System.out.println("Skip unsupported identity file " + file); continue; @@ -74,13 +74,13 @@ public class ServerIdentityTest extends BaseTestSupport { paths.add(file); expected.add(type); } - + Properties props = new Properties(); props.setProperty(ServerIdentity.HOST_KEY_CONFIG_PROP, GenericUtils.join(paths, ',')); - - Map<String,KeyPair> ids = ServerIdentity.loadIdentities(props, options); + + Map<String, KeyPair> ids = ServerIdentity.loadIdentities(props, options); assertEquals("Mismatched loaded ids count", GenericUtils.size(paths), GenericUtils.size(ids)); - + Collection<KeyPair> pairs = new ArrayList<KeyPair>(ids.size()); for (BuiltinIdentities type : BuiltinIdentities.VALUES) { if (expected.contains(type)) { @@ -89,7 +89,7 @@ public class ServerIdentityTest extends BaseTestSupport { pairs.add(kp); } } - + KeyPairProvider provider = IdentityUtils.createKeyPairProvider(ids, true /* supported only */); assertNotNull("No provider generated", provider); @@ -97,7 +97,7 @@ public class ServerIdentityTest extends BaseTestSupport { for (KeyPair kp : keys) { assertTrue("Unexpected loaded key: " + kp, pairs.remove(kp)); } - + assertEquals("Not all pairs listed", 0, pairs.size()); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java b/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java index 0062688..ff9fd27 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/jaas/JaasPasswordAuthenticatorTest.java @@ -18,10 +18,6 @@ */ package org.apache.sshd.server.jaas; -import java.io.IOException; -import java.util.HashMap; -import java.util.Map; - import javax.security.auth.Subject; import javax.security.auth.callback.Callback; import javax.security.auth.callback.CallbackHandler; @@ -32,6 +28,9 @@ import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginException; import javax.security.auth.spi.LoginModule; +import java.io.IOException; +import java.util.HashMap; +import java.util.Map; import org.apache.sshd.util.BaseTestSupport; import org.junit.After; @@ -53,12 +52,13 @@ public class JaasPasswordAuthenticatorTest extends BaseTestSupport { Configuration config = new Configuration() { @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { - return new AppConfigurationEntry[] { + return new AppConfigurationEntry[]{ new AppConfigurationEntry(DummyLoginModule.class.getName(), - AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, - new HashMap<String,Object>()) + AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, + new HashMap<String, Object>()) }; } + @Override public void refresh() { // ignored http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java index ece0710..9378d1a 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java @@ -75,12 +75,12 @@ public class PEMGeneratorHostKeyProviderTest extends BaseTestSupport { } private File testPEMGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) { - File path = initKeyFileLocation(algorithm); + File path = initKeyFileLocation(algorithm); KeyPair kpWrite = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); assertTrue("Key file not generated: " + path.getAbsolutePath(), path.exists()); - KeyPair kpRead = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); - PublicKey pubWrite = kpWrite.getPublic(), pubRead = kpRead.getPublic(); + KeyPair kpRead = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); + PublicKey pubWrite = kpWrite.getPublic(), pubRead = kpRead.getPublic(); if (pubWrite instanceof ECPublicKey) { // The algorithm is reported as ECDSA instead of EC assertECPublicKeyEquals("Mismatched EC public key", ECPublicKey.class.cast(pubWrite), ECPublicKey.class.cast(pubRead)); @@ -105,8 +105,8 @@ public class PEMGeneratorHostKeyProviderTest extends BaseTestSupport { } private static KeyPair validateKeyPairProvider(KeyPairProvider provider, String keyType) { - Iterable<String> types=provider.getKeyTypes(); - KeyPair kp=null; + Iterable<String> types = provider.getKeyTypes(); + KeyPair kp = null; for (String type : types) { if (keyType.equals(type)) { kp = provider.loadKey(keyType); @@ -114,7 +114,7 @@ public class PEMGeneratorHostKeyProviderTest extends BaseTestSupport { break; } } - + assertNotNull("Expected key type not found: " + keyType, kp); return kp; } @@ -129,7 +129,7 @@ public class PEMGeneratorHostKeyProviderTest extends BaseTestSupport { if (path.exists()) { assertTrue("Failed to delete test key file: " + path.getAbsolutePath(), path.delete()); } - + return path; } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java index a5f6edd..4f9198f 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java @@ -54,7 +54,7 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport { Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); testSimpleGeneratorHostKeyProvider("EC", KeyPairProvider.ECDSA_SHA2_NISTP256, -1, new ECGenParameterSpec("prime256v1")); } - + @Test public void testEC_NISTP384() { Assume.assumeTrue("BouncyCastle not registered", SecurityUtils.isBouncyCastleRegistered()); @@ -68,7 +68,7 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport { } private File testSimpleGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) { - File path = initKeyFileLocation(algorithm); + File path = initKeyFileLocation(algorithm); KeyPair kpWrite = invokeSimpleGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec); assertTrue("Key file not generated: " + path.getAbsolutePath(), path.exists()); @@ -88,13 +88,13 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport { if (keySpec != null) { provider.setKeySpec(keySpec); } - + return validateKeyPairProvider(provider, keyType); } private static KeyPair validateKeyPairProvider(KeyPairProvider provider, String keyType) { - Iterable<String> types=provider.getKeyTypes(); - KeyPair kp=null; + Iterable<String> types = provider.getKeyTypes(); + KeyPair kp = null; for (String type : types) { if (keyType.equals(type)) { kp = provider.loadKey(keyType); @@ -102,7 +102,7 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport { break; } } - + assertNotNull("Expected key type not found: " + keyType, kp); return kp; } @@ -117,7 +117,7 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport { if (path.exists()) { assertTrue("Failed to delete test key file: " + path.getAbsolutePath(), path.delete()); } - + return path; } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 ac1333a..a5ba369 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 @@ -37,9 +37,9 @@ public class InvertedShellWrapperTest extends BaseTestSupport { public void testStreamsAreFlushedBeforeClosing() throws Exception { BogusInvertedShell shell = newShell("out", "err"); shell.setAlive(false); - try(ByteArrayInputStream in = new ByteArrayInputStream("in".getBytes(StandardCharsets.UTF_8)); - ByteArrayOutputStream out = new ByteArrayOutputStream(50); - ByteArrayOutputStream err = new ByteArrayOutputStream()) { + try (ByteArrayInputStream in = new ByteArrayInputStream("in".getBytes(StandardCharsets.UTF_8)); + ByteArrayOutputStream out = new ByteArrayOutputStream(50); + ByteArrayOutputStream err = new ByteArrayOutputStream()) { InvertedShellWrapper wrapper = new InvertedShellWrapper(shell); wrapper.setInputStream(in); @@ -47,9 +47,9 @@ public class InvertedShellWrapperTest extends BaseTestSupport { 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()); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemFactoryTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemFactoryTest.java b/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemFactoryTest.java index 7a251ea..a2ad7f6 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemFactoryTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SftpSubsystemFactoryTest.java @@ -21,8 +21,6 @@ package org.apache.sshd.server.subsystem.sftp; import java.util.concurrent.ExecutorService; -import org.apache.sshd.server.subsystem.sftp.SftpSubsystemFactory; -import org.apache.sshd.server.subsystem.sftp.UnsupportedAttributePolicy; import org.apache.sshd.util.BaseTestSupport; import org.junit.FixMethodOrder; import org.junit.Test; http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SshFsMounter.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SshFsMounter.java b/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SshFsMounter.java index 11b97a6..9f3c598 100644 --- a/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SshFsMounter.java +++ b/sshd-core/src/test/java/org/apache/sshd/server/subsystem/sftp/SshFsMounter.java @@ -60,6 +60,7 @@ import org.apache.sshd.util.Utils; /** * A basic implementation to allow remote mounting of the local file system via SFTP + * * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> */ public class SshFsMounter { @@ -86,7 +87,7 @@ public class SshFsMounter { if (GenericUtils.isEmpty(c)) { continue; } - + args.add(c); } } else { @@ -117,10 +118,10 @@ public class SshFsMounter { } else { throw new UnsupportedOperationException("Unknown command"); } - + log.info("run(" + username + ")[" + command + "] end"); callback.onExit(0); - } catch(Exception e) { + } catch (Exception e) { log.error("run(" + username + ")[" + command + "] " + e.getClass().getSimpleName() + ": " + e.getMessage(), e); stderr.append(e.getClass().getSimpleName()).append(": ").println(e.getMessage()); callback.onExit((-1), e.toString()); @@ -171,7 +172,7 @@ public class SshFsMounter { stdout = null; } } - + if (stderr != null) { try { log.info("destroy(" + username + ")[" + command + "] close stderr"); @@ -181,20 +182,20 @@ public class SshFsMounter { stderr = null; } } - + if (stdin != null) { try { log.info("destroy(" + username + ")[" + command + "] close stdin"); stdin.close(); log.info("destroy(" + username + ")[" + command + "] stdin closed"); - } catch(IOException e) { + } catch (IOException e) { log.warn("destroy(" + username + ")[" + command + "] failed (" + e.getClass().getSimpleName() + ") to close stdin: " + e.getMessage()); } finally { stdin = null; } } } - + private void stopCommand() { if ((future != null) && (!future.isDone())) { try { @@ -205,7 +206,7 @@ public class SshFsMounter { future = null; } } - + if ((executor != null) && (!executor.isShutdown())) { try { log.info("stopCommand(" + username + ")[" + command + "] shutdown executor"); @@ -230,7 +231,7 @@ public class SshFsMounter { return new MounterCommand(command); } } - + public static void main(String[] args) throws Exception { int port = SshConfigFileReader.DEFAULT_PORT; boolean error = false; @@ -250,7 +251,7 @@ public class SshFsMounter { System.err.println("option requires an argument: " + argName); break; } - + String provider = args[++i]; if ("mina".equals(provider)) { System.setProperty(IoServiceFactory.class.getName(), MinaServiceFactory.class.getName()); @@ -291,9 +292,9 @@ public class SshFsMounter { } System.err.println("Starting SSHD on port " + port); - + SshServer sshd = SshServer.setUpDefaultServer(); - Map<String,Object> props = sshd.getProperties(); + Map<String, Object> props = sshd.getProperties(); // FactoryManagerUtils.updateProperty(props, ServerFactoryManager.WELCOME_BANNER, "Welcome to SSH-FS Mounter\n"); props.putAll(options); sshd.setPort(port); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java b/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java index 1ae01fc..53e4d8c 100644 --- a/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/spring/SpringConfigTest.java @@ -21,6 +21,8 @@ package org.apache.sshd.spring; import java.io.OutputStream; import java.nio.charset.StandardCharsets; +import com.jcraft.jsch.Channel; +import com.jcraft.jsch.JSch; import org.apache.sshd.common.util.OsUtils; import org.apache.sshd.server.SshServer; import org.apache.sshd.util.BaseTestSupport; @@ -33,9 +35,6 @@ import org.junit.Test; import org.junit.runners.MethodSorters; import org.springframework.context.support.ClassPathXmlApplicationContext; -import com.jcraft.jsch.Channel; -import com.jcraft.jsch.JSch; - /** * Test for spring based configuration. * @@ -74,13 +73,13 @@ public class SpringConfigTest extends BaseTestSupport { com.jcraft.jsch.Session s = sch.getSession(getCurrentTestName(), "localhost", port); s.setUserInfo(new SimpleUserInfo(getCurrentTestName())); s.connect(); - + try { Channel c = s.openChannel("shell"); c.connect(); - + String command = OsUtils.isWin32() ? "dir" : "ls"; - try(OutputStream os = c.getOutputStream()) { + try (OutputStream os = c.getOutputStream()) { os.write(command.getBytes(StandardCharsets.UTF_8)); os.flush(); Thread.sleep(100);
