http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java index c11e909..87793a4 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/scp/ScpTest.java @@ -38,6 +38,12 @@ import java.util.EnumSet; import java.util.Set; import java.util.concurrent.TimeUnit; +import ch.ethz.ssh2.Connection; +import ch.ethz.ssh2.ConnectionInfo; +import ch.ethz.ssh2.SCPClient; +import com.jcraft.jsch.ChannelExec; +import com.jcraft.jsch.JSch; +import com.jcraft.jsch.JSchException; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.common.Factory; @@ -66,14 +72,6 @@ import org.junit.runners.MethodSorters; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.jcraft.jsch.ChannelExec; -import com.jcraft.jsch.JSch; -import com.jcraft.jsch.JSchException; - -import ch.ethz.ssh2.Connection; -import ch.ethz.ssh2.ConnectionInfo; -import ch.ethz.ssh2.SCPClient; - /** * Test for SCP support. * @@ -90,7 +88,7 @@ public class ScpTest extends BaseTestSupport { public ScpTest() throws IOException { Path targetPath = detectTargetFolder().toPath(); Path parentPath = targetPath.getParent(); - final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String,Object>emptyMap()); + final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap()); fileSystemFactory = new FileSystemFactory() { @Override public FileSystem createFileSystem(Session session) throws IOException { @@ -125,7 +123,7 @@ public class ScpTest extends BaseTestSupport { if (session != null) { session.disconnect(); } - + if (sshd != null) { sshd.stop(true); } @@ -170,7 +168,7 @@ public class ScpTest extends BaseTestSupport { if (sb.length() > 0) { sb.setLength(0); // start again } - + sb.append(remoteComps[0]); for (int j = 1; j < remoteComps.length; j++) { String name = remoteComps[j]; @@ -178,11 +176,11 @@ public class ScpTest extends BaseTestSupport { sb.append(name); } slashify(sb, rnd); - + String path = sb.toString(); scp.upload(localPath, path); assertTrue("Remote file not ready for " + path, waitForFile(remoteFile, data.length, TimeUnit.SECONDS.toMillis(5L))); - + byte[] actual = Files.readAllBytes(remoteFile); assertArrayEquals("Mismatched uploaded data for " + path, data, actual); Files.delete(remoteFile); @@ -194,10 +192,10 @@ public class ScpTest extends BaseTestSupport { private static int slashify(StringBuilder sb, Random rnd) { int slashes = 1 /* at least one slash */ + rnd.random(Byte.SIZE); - for (int k=0; k < slashes; k++) { + for (int k = 0; k < slashes; k++) { sb.append('/'); } - + return slashes; } @@ -232,7 +230,7 @@ public class ScpTest extends BaseTestSupport { String secondPath = Utils.resolveRelativeRemotePath(parentPath, secondRemote); scp.upload(localPath, secondPath); assertFileLength(secondRemote, data.length, TimeUnit.SECONDS.toMillis(5L)); - + Path pathRemote = remoteDir.resolve("file-path.txt"); String pathPath = Utils.resolveRelativeRemotePath(parentPath, pathRemote); scp.upload(localFile, pathPath); @@ -375,16 +373,16 @@ public class ScpTest extends BaseTestSupport { writeFile(localOutFile, data); assertFalse("Remote folder already exists: " + remoteDir, Files.exists(remoteDir)); - + String localOutPath = localOutFile.toString(); String remoteOutPath = Utils.resolveRelativeRemotePath(parentPath, remoteOutFile); try { scp.upload(localOutPath, remoteOutPath); fail("Expected IOException for 1st time " + remoteOutPath); - } catch(IOException e) { + } catch (IOException e) { // ok } - + assertHierarchyTargetFolderExists(remoteDir); scp.upload(localOutPath, remoteOutPath); assertFileLength(remoteOutFile, data.length(), TimeUnit.SECONDS.toMillis(5L)); @@ -392,7 +390,7 @@ public class ScpTest extends BaseTestSupport { Path secondLocal = localDir.resolve(localOutFile.getFileName()); scp.download(remoteOutPath, Utils.resolveRelativeRemotePath(parentPath, secondLocal)); assertFileLength(secondLocal, data.length(), TimeUnit.SECONDS.toMillis(5L)); - + Path localPath = localDir.resolve("file-path.txt"); scp.download(remoteOutPath, Utils.resolveRelativeRemotePath(parentPath, localPath)); assertFileLength(localPath, data.length(), TimeUnit.SECONDS.toMillis(5L)); @@ -427,14 +425,14 @@ public class ScpTest extends BaseTestSupport { Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote")); Path remote1 = remoteDir.resolve(local1.getFileName()); String remote1Path = Utils.resolveRelativeRemotePath(parentPath, remote1); - String[] locals = { local1.toString(), local2.toString() }; + String[] locals = {local1.toString(), local2.toString()}; try { scp.upload(locals, remote1Path); fail("Unexpected upload success to missing remote file: " + remote1Path); } catch (IOException e) { // Ok } - + Files.write(remote1, data); try { scp.upload(locals, remote1Path); @@ -445,7 +443,7 @@ public class ScpTest extends BaseTestSupport { Path remoteSubDir = assertHierarchyTargetFolderExists(remoteDir.resolve("dir")); scp.upload(locals, Utils.resolveRelativeRemotePath(parentPath, remoteSubDir)); - + Path remoteSub1 = remoteSubDir.resolve(local1.getFileName()); assertFileLength(remoteSub1, data.length, TimeUnit.SECONDS.toMillis(5L)); @@ -455,7 +453,7 @@ public class ScpTest extends BaseTestSupport { String[] remotes = { Utils.resolveRelativeRemotePath(parentPath, remoteSub1), Utils.resolveRelativeRemotePath(parentPath, remoteSub2), - }; + }; try { scp.download(remotes, Utils.resolveRelativeRemotePath(parentPath, local1)); @@ -463,7 +461,7 @@ public class ScpTest extends BaseTestSupport { } catch (IOException e) { // Ok } - + Path localSubDir = localDir.resolve("dir"); try { scp.download(remotes, localSubDir); @@ -507,7 +505,7 @@ public class ScpTest extends BaseTestSupport { Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote")); scp.upload(localSubDir, Utils.resolveRelativeRemotePath(parentPath, remoteDir), ScpClient.Option.Recursive); - + Path remoteSubDir = remoteDir.resolve(localSubDir.getFileName()); assertFileLength(remoteSubDir.resolve(localSub1.getFileName()), data.length, TimeUnit.SECONDS.toMillis(5L)); assertFileLength(remoteSubDir.resolve(localSub2.getFileName()), data.length, TimeUnit.SECONDS.toMillis(5L)); @@ -647,7 +645,7 @@ public class ScpTest extends BaseTestSupport { Path remote1 = remoteDir.resolve(local1.getFileName()); assertFileLength(remote1, data.length, TimeUnit.SECONDS.toMillis(5L)); - + File remFile1 = remote1.toFile(); assertLastModifiedTimeEquals(remFile1, lcl1ModSet, lastModSecs); @@ -731,8 +729,7 @@ public class ScpTest extends BaseTestSupport { .append('[').append(new Date(expectedMillis).toString()).append(']') .append(", actual=").append(String.valueOf(actualSeconds)) .append('[').append(new Date(actualMillis).toString()).append(']') - .println() - ; + .println(); } } else { assertEquals("Mismatched last modified time for " + file.getAbsolutePath(), expectedSeconds, actualSeconds); @@ -740,8 +737,8 @@ public class ScpTest extends BaseTestSupport { } private static byte[] writeFile(Path path, String data) throws IOException { - try(OutputStream fos = Files.newOutputStream(path)) { - byte[] bytes = data.getBytes(StandardCharsets.UTF_8); + try (OutputStream fos = Files.newOutputStream(path)) { + byte[] bytes = data.getBytes(StandardCharsets.UTF_8); fos.write(bytes); return bytes; } @@ -752,7 +749,7 @@ public class ScpTest extends BaseTestSupport { session = getJschSession(); try { String data = getCurrentTestName() + "\n"; - + String unixDir = "target/scp"; String fileName = getCurrentTestName() + ".txt"; String unixPath = unixDir + "/" + fileName; @@ -761,27 +758,27 @@ public class ScpTest extends BaseTestSupport { Utils.deleteRecursive(root); root.mkdirs(); assertTrue(root.exists()); - + target.delete(); assertFalse(target.exists()); sendFile(unixPath, fileName, data); assertFileLength(target, data.length(), TimeUnit.SECONDS.toMillis(5L)); - + target.delete(); assertFalse(target.exists()); sendFile(unixDir, fileName, data); assertFileLength(target, data.length(), TimeUnit.SECONDS.toMillis(5L)); - + sendFileError("target", ScpHelper.SCP_COMMAND_PREFIX, data); - + readFileError(unixDir); - + assertEquals("Mismatched file data", data, readFile(unixPath, target.length())); assertEquals("Mismatched dir data", data, readDir(unixDir, fileName, target.length())); - + target.delete(); root.delete(); - + sendDir("target", ScpHelper.SCP_COMMAND_PREFIX, fileName, data); assertFileLength(target, data.length(), TimeUnit.SECONDS.toMillis(5L)); } finally { @@ -802,30 +799,30 @@ public class ScpTest extends BaseTestSupport { String fileName = "file.txt"; Path remoteFile = remoteDir.resolve(fileName); String mode = ScpHelper.getOctalPermissions(EnumSet.of( - PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE, - PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, - PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE - )); + PosixFilePermission.OTHERS_READ, PosixFilePermission.OTHERS_WRITE, + PosixFilePermission.GROUP_READ, PosixFilePermission.GROUP_WRITE, + PosixFilePermission.OWNER_READ, PosixFilePermission.OWNER_WRITE + )); final Connection conn = new Connection("localhost", port); try { ConnectionInfo info = conn.connect(null, (int) TimeUnit.SECONDS.toMillis(5L), (int) TimeUnit.SECONDS.toMillis(11L)); System.out.println("Connected: kex=" + info.keyExchangeAlgorithm + ", key-type=" + info.serverHostKeyAlgorithm - + ", c2senc=" + info.clientToServerCryptoAlgorithm + ", s2cenc=" + info.serverToClientCryptoAlgorithm - + ", c2mac=" + info.clientToServerMACAlgorithm + ", s2cmac=" + info.serverToClientMACAlgorithm); + + ", c2senc=" + info.clientToServerCryptoAlgorithm + ", s2cenc=" + info.serverToClientCryptoAlgorithm + + ", c2mac=" + info.clientToServerMACAlgorithm + ", s2cmac=" + info.serverToClientMACAlgorithm); conn.authenticateWithPassword(getCurrentTestName(), getCurrentTestName()); final SCPClient scp_client = new SCPClient(conn); - try(OutputStream output = scp_client.put(fileName, expected.length, remotePath, mode)) { + try (OutputStream output = scp_client.put(fileName, expected.length, remotePath, mode)) { output.write(expected); } - + assertTrue("Remote file not created: " + remoteFile, Files.exists(remoteFile)); byte[] remoteData = Files.readAllBytes(remoteFile); assertArrayEquals("Mismatched remote put data", expected, remoteData); - + Arrays.fill(remoteData, (byte) 0); // make sure we start with a clean slate - try(InputStream input = scp_client.get(remotePath + "/" + fileName)) { + try (InputStream input = scp_client.get(remotePath + "/" + fileName)) { int readLen = input.read(remoteData); assertEquals("Mismatched remote get data size", expected.length, readLen); // make sure we reached EOF @@ -845,8 +842,8 @@ public class ScpTest extends BaseTestSupport { int namePos = path.lastIndexOf('/'); String fileName = (namePos >= 0) ? path.substring(namePos + 1) : path; - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { os.write(0); os.flush(); @@ -856,7 +853,7 @@ public class ScpTest extends BaseTestSupport { int length = Integer.parseInt(header.substring(6, header.indexOf(' ', 6))); os.write(0); os.flush(); - + byte[] buffer = new byte[length]; length = is.read(buffer, 0, buffer.length); assertEquals("Mismatched read data length for " + path, length, buffer.length); @@ -876,8 +873,8 @@ public class ScpTest extends BaseTestSupport { c.setCommand("scp -r -f " + path); c.connect(); - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { os.write(0); os.flush(); @@ -913,13 +910,13 @@ public class ScpTest extends BaseTestSupport { protected String readFileError(String path) throws Exception { ChannelExec c = (ChannelExec) session.openChannel("exec"); - String command = "scp -f " + path; + String command = "scp -f " + path; c.setCommand(command); c.connect(); - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { - + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { + os.write(0); os.flush(); assertEquals("Mismatched response for command: " + command, 2, is.read()); @@ -935,11 +932,11 @@ public class ScpTest extends BaseTestSupport { c.setCommand(command); c.connect(); - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { assertAckReceived(is, command); - assertAckReceived(os, is, "C7777 " + data.length() + " " + name); + assertAckReceived(os, is, "C7777 " + data.length() + " " + name); os.write(data.getBytes(StandardCharsets.UTF_8)); os.flush(); @@ -966,12 +963,12 @@ public class ScpTest extends BaseTestSupport { protected void sendFileError(String path, String name, String data) throws Exception { ChannelExec c = (ChannelExec) session.openChannel("exec"); - String command = "scp -t " + path; + String command = "scp -t " + path; c.setCommand(command); c.connect(); - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { assertAckReceived(is, command); @@ -989,9 +986,9 @@ public class ScpTest extends BaseTestSupport { String command = "scp -t -r " + path; c.setCommand(command); c.connect(); - - try(OutputStream os = c.getOutputStream(); - InputStream is = c.getInputStream()) { + + try (OutputStream os = c.getOutputStream(); + InputStream is = c.getInputStream()) { assertAckReceived(is, command); assertAckReceived(os, is, "D0755 0 " + dirName); @@ -1003,7 +1000,7 @@ public class ScpTest extends BaseTestSupport { os.write(0); os.flush(); - + os.write("E\n".getBytes(StandardCharsets.UTF_8)); os.flush(); assertAckReceived(is, "Signal end of " + path);
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionImplTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionImplTest.java b/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionImplTest.java index f73a785..f7608ee 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionImplTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/session/ClientSessionImplTest.java @@ -54,22 +54,22 @@ public class ClientSessionImplTest extends BaseTestSupport { public void testAddRemoveIdentities() throws Exception { ClientFactoryManager client = Mockito.mock(ClientFactoryManager.class); Mockito.when(client.getTcpipForwarderFactory()).thenReturn(DefaultTcpipForwarderFactory.INSTANCE); - + Factory<Random> randomFactory = new SingletonRandomFactory(JceRandomFactory.INSTANCE); Mockito.when(client.getRandomFactory()).thenReturn(randomFactory); - + List<ServiceFactory> serviceFactories = Arrays.asList( - ClientUserAuthServiceFactory.INSTANCE, - ClientConnectionServiceFactory.INSTANCE - ); + ClientUserAuthServiceFactory.INSTANCE, + ClientConnectionServiceFactory.INSTANCE + ); Mockito.when(client.getServiceFactories()).thenReturn(serviceFactories); - try(ClientSession session = new ClientSessionImpl(client, Mockito.mock(IoSession.class)) { + try (ClientSession session = new ClientSessionImpl(client, Mockito.mock(IoSession.class)) { @Override protected void sendClientIdentification() { // ignored } - + @Override protected byte[] sendKexInit() throws IOException { return GenericUtils.EMPTY_BYTE_ARRAY; @@ -84,17 +84,17 @@ public class ClientSessionImplTest extends BaseTestSupport { String expected = getCurrentTestName(); assertNull("Unexpected initial password identity", session.removePasswordIdentity(expected)); session.addPasswordIdentity(expected); - + String actual = session.removePasswordIdentity(expected); assertSame("Mismatched removed password identity", expected, actual); assertNull("Password identity not removed", session.removePasswordIdentity(expected)); } - + { KeyPair expected = new KeyPair(Mockito.mock(PublicKey.class), Mockito.mock(PrivateKey.class)); assertNull("Unexpected initial pubket identity", session.removePublicKeyIdentity(expected)); session.addPublicKeyIdentity(expected); - + KeyPair actual = session.removePublicKeyIdentity(expected); assertSame("Mismatched removed pubkey identity", expected, actual); assertNull("Pubkey identity not removed", session.removePublicKeyIdentity(expected)); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java index cb820d4..bf61f80 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/AbstractSftpClientTestSupport.java @@ -51,7 +51,7 @@ public abstract class AbstractSftpClientTestSupport extends BaseTestSupport { protected AbstractSftpClientTestSupport() throws IOException { Path targetPath = detectTargetFolder().toPath(); Path parentPath = targetPath.getParent(); - rootFileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String,Object>emptyMap()); + rootFileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap()); fileSystemFactory = new FileSystemFactory() { @Override public FileSystem createFileSystem(Session session) throws IOException { @@ -71,7 +71,7 @@ public abstract class AbstractSftpClientTestSupport extends BaseTestSupport { sshd.start(); port = sshd.getPort(); } - + protected void tearDownServer() throws Exception { if (sshd != null) { try { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/DefaultCloseableHandleTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/DefaultCloseableHandleTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/DefaultCloseableHandleTest.java index 1f9c6db..92d8d94 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/DefaultCloseableHandleTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/DefaultCloseableHandleTest.java @@ -48,14 +48,14 @@ public class DefaultCloseableHandleTest extends BaseTestSupport { final byte[] id = getCurrentTestName().getBytes(StandardCharsets.UTF_8); SftpClient client = Mockito.mock(SftpClient.class); Mockito.doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - Handle handle = (Handle) args[0]; - assertArrayEquals("Mismatched closing handle", id, handle.getIdentifier()); - return null; - } - }).when(client).close(Matchers.any(Handle.class)); + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + Handle handle = (Handle) args[0]; + assertArrayEquals("Mismatched closing handle", id, handle.getIdentifier()); + return null; + } + }).when(client).close(Matchers.any(Handle.class)); CloseableHandle handle = new DefaultCloseableHandle(client, id); try { @@ -73,19 +73,19 @@ public class DefaultCloseableHandleTest extends BaseTestSupport { SftpClient client = Mockito.mock(SftpClient.class); final AtomicBoolean closeCalled = new AtomicBoolean(false); Mockito.doAnswer(new Answer<Void>() { - @Override - public Void answer(InvocationOnMock invocation) throws Throwable { - Object[] args = invocation.getArguments(); - assertFalse("Close already called on handle=" + args[0], closeCalled.getAndSet(true)); - return null; - } - }).when(client).close(Matchers.any(Handle.class)); + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + Object[] args = invocation.getArguments(); + assertFalse("Close already called on handle=" + args[0], closeCalled.getAndSet(true)); + return null; + } + }).when(client).close(Matchers.any(Handle.class)); CloseableHandle handle = new DefaultCloseableHandle(client, getCurrentTestName().getBytes(StandardCharsets.UTF_8)); - for (int index=0; index < Byte.SIZE; index++) { + for (int index = 0; index < Byte.SIZE; index++) { handle.close(); } - + assertTrue("Close method not called", closeCalled.get()); } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpCommandMain.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpCommandMain.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpCommandMain.java index 8cca06f..af08660 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpCommandMain.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpCommandMain.java @@ -22,6 +22,7 @@ package org.apache.sshd.client.subsystem.sftp; /** * Just a test class used to invoke {@link SftpCommand#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 SftpCommandMain { http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java index 946dd57..99777b5 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpFileSystemTest.java @@ -85,7 +85,7 @@ public class SftpFileSystemTest extends BaseTestSupport { public SftpFileSystemTest() throws IOException { Path targetPath = detectTargetFolder().toPath(); Path parentPath = targetPath.getParent(); - final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String,Object>emptyMap()); + final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String, Object>emptyMap()); fileSystemFactory = new FileSystemFactory() { @Override public FileSystem createFileSystem(Session session) throws IOException { @@ -116,15 +116,15 @@ public class SftpFileSystemTest extends BaseTestSupport { @Test public void testFileSystem() throws Exception { - try(FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), - new TreeMap<String,Object>() { + try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), + new TreeMap<String, Object>() { private static final long serialVersionUID = 1L; // we're not serializing it - + { put(SftpFileSystemProvider.READ_BUFFER_PROP_NAME, Integer.valueOf(IoUtils.DEFAULT_COPY_SIZE)); put(SftpFileSystemProvider.WRITE_BUFFER_PROP_NAME, Integer.valueOf(IoUtils.DEFAULT_COPY_SIZE)); } - })) { + })) { testFileSystem(fs); } } @@ -135,15 +135,15 @@ public class SftpFileSystemTest extends BaseTestSupport { Path lclSftp = Utils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); Utils.deleteRecursive(lclSftp); - try(FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), - new TreeMap<String,Object>() { + try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), + new TreeMap<String, Object>() { private static final long serialVersionUID = 1L; // we're not serializing it - + { put(SftpFileSystemProvider.READ_BUFFER_PROP_NAME, Integer.valueOf(SftpClient.MIN_READ_BUFFER_SIZE)); put(SftpFileSystemProvider.WRITE_BUFFER_PROP_NAME, Integer.valueOf(SftpClient.MIN_WRITE_BUFFER_SIZE)); } - })) { + })) { Path parentPath = targetPath.getParent(); Path clientFolder = lclSftp.resolve("client"); @@ -151,10 +151,10 @@ public class SftpFileSystemTest extends BaseTestSupport { Path file = fs.getPath(remFilePath); assertHierarchyTargetFolderExists(file.getParent()); Files.write(file, (getCurrentTestName() + "\n").getBytes(StandardCharsets.UTF_8)); - + Map<String, Object> attrs = Files.readAttributes(file, "posix:*"); assertNotNull("NO attributes read for " + file, attrs); - + Files.setAttribute(file, "basic:size", Long.valueOf(2L)); Files.setAttribute(file, "posix:permissions", PosixFilePermissions.fromString("rwxr-----")); Files.setAttribute(file, "basic:lastModifiedTime", FileTime.fromMillis(100000L)); @@ -185,7 +185,7 @@ public class SftpFileSystemTest extends BaseTestSupport { Utils.deleteRecursive(rootNative); assertHierarchyTargetFolderExists(rootNative); - try(FileSystem fs = FileSystems.newFileSystem(URI.create("root:" + rootNative.toUri().toString() + "!/"), null)) { + try (FileSystem fs = FileSystems.newFileSystem(URI.create("root:" + rootNative.toUri().toString() + "!/"), null)) { Path dir = assertHierarchyTargetFolderExists(fs.getPath("test/foo")); System.out.println("Created " + dir); } @@ -193,21 +193,21 @@ public class SftpFileSystemTest extends BaseTestSupport { @Test public void testFileStore() throws IOException { - try(FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.<String,Object>emptyMap())) { + try (FileSystem fs = FileSystems.newFileSystem(createDefaultFileSystemURI(), Collections.<String, Object>emptyMap())) { Iterable<FileStore> iter = fs.getFileStores(); assertTrue("Not a list", iter instanceof List<?>); - + List<FileStore> list = (List<FileStore>) iter; assertEquals("Mismatched stores count", 1, list.size()); - + FileStore store = list.get(0); assertEquals("Mismatched type", SftpConstants.SFTP_SUBSYSTEM_NAME, store.type()); assertFalse("Read-only ?", store.isReadOnly()); - + for (String name : SftpFileSystem.SUPPORTED_VIEWS) { assertTrue("Unsupported view name: " + name, store.supportsFileAttributeView(name)); } - + for (Class<? extends FileAttributeView> type : SftpFileSystemProvider.SUPPORTED_VIEWS) { assertTrue("Unsupported view type: " + type.getSimpleName(), store.supportsFileAttributeView(type)); } @@ -216,26 +216,26 @@ public class SftpFileSystemTest extends BaseTestSupport { @Test public void testMultipleFileStoresOnSameProvider() throws IOException { - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); SftpFileSystemProvider provider = new SftpFileSystemProvider(client); Collection<SftpFileSystem> fsList = new LinkedList<>(); try { Collection<String> idSet = new HashSet<>(); - for (int index=0; index < 4; index++) { + for (int index = 0; index < 4; index++) { String credentials = getCurrentTestName() + "-user-" + index; - SftpFileSystem expected = provider.newFileSystem(createFileSystemURI(credentials), Collections.<String,Object>emptyMap()); + SftpFileSystem expected = provider.newFileSystem(createFileSystemURI(credentials), Collections.<String, Object>emptyMap()); fsList.add(expected); String id = expected.getId(); assertTrue("Non unique file system id: " + id, idSet.add(id)); - + SftpFileSystem actual = provider.getFileSystem(id); assertSame("Mismatched cached instances for " + id, expected, actual); System.out.println("Created file system id: " + id); } - + for (SftpFileSystem fs : fsList) { String id = fs.getId(); fs.close(); @@ -246,7 +246,7 @@ public class SftpFileSystemTest extends BaseTestSupport { for (FileSystem fs : fsList) { try { fs.close(); - } catch(IOException e) { + } catch (IOException e) { err = GenericUtils.accumulateException(err, e); } } @@ -257,46 +257,46 @@ public class SftpFileSystemTest extends BaseTestSupport { throw err; } } - } + } } @Test public void testSftpVersionSelector() throws Exception { final AtomicInteger selected = new AtomicInteger(-1); SftpVersionSelector selector = new SftpVersionSelector() { - @Override - public int selectVersion(int current, List<Integer> available) { - int numAvailable = GenericUtils.size(available); - Integer maxValue = null; - if (numAvailable == 1) { - maxValue = available.get(0); - } else { - for (Integer v : available) { - if (v.intValue() == current) { - continue; - } - - if ((maxValue == null) || (maxValue.intValue() < v.intValue())) { - maxValue = v; - } + @Override + public int selectVersion(int current, List<Integer> available) { + int numAvailable = GenericUtils.size(available); + Integer maxValue = null; + if (numAvailable == 1) { + maxValue = available.get(0); + } else { + for (Integer v : available) { + if (v.intValue() == current) { + continue; } - } - selected.set(maxValue.intValue()); - return selected.get(); + if ((maxValue == null) || (maxValue.intValue() < v.intValue())) { + maxValue = v; + } + } } - }; - try(SshClient client = SshClient.setUpDefaultClient()) { + + selected.set(maxValue.intValue()); + return selected.get(); + } + }; + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(FileSystem fs = session.createSftpFileSystem(selector)) { + try (FileSystem fs = session.createSftpFileSystem(selector)) { assertTrue("Not an SftpFileSystem", fs instanceof SftpFileSystem); - - try(SftpClient sftp = ((SftpFileSystem) fs).getClient()) { + + try (SftpClient sftp = ((SftpFileSystem) fs).getClient()) { assertEquals("Mismatched negotiated version", selected.get(), sftp.getVersion()); } @@ -308,11 +308,11 @@ public class SftpFileSystemTest extends BaseTestSupport { } } - + private void testFileSystem(FileSystem fs) throws Exception { Iterable<Path> rootDirs = fs.getRootDirectories(); for (Path root : rootDirs) { - String rootName = root.toString(); + String rootName = root.toString(); try (DirectoryStream<Path> ds = Files.newDirectoryStream(root)) { for (Path child : ds) { String name = child.getFileName().toString(); @@ -320,7 +320,7 @@ public class SftpFileSystemTest extends BaseTestSupport { assertNotEquals("Unexpected dotdot name", "..", name); System.out.append('\t').append('[').append(rootName).append("] ").println(child); } - } catch(IOException | RuntimeException e) { + } catch (IOException | RuntimeException e) { // TODO on Windows one might get share problems for *.sys files // e.g. "C:\hiberfil.sys: The process cannot access the file because it is being used by another process" // for now, Windows is less of a target so we are lenient with it @@ -345,7 +345,7 @@ public class SftpFileSystemTest extends BaseTestSupport { Path file1 = fs.getPath(remFile1Path); assertHierarchyTargetFolderExists(file1.getParent()); - String expected="Hello world: " + getCurrentTestName(); + String expected = "Hello world: " + getCurrentTestName(); { Files.write(file1, expected.getBytes(StandardCharsets.UTF_8)); String buf = new String(Files.readAllBytes(file1), StandardCharsets.UTF_8); http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java index 9eb4639..70481de 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/SftpTest.java @@ -18,11 +18,6 @@ */ package org.apache.sshd.client.subsystem.sftp; -import static org.apache.sshd.common.subsystem.sftp.SftpConstants.SSH_FX_FILE_ALREADY_EXISTS; -import static org.apache.sshd.common.subsystem.sftp.SftpConstants.SSH_FX_NO_SUCH_FILE; -import static org.apache.sshd.common.subsystem.sftp.SftpConstants.S_IRUSR; -import static org.apache.sshd.common.subsystem.sftp.SftpConstants.S_IWUSR; - import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; @@ -43,6 +38,8 @@ import java.util.Vector; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import com.jcraft.jsch.ChannelSftp; +import com.jcraft.jsch.JSch; import org.apache.sshd.client.SshClient; import org.apache.sshd.client.session.ClientSession; import org.apache.sshd.client.subsystem.sftp.extensions.BuiltinSftpClientExtensions; @@ -71,8 +68,10 @@ import org.junit.Ignore; import org.junit.Test; import org.junit.runners.MethodSorters; -import com.jcraft.jsch.ChannelSftp; -import com.jcraft.jsch.JSch; +import static org.apache.sshd.common.subsystem.sftp.SftpConstants.SSH_FX_FILE_ALREADY_EXISTS; +import static org.apache.sshd.common.subsystem.sftp.SftpConstants.SSH_FX_NO_SUCH_FILE; +import static org.apache.sshd.common.subsystem.sftp.SftpConstants.S_IRUSR; +import static org.apache.sshd.common.subsystem.sftp.SftpConstants.S_IWUSR; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class SftpTest extends AbstractSftpClientTestSupport { @@ -98,7 +97,7 @@ public class SftpTest extends AbstractSftpClientTestSupport { if (session != null) { session.disconnect(); } - + tearDownServer(); } @@ -111,25 +110,25 @@ public class SftpTest extends AbstractSftpClientTestSupport { @Test public void testNormalizeRemoteRootValues() throws Exception { - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(SftpClient sftp = session.createSftpClient()) { + try (SftpClient sftp = session.createSftpClient()) { StringBuilder sb = new StringBuilder(Long.SIZE + 1); String expected = sftp.canonicalPath("/"); for (int i = 0; i < Long.SIZE; i++) { if (sb.length() > 0) { sb.setLength(0); } - + for (int j = 1; j <= i; j++) { sb.append('/'); } - + String remotePath = sb.toString(); String actual = sftp.canonicalPath(remotePath); assertEquals("Mismatched roots for " + remotePath.length() + " slashes", expected, actual); @@ -151,23 +150,23 @@ public class SftpTest extends AbstractSftpClientTestSupport { String file = Utils.resolveRelativeRemotePath(parentPath, testFile); String[] comps = GenericUtils.split(file, '/'); - try(SshClient client = SshClient.setUpDefaultClient()) { + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - + Factory<? extends Random> factory = client.getRandomFactory(); Random rnd = factory.create(); try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(SftpClient sftp = session.createSftpClient()) { + try (SftpClient sftp = session.createSftpClient()) { StringBuilder sb = new StringBuilder(file.length() + comps.length); String expected = sftp.canonicalPath(file); for (int i = 0; i < file.length(); i++) { if (sb.length() > 0) { sb.setLength(0); } - + sb.append(comps[0]); for (int j = 1; j < comps.length; j++) { String name = comps[j]; @@ -175,7 +174,7 @@ public class SftpTest extends AbstractSftpClientTestSupport { sb.append(name); } slashify(sb, rnd); - + if (rnd.random(Byte.SIZE) < (Byte.SIZE / 2)) { sb.append('.'); } @@ -193,10 +192,10 @@ public class SftpTest extends AbstractSftpClientTestSupport { private static int slashify(StringBuilder sb, Random rnd) { int slashes = 1 /* at least one slash */ + rnd.random(Byte.SIZE); - for (int k=0; k < slashes; k++) { + for (int k = 0; k < slashes; k++) { sb.append('/'); } - + return slashes; } @@ -212,9 +211,9 @@ public class SftpTest extends AbstractSftpClientTestSupport { File javaFile = testFile.toFile(); assertHierarchyTargetFolderExists(javaFile.getParentFile()); - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); @@ -222,11 +221,11 @@ public class SftpTest extends AbstractSftpClientTestSupport { javaFile.createNewFile(); javaFile.setWritable(false, false); javaFile.setReadable(false, false); - + try (SftpClient sftp = session.createSftpClient()) { - boolean isWindows = OsUtils.isWin32(); - - try(SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { + boolean isWindows = OsUtils.isWin32(); + + try (SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { // NOTE: on Windows files are always readable // see https://svn.apache.org/repos/asf/harmony/enhanced/java/branches/java6/classlib/modules/luni/src/test/api/windows/org/apache/harmony/luni/tests/java/io/WinFileTest.java assertTrue("Empty read should have failed on " + file, isWindows); @@ -235,49 +234,49 @@ public class SftpTest extends AbstractSftpClientTestSupport { throw e; } } - - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { + + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { fail("Empty write should have failed on " + file); } catch (IOException e) { // ok } - - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate))) { + + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate))) { // NOTE: on Windows files are always readable assertTrue("Empty truncate should have failed on " + file, isWindows); } catch (IOException e) { // ok } - + // NOTE: on Windows files are always readable - int perms=sftp.stat(file).perms; - int permsMask=S_IWUSR | (isWindows ? 0 : S_IRUSR); + int perms = sftp.stat(file).perms; + int permsMask = S_IWUSR | (isWindows ? 0 : S_IRUSR); assertEquals("Mismatched permissions for " + file + ": 0x" + Integer.toHexString(perms), 0, (perms & permsMask)); - + javaFile.setWritable(true, false); - - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate, SftpClient.OpenMode.Write))) { + + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate, SftpClient.OpenMode.Write))) { // OK should succeed assertTrue("Handle not marked as open for file=" + file, h.isOpen()); } - + byte[] d = "0123456789\n".getBytes(StandardCharsets.UTF_8); - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { sftp.write(h, 0, d, 0, d.length); sftp.write(h, d.length, d, 0, d.length); } - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { sftp.write(h, d.length * 2, d, 0, d.length); } - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write))) { byte[] overwrite = "-".getBytes(StandardCharsets.UTF_8); sftp.write(h, 3L, overwrite, 0, 1); d[3] = overwrite[0]; } - try(SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { + try (SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { // NOTE: on Windows files are always readable assertTrue("Data read should have failed on " + file, isWindows); } catch (IOException e) { @@ -285,11 +284,11 @@ public class SftpTest extends AbstractSftpClientTestSupport { throw e; } } - + javaFile.setReadable(true, false); - + byte[] buf = new byte[3]; - try(SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { + try (SftpClient.CloseableHandle h = sftp.open(file /* no mode == read */)) { int l = sftp.read(h, 2L, buf, 0, buf.length); String expected = new String(d, 2, l, StandardCharsets.UTF_8); String actual = new String(buf, 0, l, StandardCharsets.UTF_8); @@ -304,7 +303,7 @@ public class SftpTest extends AbstractSftpClientTestSupport { @Test public void testClient() throws Exception { - 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()) { @@ -324,17 +323,18 @@ public class SftpTest extends AbstractSftpClientTestSupport { * this test is meant to test out write's logic, to ensure that internal chunking (based on Buffer.MAX_LEN) is * functioning properly. To do this, we write a variety of file sizes, both smaller and larger than Buffer.MAX_LEN. * in addition, this test ensures that improper arguments passed in get caught with an IllegalArgumentException + * * @throws Exception upon any uncaught exception or failure */ @Test public void testWriteChunking() throws Exception { - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - + Path targetPath = detectTargetFolder().toPath(); Path lclSftp = Utils.resolve(targetPath, SftpConstants.SFTP_SUBSYSTEM_NAME, getClass().getSimpleName(), getCurrentTestName()); Utils.deleteRecursive(lclSftp); @@ -342,26 +342,26 @@ public class SftpTest extends AbstractSftpClientTestSupport { Path parentPath = targetPath.getParent(); Path clientFolder = assertHierarchyTargetFolderExists(lclSftp).resolve("client"); String dir = Utils.resolveRelativeRemotePath(parentPath, clientFolder); - - try(SftpClient sftp = session.createSftpClient()) { + + try (SftpClient sftp = session.createSftpClient()) { sftp.mkdir(dir); - + uploadAndVerifyFile(sftp, clientFolder, dir, 0, "emptyFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, 1000, "smallFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, ByteArrayBuffer.MAX_LEN - 1, "bufferMaxLenMinusOneFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, ByteArrayBuffer.MAX_LEN, "bufferMaxLenFile.txt"); // were chunking not implemented, these would fail. these sizes should invoke our internal chunking mechanism uploadAndVerifyFile(sftp, clientFolder, dir, ByteArrayBuffer.MAX_LEN + 1, "bufferMaxLenPlusOneFile.txt"); - uploadAndVerifyFile(sftp, clientFolder, dir, (int)(1.5 * ByteArrayBuffer.MAX_LEN), "1point5BufferMaxLenFile.txt"); + uploadAndVerifyFile(sftp, clientFolder, dir, (int) (1.5 * ByteArrayBuffer.MAX_LEN), "1point5BufferMaxLenFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, (2 * ByteArrayBuffer.MAX_LEN) - 1, "2TimesBufferMaxLenMinusOneFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, 2 * ByteArrayBuffer.MAX_LEN, "2TimesBufferMaxLenFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, (2 * ByteArrayBuffer.MAX_LEN) + 1, "2TimesBufferMaxLenPlusOneFile.txt"); uploadAndVerifyFile(sftp, clientFolder, dir, 200000, "largerFile.txt"); - + // test erroneous calls that check for negative values Path invalidPath = clientFolder.resolve(getCurrentTestName() + "-invalid"); testInvalidParams(sftp, invalidPath, Utils.resolveRelativeRemotePath(parentPath, invalidPath)); - + // cleanup sftp.rmdir(dir); } @@ -375,7 +375,7 @@ public class SftpTest extends AbstractSftpClientTestSupport { // generate random file and upload it String randomData = randomString(5); byte[] randomBytes = randomData.getBytes(StandardCharsets.UTF_8); - try(SftpClient.CloseableHandle handle = sftp.open(filePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create))) { + try (SftpClient.CloseableHandle handle = sftp.open(filePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create))) { try { sftp.write(handle, -1, randomBytes, 0, 0); fail("should not have been able to write file with invalid file offset for " + filePath); @@ -416,7 +416,7 @@ public class SftpTest extends AbstractSftpClientTestSupport { // generate random file and upload it String remotePath = remoteDir + "/" + filename; String randomData = randomString(size); - try(SftpClient.CloseableHandle handle = sftp.open(remotePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create))) { + try (SftpClient.CloseableHandle handle = sftp.open(remotePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create))) { sftp.write(handle, 0, randomData.getBytes(StandardCharsets.UTF_8), 0, randomData.length()); } @@ -441,8 +441,8 @@ public class SftpTest extends AbstractSftpClientTestSupport { Path target = assertHierarchyTargetFolderExists(lclSftp).resolve("file.txt"); String remotePath = Utils.resolveRelativeRemotePath(targetPath.getParent(), target); - final int NUM_ITERATIONS=10; - StringBuilder sb = new StringBuilder(d.length() * NUM_ITERATIONS * NUM_ITERATIONS); + final int NUM_ITERATIONS = 10; + StringBuilder sb = new StringBuilder(d.length() * NUM_ITERATIONS * NUM_ITERATIONS); for (int j = 1; j <= NUM_ITERATIONS; j++) { if (sb.length() > 0) { sb.setLength(0); @@ -474,11 +474,11 @@ public class SftpTest extends AbstractSftpClientTestSupport { c.connect(); try { c.put(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)), remotePath); - + assertTrue("Remote file not created after initial write: " + localPath, Files.exists(localPath)); assertEquals("Mismatched data read from " + remotePath, data, readFile(remotePath)); - - try(OutputStream os = c.put(remotePath, null, ChannelSftp.APPEND, appendOffset)) { + + try (OutputStream os = c.put(remotePath, null, ChannelSftp.APPEND, appendOffset)) { os.write(extraData.getBytes(StandardCharsets.UTF_8)); } } finally { @@ -486,7 +486,7 @@ public class SftpTest extends AbstractSftpClientTestSupport { } assertTrue("Remote file not created after data update: " + localPath, Files.exists(localPath)); - + String expected = data.substring(0, data.length() + appendOffset) + extraData; String actual = readFile(remotePath); assertEquals("Mismatched final file data in " + remotePath, expected, actual); @@ -519,14 +519,14 @@ public class SftpTest extends AbstractSftpClientTestSupport { Path parentPath = targetPath.getParent(); Path clientFolder = assertHierarchyTargetFolderExists(lclSftp.resolve("client")); - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(SftpClient sftp = session.createSftpClient()) { + + try (SftpClient sftp = session.createSftpClient()) { Path file1 = clientFolder.resolve("file-1.txt"); String file1Path = Utils.resolveRelativeRemotePath(parentPath, file1); try (OutputStream os = sftp.write(file1Path, SftpClient.MIN_WRITE_BUFFER_SIZE)) { @@ -543,11 +543,11 @@ public class SftpTest extends AbstractSftpClientTestSupport { } catch (org.apache.sshd.client.subsystem.sftp.SftpException e) { assertEquals("Mismatched status for failed rename of " + file2Path + " => " + file3Path, SSH_FX_NO_SUCH_FILE, e.getStatus()); } - + try (OutputStream os = sftp.write(file2Path, SftpClient.MIN_WRITE_BUFFER_SIZE)) { - os.write("H".getBytes(StandardCharsets.UTF_8)); + os.write("h".getBytes(StandardCharsets.UTF_8)); } - + try { sftp.rename(file1Path, file2Path); fail("Unxpected rename success of " + file1Path + " => " + file2Path); @@ -565,25 +565,25 @@ public class SftpTest extends AbstractSftpClientTestSupport { @Test public void testServerExtensionsDeclarations() throws Exception { - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(SftpClient sftp = session.createSftpClient()) { - Map<String,byte[]> extensions = sftp.getServerExtensions(); - for (String name : new String[] { + try (SftpClient sftp = session.createSftpClient()) { + Map<String, byte[]> extensions = sftp.getServerExtensions(); + for (String name : new String[]{ SftpConstants.EXT_NEWLINE, SftpConstants.EXT_VERSIONS, - SftpConstants.EXT_VENDORID, + SftpConstants.EXT_VENDOR_ID, SftpConstants.EXT_SUPPORTED, SftpConstants.EXT_SUPPORTED2 - }) { + }) { assertTrue("Missing extension=" + name, extensions.containsKey(name)); } - - Map<String,?> data = ParserUtils.parse(extensions); - for (Map.Entry<String,?> de : data.entrySet()) { + + Map<String, ?> data = ParserUtils.parse(extensions); + for (Map.Entry<String, ?> de : data.entrySet()) { String extName = de.getKey(); Object extValue = de.getValue(); System.out.append('\t').append(extName).append(": ").println(extValue); @@ -627,7 +627,8 @@ public class SftpTest extends AbstractSftpClientTestSupport { } } - private static Set<String> EXPECTED_EXTENSIONS = SftpSubsystem.DEFAULT_SUPPORTED_CLIENT_EXTENSIONS; + private static Set<String> EXPECTED_EXTENSIONS = SftpSubsystem.DEFAULT_SUPPORTED_CLIENT_EXTENSIONS; + private static void assertSupportedExtensions(String extName, Collection<String> extensionNames) { assertEquals(extName + "[count]", EXPECTED_EXTENSIONS.size(), GenericUtils.size(extensionNames)); @@ -640,37 +641,37 @@ public class SftpTest extends AbstractSftpClientTestSupport { public void testSftpVersionSelector() throws Exception { final AtomicInteger selected = new AtomicInteger(-1); SftpVersionSelector selector = new SftpVersionSelector() { - @Override - public int selectVersion(int current, List<Integer> available) { - int numAvailable = GenericUtils.size(available); - Integer maxValue = null; - if (numAvailable == 1) { - maxValue = available.get(0); - } else { - for (Integer v : available) { - if (v.intValue() == current) { - continue; - } - - if ((maxValue == null) || (maxValue.intValue() < v.intValue())) { - maxValue = v; - } + @Override + public int selectVersion(int current, List<Integer> available) { + int numAvailable = GenericUtils.size(available); + Integer maxValue = null; + if (numAvailable == 1) { + maxValue = available.get(0); + } else { + for (Integer v : available) { + if (v.intValue() == current) { + continue; } - } - selected.set(maxValue.intValue()); - return selected.get(); + if ((maxValue == null) || (maxValue.intValue() < v.intValue())) { + maxValue = v; + } + } } - }; - try(SshClient client = SshClient.setUpDefaultClient()) { + selected.set(maxValue.intValue()); + return selected.get(); + } + }; + + try (SshClient client = SshClient.setUpDefaultClient()) { client.start(); - + try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).verify(7L, TimeUnit.SECONDS).getSession()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - try(SftpClient sftp = session.createSftpClient(selector)) { + try (SftpClient sftp = session.createSftpClient(selector)) { assertEquals("Mismatched negotiated version", selected.get(), sftp.getVersion()); testClient(client, sftp); } @@ -691,20 +692,20 @@ public class SftpTest extends AbstractSftpClientTestSupport { String file = dir + "/" + "file.txt"; sftp.mkdir(dir); - - try(SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create))) { + + try (SftpClient.CloseableHandle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create))) { byte[] d = "0123456789\n".getBytes(StandardCharsets.UTF_8); sftp.write(h, 0, d, 0, d.length); sftp.write(h, d.length, d, 0, d.length); - + SftpClient.Attributes attrs = sftp.stat(h); assertNotNull("No handle attributes", attrs); - } + } - try(SftpClient.CloseableHandle h = sftp.openDir(dir)) { + try (SftpClient.CloseableHandle h = sftp.openDir(dir)) { List<SftpClient.DirEntry> dirEntries = sftp.readDir(h); assertNotNull("No dir entries", dirEntries); - + boolean dotFiltered = false, dotdotFiltered = false; for (Iterator<SftpClient.DirEntry> it = dirEntries.iterator(); it.hasNext(); ) { SftpClient.DirEntry entry = it.next(); @@ -794,12 +795,12 @@ public class SftpTest extends AbstractSftpClientTestSupport { c.connect(); try { c.put(new ByteArrayInputStream(data.getBytes(StandardCharsets.UTF_8)), remSrcPath); - + assertTrue("Source file not created: " + sourcePath, Files.exists(sourcePath)); assertEquals("Mismatched stored data in " + remSrcPath, data, readFile(remSrcPath)); - + c.symlink(remSrcPath, remLinkPath); - + assertTrue("Symlink not created: " + linkPath, Files.exists(linkPath)); assertEquals("Mismatched link data in " + remLinkPath, data, readFile(remLinkPath)); @@ -814,9 +815,9 @@ public class SftpTest extends AbstractSftpClientTestSupport { protected String readFile(String path) throws Exception { ChannelSftp c = (ChannelSftp) session.openChannel(SftpConstants.SFTP_SUBSYSTEM_NAME); c.connect(); - - try(ByteArrayOutputStream bos = new ByteArrayOutputStream(); - InputStream is = c.get(path)) { + + try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); + InputStream is = c.get(path)) { byte[] buffer = new byte[256]; int count; http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/BuiltinSftpClientExtensionsTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/BuiltinSftpClientExtensionsTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/BuiltinSftpClientExtensionsTest.java index 11be24f..9a57a74 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/BuiltinSftpClientExtensionsTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/BuiltinSftpClientExtensionsTest.java @@ -38,7 +38,7 @@ public class BuiltinSftpClientExtensionsTest extends BaseTestSupport { @Test public void testFromName() { - for (String name : new String[] { null, "", getCurrentTestName() }) { + for (String name : new String[]{null, "", getCurrentTestName()}) { assertNull("Unexpected result for name='" + name + "'", BuiltinSftpClientExtensions.fromName(name)); } @@ -54,7 +54,7 @@ public class BuiltinSftpClientExtensionsTest extends BaseTestSupport { @Test public void testFromType() { - for (Class<?> clazz : new Class<?>[] { null, getClass(), SftpClientExtension.class }) { + for (Class<?> clazz : new Class<?>[]{null, getClass(), SftpClientExtension.class}) { assertNull("Unexpected value for class=" + clazz, BuiltinSftpClientExtensions.fromType(clazz)); } @@ -67,7 +67,7 @@ public class BuiltinSftpClientExtensionsTest extends BaseTestSupport { @Test public void testFromInstance() { - for (Object instance : new Object[] { null, this }) { + for (Object instance : new Object[]{null, this}) { assertNull("Unexpected value for " + instance, BuiltinSftpClientExtensions.fromInstance(instance)); } @@ -79,6 +79,6 @@ public class BuiltinSftpClientExtensionsTest extends BaseTestSupport { BuiltinSftpClientExtensions actual = BuiltinSftpClientExtensions.fromInstance(e); assertSame(expected.getName(), expected, actual); assertEquals("Mismatched extension name", expected.getName(), actual.getName()); - } + } } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractCheckFileExtensionTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractCheckFileExtensionTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractCheckFileExtensionTest.java index c341ffb..9b98ebf 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractCheckFileExtensionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractCheckFileExtensionTest.java @@ -71,7 +71,7 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor Integer.valueOf(Byte.MAX_VALUE), Integer.valueOf(SftpConstants.MIN_CHKFILE_BLOCKSIZE), Integer.valueOf(IoUtils.DEFAULT_COPY_SIZE), - Integer.valueOf(Byte.SIZE *IoUtils.DEFAULT_COPY_SIZE) + Integer.valueOf(Byte.SIZE * IoUtils.DEFAULT_COPY_SIZE) )); private static final Collection<Integer> BLOCK_SIZES = Collections.unmodifiableList( @@ -80,18 +80,18 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor Integer.valueOf(SftpConstants.MIN_CHKFILE_BLOCKSIZE), Integer.valueOf(1024), Integer.valueOf(IoUtils.DEFAULT_COPY_SIZE) - )); + )); @SuppressWarnings("synthetic-access") private static final Collection<Object[]> PARAMETERS = Collections.unmodifiableCollection(new LinkedList<Object[]>() { private static final long serialVersionUID = 1L; // we're not serializing it - + { for (NamedFactory<?> factory : BuiltinDigests.VALUES) { String algorithm = factory.getName(); for (Number dataSize : DATA_SIZES) { for (Number blockSize : BLOCK_SIZES) { - add(new Object[] { algorithm, dataSize, blockSize }); + add(new Object[]{algorithm, dataSize, blockSize}); } } } @@ -136,16 +136,15 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor } byte[] seed = (getClass().getName() + "#" + getCurrentTestName() - + "-" + expectedAlgorithm - + "-" + inputDataSize + "/" + hashBlockSize - + System.getProperty("line.separator")) - .getBytes(StandardCharsets.UTF_8) - ; + + "-" + expectedAlgorithm + + "-" + inputDataSize + "/" + hashBlockSize + + System.getProperty("line.separator")) + .getBytes(StandardCharsets.UTF_8); - try(ByteArrayOutputStream baos=new ByteArrayOutputStream(inputDataSize + seed.length)) { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(inputDataSize + seed.length)) { while (baos.size() < inputDataSize) { baos.write(seed); - + if (digest != null) { digest.update(seed); } @@ -168,7 +167,7 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor if (f == factory) { continue; } - + algorithms.add(f.getName()); } @@ -176,34 +175,34 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor String srcPath = Utils.resolveRelativeRemotePath(parentPath, srcFile); String srcFolder = Utils.resolveRelativeRemotePath(parentPath, srcFile.getParent()); - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(SftpClient sftp = session.createSftpClient()) { + + try (SftpClient sftp = session.createSftpClient()) { CheckFileNameExtension file = assertExtensionCreated(sftp, CheckFileNameExtension.class); try { - Pair<String,?> result = file.checkFileName(srcFolder, algorithms, 0L, 0L, hashBlockSize); + Pair<String, ?> result = file.checkFileName(srcFolder, algorithms, 0L, 0L, hashBlockSize); fail("Unexpected success to hash folder=" + srcFolder + ": " + result.getFirst()); - } catch(IOException e) { // expected - not allowed to hash a folder + } catch (IOException e) { // expected - not allowed to hash a folder assertTrue("Not an SftpException", e instanceof SftpException); } CheckFileHandleExtension hndl = assertExtensionCreated(sftp, CheckFileHandleExtension.class); - try(CloseableHandle dirHandle = sftp.openDir(srcFolder)) { + try (CloseableHandle dirHandle = sftp.openDir(srcFolder)) { try { - Pair<String,?> result = hndl.checkFileHandle(dirHandle, algorithms, 0L, 0L, hashBlockSize); + Pair<String, ?> result = hndl.checkFileHandle(dirHandle, algorithms, 0L, 0L, hashBlockSize); fail("Unexpected handle success on folder=" + srcFolder + ": " + result.getFirst()); - } catch(IOException e) { // expected - not allowed to hash a folder + } catch (IOException e) { // expected - not allowed to hash a folder assertTrue("Not an SftpException", e instanceof SftpException); } } - + validateHashResult(file, file.checkFileName(srcPath, algorithms, 0L, 0L, hashBlockSize), algorithms.get(0), expectedHash); - try(CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { + try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { validateHashResult(hndl, hndl.checkFileHandle(fileHandle, algorithms, 0L, 0L, hashBlockSize), algorithms.get(0), expectedHash); } } @@ -212,21 +211,21 @@ public class AbstractCheckFileExtensionTest extends AbstractSftpClientTestSuppor } } } - - private void validateHashResult(NamedResource hasher, Pair<String,Collection<byte[]>> result, String expectedAlgorithm, byte[] expectedHash) { + + private void validateHashResult(NamedResource hasher, Pair<String, Collection<byte[]>> result, String expectedAlgorithm, byte[] expectedHash) { String name = hasher.getName(); assertNotNull("No result for hash=" + name, result); assertEquals("Mismatched hash algorithms for " + name, expectedAlgorithm, result.getFirst()); - + if (GenericUtils.length(expectedHash) > 0) { Collection<byte[]> values = result.getSecond(); assertEquals("Mismatched hash values count for " + name, 1, GenericUtils.size(values)); - + byte[] actualHash = values.iterator().next(); if (!Arrays.equals(expectedHash, actualHash)) { fail("Mismatched hashes for " + name - + ": expected=" + BufferUtils.printHex(':', expectedHash) - + ", actual=" + BufferUtils.printHex(':', expectedHash)); + + ": expected=" + BufferUtils.printHex(':', expectedHash) + + ", actual=" + BufferUtils.printHex(':', expectedHash)); } } } http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/17f2d627/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractMD5HashExtensionTest.java ---------------------------------------------------------------------- diff --git a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractMD5HashExtensionTest.java b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractMD5HashExtensionTest.java index 878771a..2d0bd47 100644 --- a/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractMD5HashExtensionTest.java +++ b/sshd-core/src/test/java/org/apache/sshd/client/subsystem/sftp/extensions/impl/AbstractMD5HashExtensionTest.java @@ -63,11 +63,11 @@ public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport private static final List<Integer> DATA_SIZES = Collections.unmodifiableList( Arrays.asList( - Integer.valueOf(Byte.MAX_VALUE), - Integer.valueOf(SftpConstants.MD5_QUICK_HASH_SIZE), - Integer.valueOf(IoUtils.DEFAULT_COPY_SIZE), - Integer.valueOf(Byte.SIZE * IoUtils.DEFAULT_COPY_SIZE) - )); + Integer.valueOf(Byte.MAX_VALUE), + Integer.valueOf(SftpConstants.MD5_QUICK_HASH_SIZE), + Integer.valueOf(IoUtils.DEFAULT_COPY_SIZE), + Integer.valueOf(Byte.SIZE * IoUtils.DEFAULT_COPY_SIZE) + )); @Parameters(name = "dataSize={0}") public static Collection<Object[]> parameters() { @@ -97,7 +97,7 @@ public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport private void testMD5HashExtension(int dataSize) throws Exception { byte[] seed = (getClass().getName() + "#" + getCurrentTestName() + "-" + dataSize + System.getProperty("line.separator")).getBytes(StandardCharsets.UTF_8); - try(ByteArrayOutputStream baos=new ByteArrayOutputStream(dataSize + seed.length)) { + try (ByteArrayOutputStream baos = new ByteArrayOutputStream(dataSize + seed.length)) { while (baos.size() < dataSize) { baos.write(seed); } @@ -131,42 +131,42 @@ public class AbstractMD5HashExtensionTest extends AbstractSftpClientTestSupport String srcPath = Utils.resolveRelativeRemotePath(parentPath, srcFile); String srcFolder = Utils.resolveRelativeRemotePath(parentPath, srcFile.getParent()); - 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()) { session.addPasswordIdentity(getCurrentTestName()); session.auth().verify(5L, TimeUnit.SECONDS); - - try(SftpClient sftp = session.createSftpClient()) { + + try (SftpClient sftp = session.createSftpClient()) { MD5FileExtension file = assertExtensionCreated(sftp, MD5FileExtension.class); try { byte[] actual = file.getHash(srcFolder, 0L, 0L, quickHash); fail("Unexpected file success on folder=" + srcFolder + ": " + BufferUtils.printHex(':', actual)); - } catch(IOException e) { // expected - not allowed to hash a folder + } catch (IOException e) { // expected - not allowed to hash a folder assertTrue("Not an SftpException for file hash on " + srcFolder, e instanceof SftpException); } MD5HandleExtension hndl = assertExtensionCreated(sftp, MD5HandleExtension.class); - try(CloseableHandle dirHandle = sftp.openDir(srcFolder)) { + try (CloseableHandle dirHandle = sftp.openDir(srcFolder)) { try { byte[] actual = hndl.getHash(dirHandle, 0L, 0L, quickHash); fail("Unexpected handle success on folder=" + srcFolder + ": " + BufferUtils.printHex(':', actual)); - } catch(IOException e) { // expected - not allowed to hash a folder + } catch (IOException e) { // expected - not allowed to hash a folder assertTrue("Not an SftpException for handle hash on " + srcFolder, e instanceof SftpException); } } - try(CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { - for (byte[] qh : new byte[][] { GenericUtils.EMPTY_BYTE_ARRAY, quickHash }) { - for (boolean useFile : new boolean[] { true, false }) { + try (CloseableHandle fileHandle = sftp.open(srcPath, SftpClient.OpenMode.Read)) { + for (byte[] qh : new byte[][]{GenericUtils.EMPTY_BYTE_ARRAY, quickHash}) { + for (boolean useFile : new boolean[]{true, false}) { byte[] actualHash = useFile ? file.getHash(srcPath, 0L, 0L, qh) : hndl.getHash(fileHandle, 0L, 0L, qh); String type = useFile ? file.getClass().getSimpleName() : hndl.getClass().getSimpleName(); if (!Arrays.equals(expectedHash, actualHash)) { fail("Mismatched hash for quick=" + BufferUtils.printHex(':', qh) - + " using " + type + " on " + srcFile - + ": expected=" + BufferUtils.printHex(':', expectedHash) - + ", actual=" + BufferUtils.printHex(':', actualHash)); + + " using " + type + " on " + srcFile + + ": expected=" + BufferUtils.printHex(':', expectedHash) + + ", actual=" + BufferUtils.printHex(':', actualHash)); } } }
