http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/UnixDateFormat.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/UnixDateFormat.java b/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/UnixDateFormat.java new file mode 100644 index 0000000..902556b --- /dev/null +++ b/sshd-core/src/main/java/org/apache/sshd/server/subsystem/sftp/UnixDateFormat.java @@ -0,0 +1,97 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.sshd.server.subsystem.sftp; + +import java.nio.file.attribute.FileTime; +import java.util.Arrays; +import java.util.Calendar; +import java.util.Collections; +import java.util.GregorianCalendar; +import java.util.List; + +/** + * @author <a href="mailto:[email protected]">Apache MINA SSHD Project</a> + */ +final class UnixDateFormat { + + private static final List<String> MONTHS = + Collections.unmodifiableList(Arrays.asList( + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" + )); + + private UnixDateFormat() { + throw new UnsupportedOperationException("No instance allowed"); + } + + /** + * Get unix style date string. + */ + public static String getUnixDate(FileTime time) { + return getUnixDate(time != null ? time.toMillis() : -1); + } + + public static String getUnixDate(long millis) { + if (millis < 0) { + return "------------"; + } + + StringBuilder sb = new StringBuilder(16); + Calendar cal = new GregorianCalendar(); + cal.setTimeInMillis(millis); + + // month + sb.append(MONTHS.get(cal.get(Calendar.MONTH))); + sb.append(' '); + + // day + int day = cal.get(Calendar.DATE); + if (day < 10) { + sb.append(' '); + } + sb.append(day); + sb.append(' '); + + long sixMonth = 15811200000L; // 183L * 24L * 60L * 60L * 1000L; + long nowTime = System.currentTimeMillis(); + if (Math.abs(nowTime - millis) > sixMonth) { + + // year + int year = cal.get(Calendar.YEAR); + sb.append(' '); + sb.append(year); + } else { + + // hour + int hh = cal.get(Calendar.HOUR_OF_DAY); + if (hh < 10) { + sb.append('0'); + } + sb.append(hh); + sb.append(':'); + + // minute + int mm = cal.get(Calendar.MINUTE); + if (mm < 10) { + sb.append('0'); + } + sb.append(mm); + } + return sb.toString(); + } +}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java b/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java index ddee616..3d22f36 100644 --- a/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java +++ b/sshd-core/src/main/java/org/apache/sshd/server/x11/X11ForwardSupport.java @@ -40,7 +40,6 @@ import org.apache.sshd.common.io.IoSession; import org.apache.sshd.common.session.ConnectionService; import org.apache.sshd.common.session.Session; import org.apache.sshd.common.util.CloseableUtils; -import org.apache.sshd.common.util.GenericUtils; import org.apache.sshd.common.util.Readable; import org.apache.sshd.common.util.ValidateUtils; import org.apache.sshd.common.util.buffer.Buffer; @@ -51,14 +50,13 @@ import org.apache.sshd.common.util.buffer.ByteArrayBuffer; */ public class X11ForwardSupport extends CloseableUtils.AbstractInnerCloseable implements IoHandler { - private static String xauthCommand = System.getProperty("sshd.xauthCommand", "xauth"); /** * Configuration value on the {@link FactoryManager} to control the * channel open timeout. If not specified then {@link #DEFAULT_CHANNEL_OPEN_TIMEOUT} * value is used */ public static final String CHANNEL_OPEN_TIMEOUT_PROP = "x11-fwd-open-timeout"; - public static final long DEFAULT_CHANNEL_OPEN_TIMEOUT = TimeUnit.SECONDS.toMillis(30L); + public static final long DEFAULT_CHANNEL_OPEN_TIMEOUT = TimeUnit.SECONDS.toMillis(30L); public static final int X11_DISPLAY_OFFSET = 10; public static final int MAX_DISPLAYS = 1000; @@ -68,6 +66,8 @@ public class X11ForwardSupport extends CloseableUtils.AbstractInnerCloseable imp */ public static final String ENV_DISPLAY = "DISPLAY"; + private static final String XAUTH_COMMAND = System.getProperty("sshd.XAUTH_COMMAND", "xauth"); + private final ConnectionService service; private IoAcceptor acceptor; @@ -103,7 +103,8 @@ public class X11ForwardSupport extends CloseableUtils.AbstractInnerCloseable imp acceptor = factory.createAcceptor(this); } - int displayNumber, port; + int displayNumber; + int port; InetSocketAddress addr; for (displayNumber = X11_DISPLAY_OFFSET; displayNumber < MAX_DISPLAYS; displayNumber++) { @@ -130,10 +131,10 @@ public class X11ForwardSupport extends CloseableUtils.AbstractInnerCloseable imp if (!os.contains("windows")) { try { String authDisplay = "unix:" + displayNumber + "." + screen; - Process p = new ProcessBuilder(xauthCommand, "remove", authDisplay).start(); + Process p = new ProcessBuilder(XAUTH_COMMAND, "remove", authDisplay).start(); int result = p.waitFor(); if (result == 0) { - p = new ProcessBuilder(xauthCommand, "add", authDisplay, authenticationProtocol, authenticationCookie).start(); + p = new ProcessBuilder(XAUTH_COMMAND, "add", authDisplay, authenticationProtocol, authenticationCookie).start(); result = p.waitFor(); } } catch (Exception e) { @@ -157,8 +158,8 @@ public class X11ForwardSupport extends CloseableUtils.AbstractInnerCloseable imp @Override public void sessionClosed(IoSession session) throws Exception { ChannelForwardedX11 channel = (ChannelForwardedX11) session.getAttribute(ChannelForwardedX11.class); - if ( channel != null ){ - channel.close(false); + if (channel != null) { + channel.close(false); } } @@ -213,7 +214,8 @@ public class X11ForwardSupport extends CloseableUtils.AbstractInnerCloseable imp if (streaming == Streaming.Async) { throw new IllegalArgumentException("Asynchronous streaming isn't supported yet on this channel"); } - invertedIn = out = new ChannelOutputStream(this, remoteWindow, log, SshConstants.SSH_MSG_CHANNEL_DATA); + out = new ChannelOutputStream(this, remoteWindow, log, SshConstants.SSH_MSG_CHANNEL_DATA); + invertedIn = out; } @Override http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 ffc219c..6ad5f6d 100644 --- a/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/AuthenticationTest.java @@ -89,9 +89,9 @@ public class AuthenticationTest extends BaseTestSupport { @Test public void testWrongPassword() throws Exception { - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - try(ClientSession s = client.connect("user", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession s = client.connect("user", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.addPasswordIdentity("bad password"); assertTrue(s.auth().await().isFailure()); @@ -101,20 +101,20 @@ public class AuthenticationTest extends BaseTestSupport { @Test public void testChangeUser() throws Exception { - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.setServiceFactories(Arrays.asList( new ClientUserAuthServiceOld.Factory(), ClientConnectionServiceFactory.INSTANCE )); client.start(); - - try(ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0); - + assertFalse("Unexpected user1 password auth success", authPassword(s, "user1", "the-password").await().isSuccess()); assertFalse("Unexpected user2 password auth success", 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("Mismatched client session close mask", ClientSession.CLOSED | ClientSession.WAIT_AUTH, s.waitFor(ClientSession.CLOSED, 1000)); @@ -126,18 +126,18 @@ public class AuthenticationTest extends BaseTestSupport { @Test public void testAuthPasswordOnly() throws Exception { - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.setServiceFactories(Arrays.asList( new ClientUserAuthServiceOld.Factory(), ClientConnectionServiceFactory.INSTANCE )); client.start(); - - try(ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0); - + assertFalse("Unexpected password auth sucess", authPassword(s, getCurrentTestName(), getCurrentTestName()).await().isSuccess()); - + s.close(true); } finally { client.stop(); @@ -147,16 +147,16 @@ public class AuthenticationTest extends BaseTestSupport { @Test public void testAuthKeyPassword() throws Exception { - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.setServiceFactories(Arrays.asList( new ClientUserAuthServiceOld.Factory(), ClientConnectionServiceFactory.INSTANCE )); client.start(); - - try(ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0); - + KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA); assertFalse("Unexpected pubkey auth success", authPublicKey(s, getCurrentTestName(), pair).await().isSuccess()); assertTrue("Failed password auth", authPassword(s, getCurrentTestName(), getCurrentTestName()).await().isSuccess()); @@ -169,20 +169,20 @@ public class AuthenticationTest extends BaseTestSupport { @Test public void testAuthKeyInteractive() throws Exception { - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.setServiceFactories(Arrays.asList( new ClientUserAuthServiceOld.Factory(), ClientConnectionServiceFactory.INSTANCE )); client.start(); - - try(ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession s = client.connect(null, "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { s.waitFor(ClientSession.CLOSED | ClientSession.WAIT_AUTH, 0); - + KeyPair pair = Utils.createTestHostKeyProvider().loadKey(KeyPairProvider.SSH_RSA); assertFalse("Unexpected pubkey auth success", authPublicKey(s, getCurrentTestName(), pair).await().isSuccess()); assertTrue("Failed password auth", authInteractive(s, getCurrentTestName(), getCurrentTestName()).await().isSuccess()); - + s.close(true); } finally { client.stop(); @@ -212,6 +212,7 @@ public class AuthenticationTest extends BaseTestSupport { public TestSession(ServerFactoryManager server, IoSession ioSession) throws Exception { super(server, ioSession); } + @Override public void handleMessage(Buffer buffer) throws Exception { super.handleMessage(buffer); // debug breakpoint http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java b/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java index 5954ec3..cb00d1e 100644 --- a/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/KeepAliveTest.java @@ -65,7 +65,7 @@ public class KeepAliveTest extends BaseTestSupport { sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE); sshd.setPublickeyAuthenticator(AcceptAllPublickeyAuthenticator.INSTANCE); sshd.start(); - port = sshd.getPort(); + port = sshd.getPort(); } @After @@ -79,15 +79,15 @@ public class KeepAliveTest extends BaseTestSupport { public void testClient() throws Exception { SshClient client = SshClient.setUpDefaultClient(); client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { + + try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { int state = channel.waitFor(ClientChannel.CLOSED, WAIT); assertEquals("Wrong channel state", ClientChannel.CLOSED | ClientChannel.EOF, state); - + channel.close(false); } } finally { @@ -99,15 +99,15 @@ public class KeepAliveTest extends BaseTestSupport { public void testClientNew() throws Exception { SshClient client = SshClient.setUpDefaultClient(); client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { + + try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { int state = channel.waitFor(ClientChannel.CLOSED, WAIT); assertEquals("Wrong channel state", ClientChannel.CLOSED | ClientChannel.EOF, state); - + channel.close(false); } } finally { @@ -121,14 +121,14 @@ public class KeepAliveTest extends BaseTestSupport { FactoryManagerUtils.updateProperty(client, ClientFactoryManager.HEARTBEAT_INTERVAL, HEARTBEAT); client.start(); - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { + try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { int state = channel.waitFor(ClientChannel.CLOSED, WAIT); assertEquals("Wrong channel state", ClientChannel.TIMEOUT, state); - + channel.close(false); } } finally { @@ -142,14 +142,14 @@ public class KeepAliveTest extends BaseTestSupport { FactoryManagerUtils.updateProperty(client, ClientFactoryManager.HEARTBEAT_INTERVAL, HEARTBEAT); client.start(); - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { + + try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { int state = channel.waitFor(ClientChannel.CLOSED, WAIT); assertEquals("Wrong channel state", ClientChannel.TIMEOUT, state); - + channel.close(false); } } finally { @@ -163,23 +163,23 @@ public class KeepAliveTest extends BaseTestSupport { SshClient client = SshClient.setUpDefaultClient(); client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream()) { + try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream()) { channel.setOut(out); channel.setErr(err); channel.open().verify(9L, TimeUnit.SECONDS); - + assertTrue("Latch time out", TestEchoShellFactory.TestEchoShell.latch.await(10L, TimeUnit.SECONDS)); int state = channel.waitFor(ClientChannel.CLOSED, WAIT); assertEquals("Wrong channel state", ClientChannel.CLOSED | ClientChannel.EOF | ClientChannel.OPENED, state); - + channel.close(false); } } finally { @@ -194,22 +194,22 @@ public class KeepAliveTest extends BaseTestSupport { SshClient client = SshClient.setUpDefaultClient(); client.start(); - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream()) { + + try (ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream()) { channel.setOut(out); channel.setErr(err); channel.open().verify(9L, TimeUnit.SECONDS); - + assertTrue("Latch time out", TestEchoShellFactory.TestEchoShell.latch.await(10L, TimeUnit.SECONDS)); int state = channel.waitFor(ClientChannel.CLOSED, WAIT); assertEquals("Wrong channel state", ClientChannel.CLOSED | ClientChannel.EOF | ClientChannel.OPENED, state); - + channel.close(false); } } finally { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 ef853f2..2864267 100644 --- a/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/KeyReExchangeTest.java @@ -27,6 +27,7 @@ import java.nio.charset.StandardCharsets; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import com.jcraft.jsch.JSch; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.channel.ChannelShell; import org.apache.sshd.client.channel.ClientChannel; @@ -48,8 +49,6 @@ import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; -import com.jcraft.jsch.JSch; - /** * Test key exchange algorithms. * @@ -79,7 +78,7 @@ public class KeyReExchangeTest extends BaseTestSupport { sshd.setShellFactory(new EchoShellFactory()); sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE); sshd.start(); - port = sshd.getPort(); + port = sshd.getPort(); } @Test @@ -96,8 +95,8 @@ public class KeyReExchangeTest extends BaseTestSupport { com.jcraft.jsch.Channel c = s.openChannel("shell"); c.connect(); - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { String expected = "this is my command\n"; byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); @@ -108,7 +107,7 @@ public class KeyReExchangeTest extends BaseTestSupport { int len = is.read(data); String str = new String(data, 0, len); - assertEquals("Mismatched data at iteration " + i,expected, str); + assertEquals("Mismatched data at iteration " + i, expected, str); s.rekey(); } } finally { @@ -123,36 +122,36 @@ public class KeyReExchangeTest extends BaseTestSupport { public void testReExchangeFromNativeClient() throws Exception { setUp(0, 0); - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(ChannelShell channel = session.createShellChannel(); - ByteArrayOutputStream sent = new ByteArrayOutputStream(); - PipedOutputStream pipedIn = new PipedOutputStream(); - InputStream inPipe = new PipedInputStream(pipedIn); - OutputStream teeOut = new TeeOutputStream(sent, pipedIn); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream()) { - + + try (ChannelShell channel = session.createShellChannel(); + ByteArrayOutputStream sent = new ByteArrayOutputStream(); + PipedOutputStream pipedIn = new PipedOutputStream(); + InputStream inPipe = new PipedInputStream(pipedIn); + OutputStream teeOut = new TeeOutputStream(sent, pipedIn); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream()) { + channel.setIn(inPipe); channel.setOut(out); channel.setErr(err); channel.open(); - + teeOut.write("this is my command\n".getBytes(StandardCharsets.UTF_8)); teeOut.flush(); - + StringBuilder sb = new StringBuilder(); for (int i = 0; i < 10; i++) { sb.append("0123456789"); } sb.append("\n"); - - byte[] data=sb.toString().getBytes(StandardCharsets.UTF_8); + + byte[] data = sb.toString().getBytes(StandardCharsets.UTF_8); for (int i = 0; i < 10; i++) { teeOut.write(data); teeOut.flush(); @@ -160,11 +159,11 @@ public class KeyReExchangeTest extends BaseTestSupport { } teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8)); teeOut.flush(); - + channel.waitFor(ClientChannel.CLOSED, 0); - + channel.close(false); - + assertArrayEquals("Mismatched sent data content", sent.toByteArray(), out.toByteArray()); } } finally { @@ -177,47 +176,49 @@ public class KeyReExchangeTest extends BaseTestSupport { public void testReExchangeFromServer() throws Exception { setUp(8192, 0); - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(ChannelShell channel = session.createShellChannel(); - ByteArrayOutputStream sent = new ByteArrayOutputStream(); - PipedOutputStream pipedIn = new PipedOutputStream(); - OutputStream teeOut = new TeeOutputStream(sent, pipedIn); - ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - InputStream inPipe = new PipedInputStream(pipedIn)) { + try (ChannelShell channel = session.createShellChannel(); + ByteArrayOutputStream sent = new ByteArrayOutputStream(); + PipedOutputStream pipedIn = new PipedOutputStream(); + OutputStream teeOut = new TeeOutputStream(sent, pipedIn); + ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream(); + InputStream inPipe = new PipedInputStream(pipedIn)) { channel.setIn(inPipe); channel.setOut(out); channel.setErr(err); channel.open(); - + teeOut.write("this is my command\n".getBytes(StandardCharsets.UTF_8)); teeOut.flush(); - + StringBuilder sb = new StringBuilder(); for (int i = 0; i < 100; i++) { sb.append("0123456789"); } sb.append("\n"); - + final AtomicInteger exchanges = new AtomicInteger(); session.addListener(new SessionListener() { @Override public void sessionCreated(Session session) { // ignored } + @Override public void sessionEvent(Session session, Event event) { if (event == Event.KeyEstablished) { exchanges.incrementAndGet(); } } + @Override public void sessionClosed(Session session) { // ignored @@ -229,11 +230,11 @@ public class KeyReExchangeTest extends BaseTestSupport { } teeOut.write("exit\n".getBytes(StandardCharsets.UTF_8)); teeOut.flush(); - + channel.waitFor(ClientChannel.CLOSED, 0); - + channel.close(false); - + assertTrue("Expected rekeying", exchanges.get() > 0); assertEquals("Mismatched sent data length", sent.toByteArray().length, out.toByteArray().length); assertArrayEquals("Mismatched sent data content", sent.toByteArray(), out.toByteArray()); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 d595892..9ade9e0 100644 --- a/sshd-core/src/test/java/org/apache/sshd/LoadTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/LoadTest.java @@ -62,7 +62,7 @@ public class LoadTest extends BaseTestSupport { sshd.setShellFactory(new EchoShellFactory()); sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE); sshd.start(); - port = sshd.getPort(); + port = sshd.getPort(); } @After @@ -120,37 +120,37 @@ public class LoadTest extends BaseTestSupport { } protected void runClient(String msg) throws Exception { - try(SshClient client = SshClient.setUpDefaultClient()) { - Map<String,Object> props=client.getProperties(); + try (SshClient client = SshClient.setUpDefaultClient()) { + Map<String, Object> props = client.getProperties(); FactoryManagerUtils.updateProperty(props, FactoryManager.MAX_PACKET_SIZE, 1024 * 16); FactoryManagerUtils.updateProperty(props, FactoryManager.WINDOW_SIZE, 1024 * 8); client.setKeyExchangeFactories(Arrays.asList( ClientBuilder.DH2KEX.transform(BuiltinDHFactories.dhg1))); client.setCipherFactories(Arrays.<NamedFactory<Cipher>>asList(BuiltinCiphers.blowfishcbc)); client.start(); - try(ClientSession session = client.connect("sshd", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + try (ClientSession session = client.connect("sshd", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity("sshd"); session.auth().verify(5L, TimeUnit.SECONDS); - - try(ByteArrayOutputStream out = new ByteArrayOutputStream(); - ByteArrayOutputStream err = new ByteArrayOutputStream(); - ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { + + try (ByteArrayOutputStream out = new ByteArrayOutputStream(); + ByteArrayOutputStream err = new ByteArrayOutputStream(); + ClientChannel channel = session.createChannel(ClientChannel.CHANNEL_SHELL)) { channel.setOut(out); channel.setErr(err); try { channel.open().verify(9L, TimeUnit.SECONDS); - try(OutputStream pipedIn = channel.getInvertedIn()) { + try (OutputStream pipedIn = channel.getInvertedIn()) { msg += "\nexit\n"; pipedIn.write(msg.getBytes(StandardCharsets.UTF_8)); pipedIn.flush(); } - + channel.waitFor(ClientChannel.CLOSED, 0); - } finally { + } finally { channel.close(false); } - + assertArrayEquals("Mismatched message data", msg.getBytes(StandardCharsets.UTF_8), out.toByteArray()); } } finally { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 bb5acdf..3b29852 100644 --- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingLoadTest.java @@ -18,8 +18,6 @@ */ package org.apache.sshd; -import static org.apache.sshd.util.Utils.getFreePort; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; @@ -37,6 +35,9 @@ 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; @@ -63,9 +64,7 @@ import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Session; +import static org.apache.sshd.util.Utils.getFreePort; /** * Port forwarding tests @@ -123,11 +122,11 @@ public class PortForwardingLoadTest extends BaseTestSupport { @Test public void testLocalForwardingPayload() throws Exception { final int NUM_ITERATIONS = 100; - final String PAYLOAD_TMP = "This is significantly 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. This is significantly "+ - "longer Test Data. This is significantly longer Test Data. This is significantly "+ - "longer Test Data. This is significantly longer Test Data. This is significantly "+ + final String PAYLOAD_TMP = "This is significantly 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. This is significantly " + + "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(PAYLOAD_TMP.length() * 1000); for (int i = 0; i < 1000; i++) { @@ -135,68 +134,68 @@ public class PortForwardingLoadTest extends BaseTestSupport { } final String PAYLOAD = sb.toString(); - Session session = createSession(); - try(final ServerSocket ss = new ServerSocket()) { + 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]; - 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); - } + @SuppressWarnings("synthetic-access") + @Override + public void run() { + try { + byte[] buf = new byte[8192]; + 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); } + log.info("Done"); + } catch (Exception e) { + log.error("Failed to complete run loop", e); } - }; + } + }; tAcceptor.start(); Thread.sleep(50); - - byte[] buf = new byte[8192]; - byte[] bytes = PAYLOAD.getBytes(StandardCharsets.UTF_8); + + byte[] buf = new byte[8192]; + byte[] bytes = PAYLOAD.getBytes(StandardCharsets.UTF_8); 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()) { + try (Socket s = new Socket("localhost", sinkPort); + OutputStream sockOut = s.getOutputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); sockOut.write(bytes); sockOut.flush(); - - try(InputStream sockIn = s.getInputStream(); - ByteArrayOutputStream baos = new ByteArrayOutputStream(bytes.length)) { + + 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); @@ -208,7 +207,7 @@ public class PortForwardingLoadTest extends BaseTestSupport { } } session.delPortForwardingL(sinkPort); - + ss.close(); tAcceptor.join(TimeUnit.SECONDS.toMillis(5L)); } finally { @@ -219,11 +218,11 @@ public class PortForwardingLoadTest extends BaseTestSupport { @Test public void testRemoteForwardingPayload() throws Exception { final int NUM_ITERATIONS = 100; - final String PAYLOAD = "This is significantly 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. This is significantly "+ - "longer Test Data. This is significantly longer Test Data. This is significantly "+ - "longer Test Data. This is significantly longer Test Data. This is significantly "+ + final String PAYLOAD = "This is significantly 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. This is significantly " + + "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. "; Session session = createSession(); try (final ServerSocket ss = new ServerSocket()) { @@ -235,33 +234,33 @@ public class PortForwardingLoadTest extends BaseTestSupport { 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(StandardCharsets.UTF_8); - 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(); - } + @SuppressWarnings("synthetic-access") + @Override + public void run() { + started[0] = true; + try { + byte[] bytes = PAYLOAD.getBytes(StandardCharsets.UTF_8); + 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); } + } 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()]; @@ -269,8 +268,8 @@ public class PortForwardingLoadTest extends BaseTestSupport { for (int i = 0; i < NUM_ITERATIONS; i++) { final int ii = i; - try(Socket s = new Socket("localhost", sinkPort); - InputStream sockIn = s.getInputStream()) { + try (Socket s = new Socket("localhost", sinkPort); + InputStream sockIn = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); @@ -288,7 +287,7 @@ public class PortForwardingLoadTest extends BaseTestSupport { if (!lenOK[ii]) { throw new IndexOutOfBoundsException("Mismatched length: expected=" + PAYLOAD.length() + ", actual=" + totalRead); } - + if (!dataOK[ii]) { throw new IllegalStateException("Mismatched content"); } @@ -354,7 +353,7 @@ public class PortForwardingLoadTest extends BaseTestSupport { 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>(); @@ -362,7 +361,7 @@ public class PortForwardingLoadTest extends BaseTestSupport { threads[i] = new Thread(getCurrentTestName() + "[" + i + "]") { @Override public void run() { - for (int j = 0; j < nbLoops; j++) { + for (int j = 0; j < nbLoops; j++) { final MultiThreadedHttpConnectionManager mgr = new MultiThreadedHttpConnectionManager(); final HttpClient client = new HttpClient(mgr); client.getHttpConnectionManager().getParams().setDefaultMaxConnectionsPerHost(100); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 567a263..0623ae7 100644 --- a/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/PortForwardingTest.java @@ -18,8 +18,6 @@ */ package org.apache.sshd; -import static org.apache.sshd.util.Utils.getFreePort; - import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Field; @@ -38,6 +36,9 @@ import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.TimeUnit; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; +import com.jcraft.jsch.Session; import org.apache.mina.core.buffer.IoBuffer; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoHandlerAdapter; @@ -71,9 +72,7 @@ import org.junit.Test; import org.junit.runners.MethodSorters; import org.slf4j.LoggerFactory; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; -import com.jcraft.jsch.Session; +import static org.apache.sshd.util.Utils.getFreePort; /** * Port forwarding tests @@ -101,48 +100,48 @@ public class PortForwardingTest extends BaseTestSupport { sshd.setPasswordAuthenticator(BogusPasswordAuthenticator.INSTANCE); sshd.setTcpipForwardingFilter(AcceptAllForwardingFilter.INSTANCE); sshd.start(); - + if (!requestsQ.isEmpty()) { requestsQ.clear(); } final TcpipForwarderFactory factory = ValidateUtils.checkNotNull(sshd.getTcpipForwarderFactory(), "No TcpipForwarderFactory"); sshd.setTcpipForwarderFactory(new TcpipForwarderFactory() { - private final Class<?>[] interfaces = { TcpipForwarder.class }; - private final Map<String,String> method2req = new TreeMap<String,String>(String.CASE_INSENSITIVE_ORDER) { - private static final long serialVersionUID = 1L; // we're not serializing it... + private final Class<?>[] interfaces = {TcpipForwarder.class}; + private final Map<String, String> method2req = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER) { + private static final long serialVersionUID = 1L; // we're not serializing it... - { - put("localPortForwardingRequested", TcpipForwardHandler.REQUEST); - put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST); - } - }; - - @Override - public TcpipForwarder create(ConnectionService service) { - Thread thread = Thread.currentThread(); - ClassLoader cl = thread.getContextClassLoader(); - - final TcpipForwarder forwarder = factory.create(service); - return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() { - @SuppressWarnings("synthetic-access") - @Override - public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { - Object result = method.invoke(forwarder, args); - String name = method.getName(); - String request = method2req.get(name); - if (GenericUtils.length(request) > 0) { - if (requestsQ.offer(request)) { - log.info("Signal " + request); - } else { - log.error("Failed to offer request=" + request); - } + { + put("localPortForwardingRequested", TcpipForwardHandler.REQUEST); + put("localPortForwardingCancelled", CancelTcpipForwardHandler.REQUEST); + } + }; + + @Override + public TcpipForwarder create(ConnectionService service) { + Thread thread = Thread.currentThread(); + ClassLoader cl = thread.getContextClassLoader(); + + final TcpipForwarder forwarder = factory.create(service); + return (TcpipForwarder) Proxy.newProxyInstance(cl, interfaces, new InvocationHandler() { + @SuppressWarnings("synthetic-access") + @Override + public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { + Object result = method.invoke(forwarder, args); + String name = method.getName(); + String request = method2req.get(name); + if (GenericUtils.length(request) > 0) { + if (requestsQ.offer(request)) { + log.info("Signal " + request); + } else { + log.error("Failed to offer request=" + request); } - return result; } - }); - } - }); + return result; + } + }); + } + }); sshPort = sshd.getPort(); NioSocketAcceptor acceptor = new NioSocketAcceptor(); @@ -170,11 +169,11 @@ public class PortForwardingTest extends BaseTestSupport { if (GenericUtils.isEmpty(actual)) { throw new IllegalStateException("Failed to retrieve request=" + expected); } - + if (expected.equals(actual)) { return; } - + long waitDuration = waitEnd - waitStart; remaining -= waitDuration; } @@ -202,24 +201,24 @@ public class PortForwardingTest extends BaseTestSupport { int forwardedPort = getFreePort(); session.setPortForwardingR(forwardedPort, "localhost", echoPort); waitForForwardingRequest(TcpipForwardHandler.REQUEST, TimeUnit.SECONDS.toMillis(5L)); - - try(Socket s = new Socket("localhost", forwardedPort); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + + try (Socket s = new Socket("localhost", forwardedPort); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); - byte[] buf = new byte[bytes.length + Long.SIZE]; - int n = input.read(buf); - String res = new String(buf, 0, n, StandardCharsets.UTF_8); + byte[] buf = new byte[bytes.length + Long.SIZE]; + int n = input.read(buf); + String res = new String(buf, 0, n, StandardCharsets.UTF_8); assertEquals("Mismatched data", expected, res); } - + session.delPortForwardingR(forwardedPort); } finally { session.disconnect(); @@ -239,21 +238,21 @@ public class PortForwardingTest extends BaseTestSupport { session.setPortForwardingR(forwardedPort, "localhost", echoPort); waitForForwardingRequest(TcpipForwardHandler.REQUEST, TimeUnit.SECONDS.toMillis(5L)); - - try(Socket s = new Socket("localhost", forwardedPort); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + + try (Socket s = new Socket("localhost", forwardedPort); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); - byte[] buf = new byte[bytes.length + Long.SIZE]; - int n = input.read(buf); - String res = new String(buf, 0, n, StandardCharsets.UTF_8); + byte[] buf = new byte[bytes.length + Long.SIZE]; + int n = input.read(buf); + String res = new String(buf, 0, n, StandardCharsets.UTF_8); assertEquals("Mismatched data", expected, res); } session.delPortForwardingR("localhost", forwardedPort); @@ -264,25 +263,25 @@ public class PortForwardingTest extends BaseTestSupport { @Test public void testRemoteForwardingNative() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress remote = new SshdSocketAddress("", 0); SshdSocketAddress local = new SshdSocketAddress("localhost", echoPort); SshdSocketAddress bound = session.startRemotePortForwarding(remote, local); - - try(Socket s = new Socket(bound.getHostName(), bound.getPort()); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + + try (Socket s = new Socket(bound.getHostName(), bound.getPort()); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); - byte[] buf = new byte[bytes.length + Long.SIZE]; - int n = input.read(buf); - String res = new String(buf, 0, n); + byte[] buf = new byte[bytes.length + Long.SIZE]; + int n = input.read(buf); + String res = new String(buf, 0, n); assertEquals("Mismatched data", expected, res); } @@ -293,31 +292,31 @@ public class PortForwardingTest extends BaseTestSupport { @Test public void testRemoteForwardingNativeBigPayload() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress remote = new SshdSocketAddress("", 0); SshdSocketAddress local = new SshdSocketAddress("localhost", echoPort); SshdSocketAddress bound = session.startRemotePortForwarding(remote, local); - try(Socket s = new Socket(bound.getHostName(), bound.getPort()); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + try (Socket s = new Socket(bound.getHostName(), bound.getPort()); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); - byte[] buf = new byte[bytes.length + Long.SIZE]; + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + byte[] buf = new byte[bytes.length + Long.SIZE]; for (int i = 0; i < 1000; i++) { output.write(bytes); output.flush(); - int n = input.read(buf); - String res = new String(buf, 0, n); + int n = input.read(buf); + String res = new String(buf, 0, n); assertEquals("Mismatched data at iteration #" + i, expected, res); } } - + session.stopRemotePortForwarding(remote); session.close(false).await(); } @@ -329,25 +328,25 @@ public class PortForwardingTest extends BaseTestSupport { try { int forwardedPort = getFreePort(); session.setPortForwardingL(forwardedPort, "localhost", echoPort); - - try(Socket s = new Socket("localhost", forwardedPort); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + + try (Socket s = new Socket("localhost", forwardedPort); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); - byte[] buf = new byte[bytes.length + Long.SIZE]; - int n = input.read(buf); - String res = new String(buf, 0, n); + byte[] buf = new byte[bytes.length + Long.SIZE]; + int n = input.read(buf); + String res = new String(buf, 0, n); assertEquals("Mismatched data", expected, res); } - + session.delPortForwardingL(forwardedPort); } finally { session.disconnect(); @@ -356,26 +355,26 @@ public class PortForwardingTest extends BaseTestSupport { @Test public void testLocalForwardingNative() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress local = new SshdSocketAddress("", 0); SshdSocketAddress remote = new SshdSocketAddress("localhost", echoPort); SshdSocketAddress bound = session.startLocalPortForwarding(local, remote); - try(Socket s = new Socket(bound.getHostName(), bound.getPort()); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + try (Socket s = new Socket(bound.getHostName(), bound.getPort()); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); output.write(bytes); output.flush(); - byte[] buf = new byte[bytes.length + Long.SIZE]; - int n = input.read(buf); - String res = new String(buf, 0, n); + byte[] buf = new byte[bytes.length + Long.SIZE]; + int n = input.read(buf); + String res = new String(buf, 0, n); assertEquals("Mismatched data", expected, res); } @@ -386,33 +385,33 @@ public class PortForwardingTest extends BaseTestSupport { @Test public void testLocalForwardingNativeReuse() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress local = new SshdSocketAddress("", 0); SshdSocketAddress remote = new SshdSocketAddress("localhost", echoPort); SshdSocketAddress bound = session.startLocalPortForwarding(local, remote); session.stopLocalPortForwarding(bound); - + SshdSocketAddress bound2 = session.startLocalPortForwarding(local, remote); session.stopLocalPortForwarding(bound2); - + session.close(false).await(); } } @Test public void testLocalForwardingNativeBigPayload() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress local = new SshdSocketAddress("", 0); SshdSocketAddress remote = new SshdSocketAddress("localhost", echoPort); SshdSocketAddress bound = session.startLocalPortForwarding(local, remote); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); - byte[] buf = new byte[bytes.length + Long.SIZE]; - try(Socket s = new Socket(bound.getHostName(), bound.getPort()); - OutputStream output = s.getOutputStream(); - InputStream input = s.getInputStream()) { + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + byte[] buf = new byte[bytes.length + Long.SIZE]; + try (Socket s = new Socket(bound.getHostName(), bound.getPort()); + OutputStream output = s.getOutputStream(); + InputStream input = s.getInputStream()) { s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); @@ -420,12 +419,12 @@ public class PortForwardingTest extends BaseTestSupport { output.write(bytes); output.flush(); - int n = input.read(buf); - String res = new String(buf, 0, n); + int n = input.read(buf); + String res = new String(buf, 0, n); assertEquals("Mismatched data at iteration #" + i, expected, res); } } - + session.stopLocalPortForwarding(bound); session.close(false).await(); } @@ -433,24 +432,24 @@ public class PortForwardingTest extends BaseTestSupport { @Test public void testForwardingChannel() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress local = new SshdSocketAddress("", 0); SshdSocketAddress remote = new SshdSocketAddress("localhost", echoPort); - try(ChannelDirectTcpip channel = session.createDirectTcpipChannel(local, remote)) { + try (ChannelDirectTcpip channel = session.createDirectTcpipChannel(local, remote)) { channel.open().verify(9L, TimeUnit.SECONDS); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); - try(OutputStream output = channel.getInvertedIn(); - InputStream input = channel.getInvertedOut()) { + try (OutputStream output = channel.getInvertedIn(); + InputStream input = channel.getInvertedOut()) { output.write(bytes); output.flush(); - - byte[] buf = new byte[bytes.length + Long.SIZE]; - int n = input.read(buf); - String res = new String(buf, 0, n); + + byte[] buf = new byte[bytes.length + Long.SIZE]; + int n = input.read(buf); + String res = new String(buf, 0, n); assertEquals("Mismatched data", expected, res); } channel.close(false); @@ -470,12 +469,12 @@ public class PortForwardingTest extends BaseTestSupport { waitForForwardingRequest(TcpipForwardHandler.REQUEST, TimeUnit.SECONDS.toMillis(5L)); // 2. Establish a connection through it - try(Socket s = new Socket("localhost", forwardedPort)) { + 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(TimeUnit.SECONDS.toMillis(1L)); @@ -486,9 +485,9 @@ public class PortForwardingTest extends BaseTestSupport { while (root.getParent() != null) { root = root.getParent(); } - + for (int index = 0; ; index++) { - Collection<Thread> pending = findThreads(root, "NioProcessor-"); + Collection<Thread> pending = findThreads(root, "NioProcessor-"); if (GenericUtils.size(pending) <= 0) { log.info("Finished after " + index + " iterations"); break; @@ -500,7 +499,7 @@ public class PortForwardingTest extends BaseTestSupport { } } } - + session.delPortForwardingR(forwardedPort); } } finally { @@ -512,15 +511,14 @@ public class PortForwardingTest extends BaseTestSupport { * Close the socket inside this JSCH session. Use reflection to find it and * just close it. * - * @param session - * the Session to violate + * @param session the Session to violate * @throws Exception */ private void rudelyDisconnectJschSession(Session session) throws Exception { Field fSocket = session.getClass().getDeclaredField("socket"); fSocket.setAccessible(true); - - try(Socket socket = (Socket) fSocket.get(session)) { + + try (Socket socket = (Socket) fSocket.get(session)) { assertTrue("socket is not connected", socket.isConnected()); assertFalse("socket should not be closed", socket.isClosed()); socket.close(); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 5dc78ce..2b6bffc 100644 --- a/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/ProxyTest.java @@ -104,23 +104,23 @@ public class ProxyTest extends BaseTestSupport { @Test public void testSocksProxy() throws Exception { - try(ClientSession session = createNativeSession()) { + try (ClientSession session = createNativeSession()) { SshdSocketAddress dynamic = session.startDynamicPortForwarding(new SshdSocketAddress("localhost", 0)); - String expected = getCurrentTestName(); - byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); - byte[] buf = new byte[bytes.length + Long.SIZE]; + String expected = getCurrentTestName(); + byte[] bytes = expected.getBytes(StandardCharsets.UTF_8); + 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())))) { + try (Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) { s.connect(new InetSocketAddress("localhost", echoPort)); s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); - - try(OutputStream sockOut = s.getOutputStream(); - InputStream sockIn = s.getInputStream()) { - + + 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)); } @@ -128,9 +128,9 @@ public class ProxyTest extends BaseTestSupport { } session.stopDynamicPortForwarding(dynamic); - + try { - try(Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) { + try (Socket s = new Socket(new Proxy(Proxy.Type.SOCKS, new InetSocketAddress("localhost", dynamic.getPort())))) { s.connect(new InetSocketAddress("localhost", echoPort)); s.setSoTimeout((int) TimeUnit.SECONDS.toMillis(10L)); s.getOutputStream().write(bytes); @@ -139,7 +139,7 @@ public class ProxyTest extends BaseTestSupport { } catch (IOException e) { // expected } - + session.close(false).await(); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 8119c74..2ecc597 100644 --- a/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/SinglePublicKeyAuthTest.java @@ -110,11 +110,11 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport { } }); delegate = auth; - - try(SshClient client = SshClient.setUpDefaultClient()) { + + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPublicKeyIdentity(pairRsaBad); session.addPublicKeyIdentity(pairRsa); session.auth().verify(5L, TimeUnit.SECONDS); @@ -146,11 +146,11 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport { return key.equals(pairRsa.getPublic()); } }; - - try(SshClient client = SshClient.setUpDefaultClient()) { + + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPublicKeyIdentity(pairRsaBad); session.addPublicKeyIdentity(pairRsa); assertTrue("Failed to authenticate", session.auth().await().isSuccess()); @@ -160,7 +160,7 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport { } assertEquals("Mismatched attempted keys count", 2, count.size()); - + String badFingerPrint = KeyUtils.getFingerPrint(pairRsaBad.getPublic()); Number badIndex = count.get(badFingerPrint); assertNotNull("Missing bad RSA key", badIndex); @@ -176,6 +176,7 @@ public class SinglePublicKeyAuthTest extends BaseTestSupport { public TestCachingPublicKeyAuthenticator(PublickeyAuthenticator authenticator) { super(authenticator); } + public Map<ServerSession, Map<PublicKey, Boolean>> getCache() { return cache; } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 8a93b6b..9a3fa49 100644 --- a/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/WelcomeBannerTest.java @@ -66,21 +66,22 @@ public class WelcomeBannerTest extends BaseTestSupport { @Test public void testBanner() throws Exception { final AtomicReference<String> welcome = new AtomicReference<String>(); - - try(SshClient client = SshClient.setUpDefaultClient()) { + + 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 lang, String[] prompt, boolean[] echo) { return null; } }); client.start(); - - try(ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); assertEquals(WELCOME, welcome.get()); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/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 1bf282f..8fb46a4 100644 --- a/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/WindowAdjustTest.java @@ -56,7 +56,7 @@ import org.junit.runners.MethodSorters; /** * This test simulates heavy traffic coming from the server towards the client making sure the traffic does not get stuck. * Especially if the server receives window adjust message while it tries to transfer all the data. - * + * <p/> * AsyncInPendingWrapper in this test serves as a handler for WritePendingException, which can occur when sending too many messages one after another. */ @FixMethodOrder(MethodSorters.NAME_ASCENDING) @@ -94,21 +94,21 @@ public class WindowAdjustTest { } } - @Test(timeout=60*1000L) + @Test(timeout = 60 * 1000L) public void testTrafficHeavyLoad() throws Exception { - - try(SshClient client = SshClient.setUpDefaultClient()) { + + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - - try(final ClientSession session = client.connect("admin", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { + + try (final ClientSession session = client.connect("admin", "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity("admin"); session.auth().verify(); - - try(final ClientChannel channel = session.createShellChannel()) { + + 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); @@ -133,7 +133,7 @@ public class WindowAdjustTest { @Override public void write(int b) throws IOException { - if(String.valueOf((char)b).equals(endFile)) { + if (String.valueOf((char) b).equals(endFile)) { channel.close(true); } } @@ -248,14 +248,14 @@ public class WindowAdjustTest { @SuppressWarnings("synthetic-access") @Override public void operationComplete(final IoWriteFuture future) { - if(wasPending) { + if (wasPending) { pending.remove(); } writePendingIfAny(); } }); } catch (final WritePendingException e) { - if(!wasPending){ + if (!wasPending) { queueRequest(msg); } } @@ -267,7 +267,7 @@ public class WindowAdjustTest { } final Buffer msg = pending.peek(); - writeWithPendingDetection( msg, true); + writeWithPendingDetection(msg, true); } private void queueRequest(final Buffer msg) {
