You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@mina.apache.org by lg...@apache.org on 2015/05/25 15:06:23 UTC
[1/3] mina-sshd git commit: [SSHD-471] Auto-detect 'target' folder
location and use it in the tests
Repository: mina-sshd
Updated Branches:
refs/heads/master 7b3d9cf8b -> b6166cc8d
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpTest.java
new file mode 100644
index 0000000..9e9207e
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpTest.java
@@ -0,0 +1,680 @@
+/*
+ * 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.client.sftp;
+
+import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_FILE_ALREADY_EXISTS;
+import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_NO_SUCH_FILE;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IRUSR;
+import static org.apache.sshd.common.sftp.SftpConstants.S_IWUSR;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+import java.nio.file.FileSystem;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.EnumSet;
+import java.util.Random;
+import java.util.Vector;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.sshd.ClientSession;
+import org.apache.sshd.SshClient;
+import org.apache.sshd.SshServer;
+import org.apache.sshd.client.SftpClient;
+import org.apache.sshd.common.NamedFactory;
+import org.apache.sshd.common.Session;
+import org.apache.sshd.common.file.FileSystemFactory;
+import org.apache.sshd.common.file.root.RootedFileSystemProvider;
+import org.apache.sshd.common.util.OsUtils;
+import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
+import org.apache.sshd.server.Command;
+import org.apache.sshd.server.command.ScpCommandFactory;
+import org.apache.sshd.server.sftp.SftpSubsystemFactory;
+import org.apache.sshd.util.BaseTestSupport;
+import org.apache.sshd.util.BogusPasswordAuthenticator;
+import org.apache.sshd.util.EchoShellFactory;
+import org.apache.sshd.util.JSchLogger;
+import org.apache.sshd.util.SimpleUserInfo;
+import org.apache.sshd.util.Utils;
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.SftpException;
+
+public class SftpTest extends BaseTestSupport {
+
+ private SshServer sshd;
+ private int port;
+ private com.jcraft.jsch.Session session;
+ private final FileSystemFactory fileSystemFactory;
+
+ public SftpTest() throws IOException {
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String,Object>emptyMap());
+ fileSystemFactory = new FileSystemFactory() {
+ @Override
+ public FileSystem createFileSystem(Session session) throws IOException {
+ return fileSystem;
+ }
+ };
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ sshd = SshServer.setUpDefaultServer();
+ sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
+ sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
+ sshd.setCommandFactory(new ScpCommandFactory());
+ sshd.setShellFactory(new EchoShellFactory());
+ sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+ sshd.setFileSystemFactory(fileSystemFactory);
+ sshd.start();
+ port = sshd.getPort();
+
+ JSchLogger.init();
+ JSch sch = new JSch();
+ session = sch.getSession("sshd", "localhost", port);
+ session.setUserInfo(new SimpleUserInfo("sshd"));
+ session.connect();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (session != null) {
+ session.disconnect();
+ }
+
+ if (sshd != null) {
+ sshd.stop(true);
+ }
+ }
+
+ @Test
+ @Ignore
+ public void testExternal() throws Exception {
+ System.out.println("SFTP subsystem available on port " + port);
+ Thread.sleep(5 * 60000);
+ }
+
+ @Test
+ public void testOpen() throws Exception {
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Path clientFolder = lclSftp.resolve("client");
+ Path testFile = clientFolder.resolve(getCurrentTestName() + ".txt");
+ String file = Utils.resolveRelativeRemotePath(parentPath, testFile);
+
+ File javaFile = testFile.toFile();
+ assertHierarchyTargetFolderExists(javaFile.getParentFile());
+ javaFile.createNewFile();
+ javaFile.setWritable(false, false);
+ javaFile.setReadable(false, false);
+
+ try (SftpClient sftp = session.createSftpClient()) {
+ SftpClient.Handle h;
+
+ boolean isWindows = OsUtils.isWin32();
+
+ try {
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.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);
+ sftp.close(h);
+ } catch (IOException e) {
+ if (isWindows) {
+ throw e;
+ }
+ }
+
+ try {
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
+ fail("Empty write should have failed on " + file);
+ } catch (IOException e) {
+ // ok
+ }
+
+ try {
+ 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);
+ sftp.close(h);
+ } 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);
+ assertEquals("Mismatched permissions for " + file + ": 0x" + Integer.toHexString(perms), 0, (perms & permsMask));
+
+ javaFile.setWritable(true, false);
+
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate, SftpClient.OpenMode.Write));
+ sftp.close(h);
+
+ byte[] d = "0123456789\n".getBytes();
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
+ try {
+ sftp.write(h, 0, d, 0, d.length);
+ sftp.write(h, d.length, d, 0, d.length);
+ } finally {
+ sftp.close(h);
+ }
+
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
+ try {
+ sftp.write(h, d.length * 2, d, 0, d.length);
+ } finally {
+ sftp.close(h);
+ }
+
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
+ try {
+ sftp.write(h, 3, "-".getBytes(), 0, 1);
+ } finally {
+ sftp.close(h);
+ }
+
+ try {
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Read));
+ try {
+ // NOTE: on Windows files are always readable
+ assertTrue("Data read should have failed on " + file, isWindows);
+ } finally {
+ sftp.close(h);
+ }
+ } catch (IOException e) {
+ if (isWindows) {
+ throw e;
+ }
+ }
+
+ javaFile.setReadable(true, false);
+
+ byte[] buf = new byte[3];
+ h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Read));
+ try {
+ int l = sftp.read(h, 2l, buf, 0, 3);
+ assertEquals("Mismatched read data", "2-4", new String(buf, 0, l));
+ } finally {
+ sftp.close(h);
+ }
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testClient() throws Exception {
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+ Files.createDirectories(lclSftp);
+
+ Path parentPath = targetPath.getParent();
+ Path clientFolder = lclSftp.resolve("client");
+ String dir = Utils.resolveRelativeRemotePath(parentPath, clientFolder);
+ String file = dir + "/" + getCurrentTestName() + ".txt";
+
+ try (SftpClient sftp = session.createSftpClient()) {
+ sftp.mkdir(dir);
+
+ SftpClient.Handle h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
+ byte[] d = "0123456789\n".getBytes();
+ sftp.write(h, 0, d, 0, d.length);
+ sftp.write(h, d.length, d, 0, d.length);
+
+ SftpClient.Attributes attrs = sftp.stat(h);
+ assertNotNull("No handle attributes", attrs);
+
+ sftp.close(h);
+
+ h = sftp.openDir(dir);
+ try {
+ SftpClient.DirEntry[] dirEntries = sftp.readDir(h);
+ assertNotNull("No dir entries", dirEntries);
+ assertEquals("Mismatced number of dir entries", 1, dirEntries.length);
+ assertNull("Unexpected entry read", sftp.readDir(h));
+ } finally {
+ sftp.close(h);
+ }
+
+ sftp.remove(file);
+
+ byte[] workBuf = new byte[1024 * 128];
+ new Random(System.currentTimeMillis()).nextBytes(workBuf);
+ try (OutputStream os = sftp.write(file)) {
+ os.write(workBuf);
+ }
+
+ try (InputStream is = sftp.read(file)) {
+ int readLen = is.read(workBuf);
+ assertEquals("Mismatched read data length", workBuf.length, readLen);
+
+ int i = is.read();
+ assertEquals("Unexpected read past EOF", -1, i);
+ }
+
+ SftpClient.Attributes attributes = sftp.stat(file);
+ assertTrue("Test file not detected as regular", attributes.isRegularFile());
+
+ attributes = sftp.stat(dir);
+ assertTrue("Test directory not reported as such", attributes.isDirectory());
+
+ int nb = 0;
+ for (SftpClient.DirEntry entry : sftp.readDir(dir)) {
+ assertNotNull("Unexpected null entry", entry);
+ nb++;
+ }
+ assertEquals("Mismatched read dir entries", 1, nb);
+
+ sftp.remove(file);
+
+ sftp.rmdir(dir);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ /**
+ * 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()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+ Files.createDirectories(lclSftp);
+
+ Path parentPath = targetPath.getParent();
+ Path clientFolder = lclSftp.resolve("client");
+ String dir = Utils.resolveRelativeRemotePath(parentPath, clientFolder);
+
+ 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, (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);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ private void testInvalidParams(SftpClient sftp, Path file, String filePath) throws Exception {
+ // generate random file and upload it
+ String randomData = randomString(5);
+ byte[] randomBytes = randomData.getBytes();
+ SftpClient.Handle handle = sftp.open(filePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
+ try {
+ try {
+ sftp.write(handle, -1, randomBytes, 0, 0);
+ fail("should not have been able to write file with invalid file offset for " + filePath);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ sftp.write(handle, 0, randomBytes, -1, 0);
+ fail("should not have been able to write file with invalid source offset for " + filePath);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ sftp.write(handle, 0, randomBytes, 0, -1);
+ fail("should not have been able to write file with invalid length for " + filePath);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ sftp.write(handle, 0, randomBytes, 0, randomBytes.length + 1);
+ fail("should not have been able to write file with length bigger than array itself (no offset) for " + filePath);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ try {
+ sftp.write(handle, 0, randomBytes, randomBytes.length, 1);
+ fail("should not have been able to write file with length bigger than array itself (with offset) for " + filePath);
+ } catch (IllegalArgumentException e) {
+ // expected
+ }
+ } finally {
+ // cleanup
+ sftp.close(handle);
+ }
+
+ sftp.remove(filePath);
+ assertFalse("File should not be there: " + file.toString(), Files.exists(file));
+ }
+
+ private void uploadAndVerifyFile(SftpClient sftp, Path clientFolder, String remoteDir, int size, String filename) throws Exception {
+ // generate random file and upload it
+ String remotePath = remoteDir + "/" + filename;
+ String randomData = randomString(size);
+ SftpClient.Handle handle = sftp.open(remotePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
+ try {
+ sftp.write(handle, 0, randomData.getBytes(), 0, randomData.length());
+ } finally {
+ sftp.close(handle);
+ }
+
+ // verify results
+ Path resultPath = clientFolder.resolve(filename);
+ assertTrue("File should exist on disk: " + resultPath, Files.exists(resultPath));
+ assertTrue("Mismatched file contents: " + resultPath, randomData.equals(readFile(remotePath)));
+
+ // cleanup
+ sftp.remove(remotePath);
+ assertFalse("File should have been removed: " + resultPath, Files.exists(resultPath));
+ }
+
+ @Test
+ public void testSftp() throws Exception {
+ String d = getCurrentTestName() + "\n";
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+ Files.createDirectories(lclSftp);
+
+ Path target = lclSftp.resolve(getCurrentTestName() + ".txt");
+ String remotePath = Utils.resolveRelativeRemotePath(targetPath.getParent(), target);
+
+ 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);
+ }
+
+ for (int i = 0; i < j; i++) {
+ sb.append(d);
+ }
+
+ sendFile(remotePath, sb.toString());
+ assertFileLength(target, sb.length(), 5000);
+ Files.delete(target);
+ }
+ }
+
+ @Test
+ public void testReadWriteWithOffset() throws Exception {
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+ Files.createDirectories(lclSftp);
+
+ Path localPath = lclSftp.resolve(getCurrentTestName() + ".txt");
+ String remotePath = Utils.resolveRelativeRemotePath(targetPath.getParent(), localPath);
+ String data = getCurrentTestName();
+ String extraData = "@" + getClass().getSimpleName();
+ int appendOffset = -5;
+
+ ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
+ c.connect();
+ try {
+ c.put(new ByteArrayInputStream(data.getBytes()), 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)) {
+ os.write(extraData.getBytes());
+ }
+ } finally {
+ c.disconnect();
+ }
+
+ 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);
+ }
+
+ @Test
+ public void testReadDir() throws Exception {
+ ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
+ c.connect();
+ try {
+ URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
+ URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
+ String path = new File(base.relativize(url).getPath()).getParent() + "/";
+ path = path.replace('\\', '/');
+ Vector<?> res = c.ls(path);
+ for (Object f : res) {
+ System.out.println(f.toString());
+ }
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ @Test
+ public void testRealPath() throws Exception {
+ ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
+ c.connect();
+
+ try {
+ URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
+ URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
+ String path = new File(base.relativize(url).getPath()).getParent() + "/";
+ path = path.replace('\\', '/');
+ String real = c.realpath(path);
+ System.out.println(real);
+ try {
+ real = c.realpath(path + "/foobar");
+ System.out.println(real);
+ fail("Expected SftpException");
+ } catch (SftpException e) {
+ // ok
+ }
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ @Test
+ public void testRename() throws Exception {
+ try(SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+ Files.createDirectories(lclSftp);
+
+ Path parentPath = targetPath.getParent();
+ Path clientFolder = assertHierarchyTargetFolderExists(lclSftp.resolve("client"));
+
+ try(SftpClient sftp = session.createSftpClient()) {
+ Path file1 = clientFolder.resolve(getCurrentTestName() + "-1.txt");
+ String file1Path = Utils.resolveRelativeRemotePath(parentPath, file1);
+ try (OutputStream os = sftp.write(file1Path)) {
+ os.write((getCurrentTestName() + "\n").getBytes());
+ }
+
+ Path file2 = clientFolder.resolve(getCurrentTestName() + "-2.txt");
+ String file2Path = Utils.resolveRelativeRemotePath(parentPath, file2);
+ Path file3 = clientFolder.resolve(getCurrentTestName() + "-3.txt");
+ String file3Path = Utils.resolveRelativeRemotePath(parentPath, file3);
+ try {
+ sftp.rename(file2Path, file3Path);
+ fail("Unxpected rename success of " + file2Path + " => " + file3Path);
+ } catch (org.apache.sshd.client.SftpException e) {
+ assertEquals("Mismatched status for failed rename of " + file2Path + " => " + file3Path, SSH_FX_NO_SUCH_FILE, e.getStatus());
+ }
+
+ try (OutputStream os = sftp.write(file2Path)) {
+ os.write("H".getBytes());
+ }
+
+ try {
+ sftp.rename(file1Path, file2Path);
+ fail("Unxpected rename success of " + file1Path + " => " + file2Path);
+ } catch (org.apache.sshd.client.SftpException e) {
+ assertEquals("Mismatched status for failed rename of " + file1Path + " => " + file2Path, SSH_FX_FILE_ALREADY_EXISTS, e.getStatus());
+ }
+
+ sftp.rename(file1Path, file2Path, SftpClient.CopyMode.Overwrite);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testCreateSymbolicLink() throws Exception {
+ // Do not execute on windows as the file system does not support symlinks
+ Assume.assumeTrue("Skip non-Unix O/S", OsUtils.isUNIX());
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+ Files.createDirectories(lclSftp);
+
+ Path parentPath = targetPath.getParent();
+ Path sourcePath = lclSftp.resolve(getCurrentTestName() + ".txt");
+ String remSrcPath = Utils.resolveRelativeRemotePath(parentPath, sourcePath);
+ Path linkPath = lclSftp.resolve("link-" + sourcePath.getFileName());
+ String remLinkPath = Utils.resolveRelativeRemotePath(parentPath, linkPath);
+
+ String data = getCurrentTestName();
+ ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
+ c.connect();
+ try {
+ c.put(new ByteArrayInputStream(data.getBytes()), 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("Mismatche link data in " + remLinkPath, data, readFile(remLinkPath));
+
+ String str1 = c.readlink(remLinkPath);
+ String str2 = c.realpath(remSrcPath);
+ assertEquals("Mismatched link vs. real path", str1, str2);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected String readFile(String path) throws Exception {
+ ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
+ c.connect();
+
+ try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ InputStream is = c.get(path)) {
+
+ byte[] buffer = new byte[256];
+ int count;
+ while (-1 != (count = is.read(buffer))) {
+ bos.write(buffer, 0, count);
+ }
+
+ return bos.toString();
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected void sendFile(String path, String data) throws Exception {
+ ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
+ c.connect();
+ try {
+ c.put(new ByteArrayInputStream(data.getBytes()), path);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ private String randomString(int size) {
+ StringBuilder sb = new StringBuilder(size);
+ for (int i = 0; i < size; i++) {
+ sb.append((char) ((i % 10) + '0'));
+ }
+ return sb.toString();
+ }
+}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java b/sshd-core/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
index 5ca20dd..2ca4c57 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/cipher/BaseCipherTest.java
@@ -31,7 +31,6 @@ import org.apache.sshd.common.NamedFactory;
import org.apache.sshd.common.util.SecurityUtils;
import org.apache.sshd.util.BaseTestSupport;
import org.junit.Assume;
-import org.junit.internal.AssumptionViolatedException;
/**
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
@@ -41,7 +40,6 @@ public abstract class BaseCipherTest extends BaseTestSupport {
super();
}
- @SuppressWarnings("deprecation")
protected void ensureKeySizeSupported(int bsize, String algorithm, String transformation) throws GeneralSecurityException {
try {
javax.crypto.Cipher cipher=SecurityUtils.getCipher(transformation);
@@ -49,7 +47,7 @@ public abstract class BaseCipherTest extends BaseTestSupport {
cipher.init(javax.crypto.Cipher.ENCRYPT_MODE, new SecretKeySpec(key, algorithm));
} catch(GeneralSecurityException e) {
if (e instanceof InvalidKeyException) { // NOTE: assumption violations are NOT test failures...
- throw new AssumptionViolatedException(algorithm + "/" + transformation + "[" + bsize + "] N/A");
+ Assume.assumeTrue(algorithm + "/" + transformation + "[" + bsize + "] N/A", false);
}
throw e;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java b/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
index 94f0a5c..262b91e 100644
--- a/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/common/file/util/BasePathTest.java
@@ -359,7 +359,7 @@ public class BasePathTest extends BaseTestSupport {
@Override
protected TestPath create(String root, ImmutableList<String> names) {
- return new TestPath(fileSystem, root, names);
+ return new TestPath(getFileSystem(), root, names);
}
@Override
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java
index 6f7594c..0c4fec8 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/PEMGeneratorHostKeyProviderTest.java
@@ -68,7 +68,7 @@ public class PEMGeneratorHostKeyProviderTest extends BaseTestSupport {
testPEMGeneratorHostKeyProvider("EC", KeyPairProvider.ECDSA_SHA2_NISTP521, -1, new ECGenParameterSpec("P-521"));
}
- private static File testPEMGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) {
+ private File testPEMGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) {
File path = initKeyFileLocation(algorithm);
KeyPair kpWrite = invokePEMGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec);
assertTrue("Key file not generated: " + path.getAbsolutePath(), path.exists());
@@ -114,8 +114,8 @@ public class PEMGeneratorHostKeyProviderTest extends BaseTestSupport {
return kp;
}
- private static File initKeyFileLocation(String algorithm) {
- File path = new File("target/keys");
+ private File initKeyFileLocation(String algorithm) {
+ File path = new File(detectTargetFolder(), "keys");
if (!path.exists()) {
assertTrue("Failed to crearte hierarchy of " + path.getAbsolutePath(), path.mkdirs());
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java
index 578ee10..9d5117a 100644
--- a/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java
+++ b/sshd-core/src/test/java/org/apache/sshd/server/keyprovider/SimpleGeneratorHostKeyProviderTest.java
@@ -64,7 +64,7 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport {
testSimpleGeneratorHostKeyProvider("EC", KeyPairProvider.ECDSA_SHA2_NISTP521, -1, new ECGenParameterSpec("P-521"));
}
- private static File testSimpleGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) {
+ private File testSimpleGeneratorHostKeyProvider(String algorithm, String keyType, int keySize, AlgorithmParameterSpec keySpec) {
File path = initKeyFileLocation(algorithm);
KeyPair kpWrite = invokeSimpleGeneratorHostKeyProvider(path, algorithm, keyType, keySize, keySpec);
assertTrue("Key file not generated: " + path.getAbsolutePath(), path.exists());
@@ -104,8 +104,8 @@ public class SimpleGeneratorHostKeyProviderTest extends BaseTestSupport {
return kp;
}
- private static File initKeyFileLocation(String algorithm) {
- File path = new File("target/keys");
+ private File initKeyFileLocation(String algorithm) {
+ File path = new File(detectTargetFolder(), "keys");
if (!path.exists()) {
assertTrue("Failed to crearte hierarchy of " + path.getAbsolutePath(), path.mkdirs());
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/util/BaseTestSupport.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/util/BaseTestSupport.java b/sshd-core/src/test/java/org/apache/sshd/util/BaseTestSupport.java
index b873313..eff59e5 100644
--- a/sshd-core/src/test/java/org/apache/sshd/util/BaseTestSupport.java
+++ b/sshd-core/src/test/java/org/apache/sshd/util/BaseTestSupport.java
@@ -19,6 +19,10 @@
package org.apache.sshd.util;
import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.Path;
import java.security.Key;
import java.security.KeyPair;
import java.security.interfaces.DSAParams;
@@ -49,6 +53,7 @@ import org.junit.runner.Description;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public abstract class BaseTestSupport extends Assert {
+ public static final String TEMP_SUBFOLDER_NAME="temp";
@Rule public final TestWatcher rule = new TestWatcher() {
// TODO consider using a ThreadLocal storage for the start time - provided
// the code is assured to call starting/finished on the same thread
@@ -67,6 +72,7 @@ public abstract class BaseTestSupport extends Assert {
}
};
@Rule public final TestName TEST_NAME_HOLDER = new TestName();
+ private File targetFolder;
protected BaseTestSupport() {
super();
@@ -76,6 +82,25 @@ public abstract class BaseTestSupport extends Assert {
return TEST_NAME_HOLDER.getMethodName();
}
+ /**
+ * Attempts to detect the location of the Maven "target" folder
+ * associated with the project that contains the actual class extending this
+ * base class
+ * @return The {@link File} representing the location of the "target" folder
+ * @throws IllegalStateException If failed to detect the folder
+ */
+ protected File detectTargetFolder() throws IllegalStateException {
+ synchronized(TEMP_SUBFOLDER_NAME) {
+ if (targetFolder == null) {
+ if ((targetFolder=Utils.detectTargetFolder(getClass())) == null) {
+ throw new IllegalStateException("Failed to detect target folder");
+ }
+ }
+ }
+
+ return targetFolder;
+ }
+
/* ------------------- Useful extra test helpers ---------------------- */
public static String shuffleCase(CharSequence cs) {
@@ -126,6 +151,14 @@ public abstract class BaseTestSupport extends Assert {
assertFalse(message + "[non-empty-actual]", actual.hasNext());
}
+ public static Path assertHierarchyTargetFolderExists(Path folder, LinkOption ... options) throws IOException {
+ if (!Files.exists(folder, options)) {
+ Files.createDirectories(folder);
+ }
+
+ return folder;
+ }
+
public static File assertHierarchyTargetFolderExists(File folder) {
if (!folder.exists()) {
assertTrue("Failed to create hierarchy of " + folder.getAbsolutePath(), folder.mkdirs());
@@ -288,4 +321,37 @@ public abstract class BaseTestSupport extends Assert {
assertEquals(message + "[x]", expected.getAffineX(), actual.getAffineX());
assertEquals(message + "[y]", expected.getAffineY(), actual.getAffineY());
}
+
+ public static void assertFileLength(File file, long length, long timeout) throws Exception {
+ assertFileLength(file.toPath(), length, timeout);
+ }
+
+ /**
+ * Waits the specified timeout for the file to exist and have the required length
+ * @param file The file {@link Path} to check
+ * @param length Expected length
+ * @param timeout Timeout (msec.) to wait for satisfying the requirements
+ * @throws Exception If failed to access the file
+ */
+ public static void assertFileLength(Path file, long length, long timeout) throws Exception {
+ boolean ok = false;
+ long sleepTime = 100L;
+ while (timeout > 0L) {
+ if (Files.exists(file) && (Files.size(file) == length)) {
+ if (!ok) {
+ ok = true;
+ } else {
+ return;
+ }
+ } else {
+ ok = false;
+ }
+
+ Thread.sleep(sleepTime);
+ timeout -= sleepTime;
+ }
+
+ assertTrue("File not found: " + file, Files.exists(file));
+ assertEquals("Mismatched file size for " + file, length, Files.size(file));
+ }
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/util/Utils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/util/Utils.java b/sshd-core/src/test/java/org/apache/sshd/util/Utils.java
index edd65ee..5f53f3e 100644
--- a/sshd-core/src/test/java/org/apache/sshd/util/Utils.java
+++ b/sshd-core/src/test/java/org/apache/sshd/util/Utils.java
@@ -19,14 +19,27 @@
package org.apache.sshd.util;
import java.io.File;
+import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
import java.net.ServerSocket;
+import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
+import java.nio.file.DirectoryStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.security.CodeSource;
+import java.security.ProtectionDomain;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.List;
import org.apache.sshd.common.keyprovider.FileKeyPairProvider;
import org.apache.sshd.common.keyprovider.KeyPairProvider;
+import org.apache.sshd.common.util.GenericUtils;
import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
public class Utils {
@@ -62,18 +75,396 @@ public class Utils {
return f.toString();
}
- public static void deleteRecursive(File file) {
- if (file != null) {
- if (file.isDirectory()) {
- File[] children = file.listFiles();
- if (children != null) {
- for (File child : children) {
- deleteRecursive(child);
- }
+ public static Path resolve(Path root, String ... children) {
+ if (GenericUtils.isEmpty(children)) {
+ return root;
+ } else {
+ return resolve(root, Arrays.asList(children));
+ }
+ }
+
+ public static Path resolve(Path root, Collection<String> children) {
+ Path path = root;
+ if (!GenericUtils.isEmpty(children)) {
+ for (String child : children) {
+ path = path.resolve(child);
+ }
+ }
+
+ return path;
+ }
+
+ /**
+ * Removes the specified file - if it is a directory, then its children
+ * are deleted recursively and then the directory itself. <B>Note:</B>
+ * no attempt is made to make sure that {@link File#delete()} was successful
+ * @param file The {@link File} to be deleted - ignored if {@code null}
+ * or does not exist anymore
+ * @return The <tt>file</tt> argument
+ */
+ public static File deleteRecursive(File file) {
+ if ((file == null) || (!file.exists())) {
+ return file;
+ }
+
+ if (file.isDirectory()) {
+ File[] children = file.listFiles();
+ if (!GenericUtils.isEmpty(children)) {
+ for (File child : children) {
+ deleteRecursive(child);
}
}
- file.delete();
}
+
+ file.delete();
+ return file;
+ }
+
+ /**
+ * Removes the specified file - if it is a directory, then its children
+ * are deleted recursively and then the directory itself.
+ * @param path The file {@link Path} to be deleted - ignored if {@code null}
+ * or does not exist anymore
+ * @return The <tt>path</tt> argument
+ * @throws IOException If failed to access/remove some file(s)
+ */
+ public static Path deleteRecursive(Path path) throws IOException {
+ if ((path == null) || (!Files.exists(path))) {
+ return path;
+ }
+
+ if (Files.isDirectory(path)) {
+ try(DirectoryStream<Path> ds = Files.newDirectoryStream(path)) {
+ for (Path child : ds) {
+ deleteRecursive(child);
+ }
+ }
+ }
+
+ try {
+ Files.delete(path);
+ } catch(IOException e) {
+ // same logic as deleteRecursive(File) which does not check if deletion succeeded
+ System.err.append("Failed (").append(e.getClass().getSimpleName()).append(")")
+ .append(" to delete ").append(path.toString())
+ .append(": ").println(e.getMessage())
+ ;
+ }
+
+ return path;
+ }
+
+ /**
+ * @param anchor An anchor {@link Class} whose container we want to use
+ * as the starting point for the "target" folder lookup up the
+ * hierarchy
+ * @return The "target" <U>folder</U> - <code>null</code> if not found
+ * @see #detectTargetFolder(File)
+ */
+ public static final File detectTargetFolder(Class<?> anchor) {
+ return detectTargetFolder(getClassContainerLocationFile(anchor));
+ }
+
+ /**
+ * @param clazz A {@link Class} object
+ * @return A {@link File} of the location of the class bytes container
+ * - e.g., the root folder, the containing JAR, etc.. Returns
+ * <code>null</code> if location could not be resolved
+ * @throws IllegalArgumentException If location is not a valid
+ * {@link File} location
+ * @see #getClassContainerLocationURI(Class)
+ * @see #toFileSource(URI)
+ */
+ public static final File getClassContainerLocationFile(Class<?> clazz)
+ throws IllegalArgumentException {
+ try {
+ URI uri=getClassContainerLocationURI(clazz);
+ return toFileSource(uri);
+ } catch(URISyntaxException | MalformedURLException e) {
+ throw new IllegalArgumentException(e.getClass().getSimpleName() + ": " + e.getMessage(), e);
+ }
+ }
+
+ /**
+ * @param clazz A {@link Class} object
+ * @return A {@link URI} to the location of the class bytes container
+ * - e.g., the root folder, the containing JAR, etc.. Returns
+ * <code>null</code> if location could not be resolved
+ * @throws URISyntaxException if location is not a valid URI
+ * @see #getClassContainerLocationURL(Class)
+ */
+ public static final URI getClassContainerLocationURI(Class<?> clazz) throws URISyntaxException {
+ URL url=getClassContainerLocationURL(clazz);
+ return (url == null) ? null : url.toURI();
+ }
+
+ /**
+ * @param clazz A {@link Class} object
+ * @return A {@link URL} to the location of the class bytes container
+ * - e.g., the root folder, the containing JAR, etc.. Returns
+ * <code>null</code> if location could not be resolved
+ */
+ public static final URL getClassContainerLocationURL(Class<?> clazz) {
+ ProtectionDomain pd=clazz.getProtectionDomain();
+ CodeSource cs=(pd == null) ? null : pd.getCodeSource();
+ URL url=(cs == null) ? null : cs.getLocation();
+ if (url == null) {
+ if ((url=getClassBytesURL(clazz)) == null) {
+ return null;
+ }
+
+ String srcForm=getURLSource(url);
+ if (GenericUtils.isEmpty(srcForm)) {
+ return null;
+ }
+
+ try {
+ url = new URL(srcForm);
+ } catch(MalformedURLException e) {
+ throw new IllegalArgumentException("getClassContainerLocationURL(" + clazz.getName() + ")"
+ + " Failed to create URL=" + srcForm + " from " + url.toExternalForm()
+ + ": " + e.getMessage());
+ }
+ }
+
+ return url;
}
+ /**
+ * Converts a {@link URL} that may refer to an internal resource to
+ * a {@link File} representing is "source" container (e.g.,
+ * if it is a resource in a JAR, then the result is the JAR's path)
+ * @param url The {@link URL} - ignored if <code>null</code>
+ * @return The matching {@link File}
+ * @throws MalformedURLException If source URL does not refer to a
+ * file location
+ * @see #toFileSource(URI)
+ */
+ public static File toFileSource(URL url) throws MalformedURLException {
+ if (url == null) {
+ return null;
+ }
+
+ try {
+ return toFileSource(url.toURI());
+ } catch(URISyntaxException e) {
+ throw new MalformedURLException("toFileSource(" + url.toExternalForm() + ")"
+ + " cannot (" + e.getClass().getSimpleName() + ")"
+ + " convert to URI: " + e.getMessage());
+ }
+ }
+
+ /**
+ * URL/URI scheme that refers to a file
+ */
+ public static final String FILE_URL_SCHEME="file";
+ /**
+ * Prefix used in URL(s) that reference a file resource
+ */
+ public static final String FILE_URL_PREFIX=FILE_URL_SCHEME + ":";
+
+ /**
+ * Converts a {@link URI} that may refer to an internal resource to
+ * a {@link File} representing is "source" container (e.g.,
+ * if it is a resource in a JAR, then the result is the JAR's path)
+ * @param uri The {@link URI} - ignored if <code>null</code>
+ * @return The matching {@link File}
+ * @throws MalformedURLException If source URI does not refer to a
+ * file location
+ * @see URLUtils#getURLSource(URI)
+ */
+ public static File toFileSource(URI uri) throws MalformedURLException {
+ String src=getURLSource(uri);
+ if (GenericUtils.isEmpty(src)) {
+ return null;
+ }
+
+ if (!src.startsWith(FILE_URL_PREFIX)) {
+ throw new MalformedURLException("toFileSource(" + src + ") not a '" + FILE_URL_SCHEME + "' scheme");
+ }
+
+ try {
+ return new File(new URI(src));
+ } catch(URISyntaxException e) {
+ throw new MalformedURLException("toFileSource(" + src + ")"
+ + " cannot (" + e.getClass().getSimpleName() + ")"
+ + " convert to URI: " + e.getMessage());
+ }
+ }
+
+ /**
+ * @param uri The {@link URI} value - ignored if <code>null</code>
+ * @return The URI(s) source path where {@link #JAR_URL_PREFIX} and
+ * any sub-resource are stripped
+ * @see #getURLSource(String)
+ */
+ public static final String getURLSource(URI uri) {
+ return getURLSource((uri == null) ? null : uri.toString());
+ }
+
+ /**
+ * @param url The {@link URL} value - ignored if <code>null</code>
+ * @return The URL(s) source path where {@link #JAR_URL_PREFIX} and
+ * any sub-resource are stripped
+ * @see #getURLSource(String)
+ */
+ public static final String getURLSource(URL url) {
+ return getURLSource((url == null) ? null : url.toExternalForm());
+ }
+
+ /**
+ * Separator used in URL(s) that reference a resource inside a JAR
+ * to denote the sub-path inside the JAR
+ */
+ public static final char RESOURCE_SUBPATH_SEPARATOR='!';
+
+ /**
+ * @param externalForm The {@link URL#toExternalForm()} string - ignored if
+ * <code>null</code>/empty
+ * @return The URL(s) source path where {@link #JAR_URL_PREFIX} and
+ * any sub-resource are stripped
+ */
+ public static final String getURLSource(String externalForm) {
+ String url=externalForm;
+ if (GenericUtils.isEmpty(url)) {
+ return url;
+ }
+
+ url = stripJarURLPrefix(externalForm);
+ if (GenericUtils.isEmpty(url)){
+ return url;
+ }
+
+ int sepPos=url.indexOf(RESOURCE_SUBPATH_SEPARATOR);
+ if (sepPos < 0) {
+ return adjustURLPathValue(url);
+ } else {
+ return adjustURLPathValue(url.substring(0, sepPos));
+ }
+ }
+
+ /**
+ * @param url A {@link URL} - ignored if {@code null}
+ * @return The path after stripping any trailing '/' provided the path
+ * is not '/' itself
+ * @see #adjustURLPathValue(String)
+ */
+ public static final String adjustURLPathValue(URL url) {
+ return adjustURLPathValue((url == null) ? null : url.getPath());
+ }
+
+ /**
+ * @param path A URL path value - ignored if {@code null}/empty
+ * @return The path after stripping any trailing '/' provided the path
+ * is not '/' itself
+ */
+ public static final String adjustURLPathValue(final String path) {
+ final int pathLen=(path == null) ? 0 : path.length();
+ if ((pathLen <= 1) || (path.charAt(pathLen - 1) != '/')) {
+ return path;
+ }
+
+ return path.substring(0, pathLen - 1);
+ }
+
+ /**
+ * Suffix of JAR files
+ */
+ public static final String JAR_FILE_SUFFIX=".jar";
+ /**
+ * URL/URI scheme that refers to a JAR
+ */
+ public static final String JAR_URL_SCHEME="jar";
+ /**
+ * Prefix used in URL(s) that reference a resource inside a JAR
+ */
+ public static final String JAR_URL_PREFIX=JAR_URL_SCHEME + ":";
+
+ public static final String stripJarURLPrefix(String externalForm) {
+ String url=externalForm;
+ if (GenericUtils.isEmpty(url)) {
+ return url;
+ }
+
+ if (url.startsWith(JAR_URL_PREFIX)) {
+ return url.substring(JAR_URL_PREFIX.length());
+ }
+
+ return url;
+ }
+
+ /**
+ * Suffix of compile Java class files
+ */
+ public static final String CLASS_FILE_SUFFIX=".class";
+
+ /**
+ * @param clazz The request {@link Class}
+ * @return A {@link URL} to the location of the <code>.class</code> file
+ * - <code>null</code> if location could not be resolved
+ */
+ public static final URL getClassBytesURL(Class<?> clazz) {
+ String className=clazz.getName();
+ int sepPos=className.indexOf('$');
+ // if this is an internal class, then need to use its parent as well
+ if (sepPos > 0) {
+ if ((sepPos=className.lastIndexOf('.')) > 0) {
+ className = className.substring(sepPos + 1);
+ }
+ } else {
+ className = clazz.getSimpleName();
+ }
+
+ return clazz.getResource(className + CLASS_FILE_SUFFIX);
+ }
+
+ public static final String getClassBytesResourceName(Class<?> clazz) {
+ return getClassBytesResourceName((clazz == null) ? null : clazz.getName());
+ }
+
+ /**
+ * @param name The fully qualified class name - ignored if {@code null}/empty
+ * @return The relative path of the class file byte-code resource
+ */
+ public static final String getClassBytesResourceName(String name) {
+ if (GenericUtils.isEmpty(name)) {
+ return name;
+ } else {
+ return new StringBuilder(name.length() + CLASS_FILE_SUFFIX.length())
+ .append(name.replace('.', '/'))
+ .append(CLASS_FILE_SUFFIX)
+ .toString()
+ ;
+ }
+ }
+
+ public static final List<String> TARGET_FOLDER_NAMES= // NOTE: order is important
+ Collections.unmodifiableList(
+ Arrays.asList("target" /* Maven */, "build" /* Gradle */));
+
+ /**
+ * @param anchorFile An anchor {@link File} we want to use
+ * as the starting point for the "target" or "build" folder
+ * lookup up the hierarchy
+ * @return The "target" <U>folder</U> - <code>null</code> if not found
+ */
+ public static final File detectTargetFolder (File anchorFile) {
+ for (File file=anchorFile; file != null; file=file.getParentFile()) {
+ if (!file.isDirectory()) {
+ continue;
+ }
+
+ String name=file.getName();
+ if (TARGET_FOLDER_NAMES.contains(name)) {
+ return file;
+ }
+ }
+
+ return null;
+ }
+
+ public static final String resolveRelativeRemotePath(Path root, Path file) {
+ Path relPath = root.relativize(file);
+ return relPath.toString().replace(File.separatorChar, '/');
+ }
}
[3/3] mina-sshd git commit: [SSHD-471] Auto-detect 'target' folder
location and use it in the tests
Posted by lg...@apache.org.
[SSHD-471] Auto-detect 'target' folder location and use it in the tests
Project: http://git-wip-us.apache.org/repos/asf/mina-sshd/repo
Commit: http://git-wip-us.apache.org/repos/asf/mina-sshd/commit/b6166cc8
Tree: http://git-wip-us.apache.org/repos/asf/mina-sshd/tree/b6166cc8
Diff: http://git-wip-us.apache.org/repos/asf/mina-sshd/diff/b6166cc8
Branch: refs/heads/master
Commit: b6166cc8d5a7bd4a068a8279d3720e969bd4a12c
Parents: 7b3d9cf
Author: Lyor Goldstein <lg...@vmware.com>
Authored: Mon May 25 16:06:10 2015 +0300
Committer: Lyor Goldstein <lg...@vmware.com>
Committed: Mon May 25 16:06:10 2015 +0300
----------------------------------------------------------------------
.../java/org/apache/sshd/client/SftpClient.java | 5 +
.../sshd/client/sftp/DefaultSftpClient.java | 8 +-
.../sshd/client/sftp/SftpFileChannel.java | 50 +-
.../client/sftp/SftpFileSystemProvider.java | 15 +-
.../org/apache/sshd/client/sftp/SftpPath.java | 15 +-
.../sshd/common/file/root/RootedFileSystem.java | 9 +-
.../file/root/RootedFileSystemProvider.java | 9 +-
.../sshd/common/file/root/RootedPath.java | 22 +-
.../sshd/common/file/util/BaseFileSystem.java | 63 +-
.../apache/sshd/common/file/util/BasePath.java | 56 +-
.../sshd/common/file/util/ImmutableList.java | 6 +-
.../virtualfs/VirtualFileSystemFactory.java | 3 +-
.../common/keyprovider/FileKeyPairProvider.java | 2 +-
.../sshd/common/random/BouncyCastleRandom.java | 2 +-
.../sshd/common/session/AbstractSession.java | 7 +-
.../common/session/AbstractSessionFactory.java | 5 +-
.../apache/sshd/common/util/SecurityUtils.java | 21 +-
.../org/apache/sshd/server/kex/DHGServer.java | 1 -
.../apache/sshd/server/sftp/SftpSubsystem.java | 4 +-
.../src/test/java/org/apache/sshd/ScpTest.java | 846 -----------------
.../org/apache/sshd/SftpFileSystemTest.java | 218 -----
.../src/test/java/org/apache/sshd/SftpTest.java | 606 ------------
.../java/org/apache/sshd/client/ScpTest.java | 935 +++++++++++++++++++
.../sshd/client/sftp/SftpFileSystemTest.java | 260 ++++++
.../org/apache/sshd/client/sftp/SftpTest.java | 680 ++++++++++++++
.../sshd/common/cipher/BaseCipherTest.java | 4 +-
.../sshd/common/file/util/BasePathTest.java | 2 +-
.../PEMGeneratorHostKeyProviderTest.java | 6 +-
.../SimpleGeneratorHostKeyProviderTest.java | 6 +-
.../org/apache/sshd/util/BaseTestSupport.java | 66 ++
.../test/java/org/apache/sshd/util/Utils.java | 409 +++++++-
31 files changed, 2520 insertions(+), 1821 deletions(-)
----------------------------------------------------------------------
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
index b0ca95e..3b8840c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/SftpClient.java
@@ -68,6 +68,11 @@ public interface SftpClient extends Closeable {
public Handle(String id) {
this.id = id;
}
+
+ @Override
+ public String toString() {
+ return id;
+ }
}
public static class Attributes {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/client/sftp/DefaultSftpClient.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/sftp/DefaultSftpClient.java b/sshd-core/src/main/java/org/apache/sshd/client/sftp/DefaultSftpClient.java
index 6381046..19e37b6 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/sftp/DefaultSftpClient.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/sftp/DefaultSftpClient.java
@@ -273,7 +273,7 @@ public class DefaultSftpClient extends AbstractLoggingBean implements SftpClient
DataInputStream dis = new DataInputStream(channel.getInvertedOut());
int length = dis.readInt();
if (length < 5) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Bad length: " + length);
}
Buffer buffer = new ByteArrayBuffer(length + 4);
buffer.putInt(length);
@@ -281,7 +281,7 @@ public class DefaultSftpClient extends AbstractLoggingBean implements SftpClient
while (nb > 0) {
int l = dis.read(buffer.array(), buffer.wpos(), nb);
if (l < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Premature EOF while read " + length + " bytes - remaining=" + nb);
}
buffer.wpos(buffer.wpos() + l);
nb -= l;
@@ -302,7 +302,7 @@ public class DefaultSftpClient extends AbstractLoggingBean implements SftpClient
try {
messages.wait();
} catch (InterruptedException e) {
- throw (IOException) new InterruptedIOException().initCause(e);
+ throw (IOException) new InterruptedIOException("Interruppted init()").initCause(e);
}
}
buffer = messages.remove(messages.keySet().iterator().next());
@@ -991,7 +991,7 @@ public class DefaultSftpClient extends AbstractLoggingBean implements SftpClient
}
@Override
public void remove() {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("readDir(" + path + ") Iterator#remove() N/A");
}
};
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
index 5f651c2..dc61005 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileChannel.java
@@ -18,6 +18,8 @@
*/
package org.apache.sshd.client.sftp;
+import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_LOCK_CONFLICT;
+
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
@@ -29,27 +31,26 @@ import java.nio.channels.OverlappingFileLockException;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Arrays;
+import java.util.Collection;
import java.util.Collections;
-import java.util.EnumSet;
import java.util.List;
+import java.util.Objects;
import java.util.concurrent.atomic.AtomicBoolean;
import org.apache.sshd.client.SftpClient;
import org.apache.sshd.client.SftpException;
-import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_LOCK_CONFLICT;
-
public class SftpFileChannel extends FileChannel {
- final SftpPath p;
- final EnumSet<SftpClient.OpenMode> modes;
- final SftpClient sftp;
- final SftpClient.Handle handle;
- final Object lock;
- volatile long pos;
- volatile Thread blockingThread;
+ private final SftpPath p;
+ private final Collection<SftpClient.OpenMode> modes;
+ private final SftpClient sftp;
+ private final SftpClient.Handle handle;
+ private final Object lock;
+ private volatile long pos;
+ private volatile Thread blockingThread;
- public SftpFileChannel(SftpPath p, EnumSet<SftpClient.OpenMode> modes) throws IOException {
+ public SftpFileChannel(SftpPath p, Collection<SftpClient.OpenMode> modes) throws IOException {
this.p = p;
this.modes = modes;
sftp = p.getFileSystem().getClient();
@@ -66,7 +67,7 @@ public class SftpFileChannel extends FileChannel {
@Override
public int read(ByteBuffer dst, long position) throws IOException {
if (position < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("read(" + p + ") illegal position to read from: " + position);
}
return (int) doRead(Collections.singletonList(dst), position);
}
@@ -127,7 +128,7 @@ public class SftpFileChannel extends FileChannel {
@Override
public int write(ByteBuffer src, long position) throws IOException {
if (position < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("write(" + p + ") illegal position to write to: " + position);
}
return (int) doWrite(Collections.singletonList(src), position);
}
@@ -182,7 +183,7 @@ public class SftpFileChannel extends FileChannel {
@Override
public FileChannel position(long newPosition) throws IOException {
if (newPosition < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("position(" + p + ") illegal file channel position: " + newPosition);
}
ensureOpen();
synchronized (lock) {
@@ -209,8 +210,8 @@ public class SftpFileChannel extends FileChannel {
@Override
public long transferTo(long position, long count, WritableByteChannel target) throws IOException {
- if (position < 0 || count < 0) {
- throw new IllegalArgumentException();
+ if ((position < 0) || (count < 0)) {
+ throw new IllegalArgumentException("transferTo(" + p + ") illegal position (" + position + ") or count (" + count + ")");
}
ensureOpen();
synchronized (lock) {
@@ -218,10 +219,11 @@ public class SftpFileChannel extends FileChannel {
boolean eof = false;
long curPos = position;
try {
- long totalRead = 0;
beginBlocking();
- byte[] buffer = new byte[32768];
+ int bufSize = (int) Math.min(count, 32768);
+ byte[] buffer = new byte[bufSize];
+ long totalRead = 0L;
while (totalRead < count) {
int read = sftp.read(handle, curPos, buffer, 0, buffer.length);
if (read > 0) {
@@ -245,8 +247,8 @@ public class SftpFileChannel extends FileChannel {
@Override
public long transferFrom(ReadableByteChannel src, long position, long count) throws IOException {
- if (position < 0 || count < 0) {
- throw new IllegalArgumentException();
+ if ((position < 0) || (count < 0)) {
+ throw new IllegalArgumentException("transferFrom(" + p + ") illegal position (" + position + ") or count (" + count + ")");
}
ensureOpen();
synchronized (lock) {
@@ -278,7 +280,7 @@ public class SftpFileChannel extends FileChannel {
@Override
public MappedByteBuffer map(MapMode mode, long position, long size) throws IOException {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("map(" + p + ")[" + mode + "," + position + "," + size + "] N/A");
}
@Override
@@ -305,6 +307,7 @@ public class SftpFileChannel extends FileChannel {
return acquiredBy().isOpen() && valid.get();
}
+ @SuppressWarnings("synthetic-access")
@Override
public void release() throws IOException {
if (valid.compareAndSet(true, false)) {
@@ -345,4 +348,9 @@ public class SftpFileChannel extends FileChannel {
throw new ClosedChannelException();
}
}
+
+ @Override
+ public String toString() {
+ return Objects.toString(p);
+ }
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileSystemProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileSystemProvider.java b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileSystemProvider.java
index ec3c2f3..4e3e9b8 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileSystemProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpFileSystemProvider.java
@@ -217,7 +217,7 @@ public class SftpFileSystemProvider extends FileSystemProvider {
@Override
public void remove() {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("newDirectoryStream(" + p + ") Iterator#remove() N/A");
}
};
}
@@ -420,7 +420,7 @@ public class SftpFileSystemProvider extends FileSystemProvider {
@Override
public FileStore getFileStore(Path path) throws IOException {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("getFileStore(" + path + ") N/A");
}
@Override
@@ -598,7 +598,7 @@ public class SftpFileSystemProvider extends FileSystemProvider {
}
};
} else {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("getFileAttributeView(" + path + ") view not supported: " + type.getSimpleName());
}
}
@@ -625,8 +625,9 @@ public class SftpFileSystemProvider extends FileSystemProvider {
}
SftpPath p = toSftpPath(path);
if (!p.getFileSystem().supportedFileAttributeViews().contains(view)) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("readAttributes(" + path + ")[" + attributes + "] view not supported: " + view);
}
+
PosixFileAttributes v = readAttributes(path, PosixFileAttributes.class, options);
if ("*".equals(attrs)) {
attrs = "lastModifiedTime,lastAccessTime,creationTime,size,isRegularFile,isDirectory,isSymbolicLink,isOther,fileKey,owner,permissions,group";
@@ -693,8 +694,9 @@ public class SftpFileSystemProvider extends FileSystemProvider {
}
SftpPath p = toSftpPath(path);
if (!p.getFileSystem().supportedFileAttributeViews().contains(view)) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("setAttribute(" + path + ")[" + attribute + "=" + value + "] view not supported: " + view);
}
+
SftpClient.Attributes attributes = new SftpClient.Attributes();
switch (attr) {
case "lastModifiedTime":
@@ -726,7 +728,8 @@ public class SftpFileSystemProvider extends FileSystemProvider {
case "isSymbolicLink":
case "isOther":
case "fileKey":
- throw new UnsupportedOperationException("setAttribute(" + path + ")[" + attribute + "] unknown view attribute: " + attr);
+ throw new UnsupportedOperationException("setAttribute(" + path + ")[" + attribute + "=" + value + "]"
+ + " unknown view=" + view + " attribute: " + attr);
default:
if (log.isTraceEnabled()) {
log.trace("setAttribute({})[{}] ignore {}={}", path, attribute, attr, value);
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpPath.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpPath.java b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpPath.java
index a1afbd8..d4e0b0b 100644
--- a/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpPath.java
+++ b/sshd-core/src/main/java/org/apache/sshd/client/sftp/SftpPath.java
@@ -19,33 +19,28 @@
package org.apache.sshd.client.sftp;
import java.io.IOException;
-import java.net.URI;
+import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
+import java.nio.file.spi.FileSystemProvider;
import org.apache.sshd.common.file.util.BasePath;
import org.apache.sshd.common.file.util.ImmutableList;
public class SftpPath extends BasePath<SftpPath, SftpFileSystem> {
-
public SftpPath(SftpFileSystem fileSystem, String root, ImmutableList<String> names) {
super(fileSystem, root, names);
}
@Override
- public URI toUri() {
- // TODO
- return null;
- }
-
- @Override
public SftpPath toRealPath(LinkOption... options) throws IOException {
// try (SftpClient client = fileSystem.getClient()) {
// client.realP
// }
// TODO: handle links
SftpPath absolute = toAbsolutePath();
- fileSystem.provider().checkAccess(absolute);
+ FileSystem fs = getFileSystem();
+ FileSystemProvider provider = fs.provider();
+ provider.checkAccess(absolute);
return absolute;
}
-
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
index fa24a39..2a0769e 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystem.java
@@ -32,15 +32,15 @@ import org.apache.sshd.common.file.util.ImmutableList;
*/
public class RootedFileSystem extends BaseFileSystem<RootedPath> {
- private Path root;
+ private Path rootPath;
public RootedFileSystem(RootedFileSystemProvider fileSystemProvider, Path root, Map<String, ?> env) {
super(fileSystemProvider);
- this.root = root;
+ this.rootPath = root;
}
public Path getRoot() {
- return root;
+ return rootPath;
}
@Override
@@ -60,7 +60,7 @@ public class RootedFileSystem extends BaseFileSystem<RootedPath> {
@Override
public Set<String> supportedFileAttributeViews() {
- return root.getFileSystem().supportedFileAttributeViews();
+ return rootPath.getFileSystem().supportedFileAttributeViews();
}
@Override
@@ -72,5 +72,4 @@ public class RootedFileSystem extends BaseFileSystem<RootedPath> {
protected RootedPath create(String root, ImmutableList<String> names) {
return new RootedPath(this, root, names);
}
-
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
index b355036..69d08ec 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedFileSystemProvider.java
@@ -57,8 +57,11 @@ import org.apache.sshd.common.util.IoUtils;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class RootedFileSystemProvider extends FileSystemProvider {
+ private final Map<Path, RootedFileSystem> fileSystems = new HashMap<>();
- final Map<Path, RootedFileSystem> fileSystems = new HashMap<>();
+ public RootedFileSystemProvider() {
+ super();
+ }
@Override
public String getScheme() {
@@ -125,7 +128,7 @@ public class RootedFileSystemProvider extends FileSystemProvider {
private boolean ensureDirectory(Path path) {
if (!Files.isDirectory(path, IoUtils.getLinkOptions(false))) {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Not a directory: " + path);
}
return true;
}
@@ -244,7 +247,7 @@ public class RootedFileSystemProvider extends FileSystemProvider {
@Override
public FileStore getFileStore(Path path) throws IOException {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("getFileStore(" + path + ") N/A");
}
@Override
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedPath.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedPath.java b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedPath.java
index 8b06584..ca723d2 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedPath.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/root/RootedPath.java
@@ -18,9 +18,12 @@
*/
package org.apache.sshd.common.file.root;
+import java.io.File;
import java.io.IOException;
-import java.net.URI;
+import java.nio.file.FileSystem;
import java.nio.file.LinkOption;
+import java.nio.file.Path;
+import java.nio.file.spi.FileSystemProvider;
import org.apache.sshd.common.file.util.BasePath;
import org.apache.sshd.common.file.util.ImmutableList;
@@ -29,22 +32,27 @@ import org.apache.sshd.common.file.util.ImmutableList;
* @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
*/
public class RootedPath extends BasePath<RootedPath, RootedFileSystem> {
-
public RootedPath(RootedFileSystem fileSystem, String root, ImmutableList<String> names) {
super(fileSystem, root, names);
}
@Override
- public URI toUri() {
- // TODO
- return null;
+ public File toFile() {
+ RootedPath absolute = toAbsolutePath();
+ RootedFileSystem fs = getFileSystem();
+ Path path = fs.getRoot();
+ for (String n : absolute.names) {
+ path = path.resolve(n);
+ }
+ return path.toFile();
}
@Override
public RootedPath toRealPath(LinkOption... options) throws IOException {
RootedPath absolute = toAbsolutePath();
- fileSystem.provider().checkAccess(absolute);
+ FileSystem fs = getFileSystem();
+ FileSystemProvider provider = fs.provider();
+ provider.checkAccess(absolute);
return absolute;
}
-
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
index 68869ca..c6bd7df 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BaseFileSystem.java
@@ -27,8 +27,11 @@ import java.nio.file.WatchService;
import java.nio.file.spi.FileSystemProvider;
import java.util.Collection;
import java.util.Collections;
+import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.sshd.common.util.GenericUtils;
+
public abstract class BaseFileSystem<T extends Path> extends FileSystem {
private final FileSystemProvider fileSystemProvider;
@@ -63,41 +66,44 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
@Override
public Iterable<FileStore> getFileStores() {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("No file stores available");
}
@Override
public T getPath(String first, String... more) {
StringBuilder sb = new StringBuilder();
- appendDedupSep(sb, first);
- for (String segment : more) {
- if (sb.length() > 0 && sb.charAt(sb.length() - 1) != '/') {
- sb.append('/');
+ if (!GenericUtils.isEmpty(first)) {
+ appendDedupSep(sb, first.replace('\\', '/')); // in case we are running on Windows
+ }
+
+ if (GenericUtils.length(more) > 0) {
+ for (String segment : more) {
+ if ((sb.length() > 0) && (sb.charAt(sb.length() - 1) != '/')) {
+ sb.append('/');
+ }
+ // in case we are running on Windows
+ appendDedupSep(sb, segment.replace('\\', '/'));
}
- appendDedupSep(sb, segment);
}
- if (sb.length() > 1 && sb.charAt(sb.length() - 1) == '/') {
+
+ if ((sb.length() > 1) && (sb.charAt(sb.length() - 1) == '/')) {
sb.setLength(sb.length() - 1);
}
- String path = sb.toString();
- String root = null;
+
+ String path = sb.toString(), root = null;
if (path.startsWith("/")) {
root = "/";
path = path.substring(1);
}
- String[] names;
- if (path.length() > 0) {
- names = path.split("/");
- } else {
- names = new String[0];
- }
+
+ String[] names=GenericUtils.split(path, '/');
return create(root, names);
}
private void appendDedupSep(StringBuilder sb, String s) {
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
- if (ch != '/' || sb.length() == 0 || sb.charAt(sb.length() - 1) != '/') {
+ if ((ch != '/') || (sb.length() == 0) || (sb.charAt(sb.length() - 1) != '/')) {
sb.append(ch);
}
}
@@ -106,7 +112,7 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
@Override
public PathMatcher getPathMatcher(String syntaxAndPattern) {
int colonIndex = syntaxAndPattern.indexOf(':');
- if (colonIndex <= 0 || colonIndex == syntaxAndPattern.length() - 1) {
+ if ((colonIndex <= 0) || (colonIndex == syntaxAndPattern.length() - 1)) {
throw new IllegalArgumentException("syntaxAndPattern must have form \"syntax:pattern\" but was \"" + syntaxAndPattern + "\"");
}
@@ -114,20 +120,21 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
String pattern = syntaxAndPattern.substring(colonIndex + 1);
String expr;
switch (syntax) {
- case "glob":
- expr = globToRegex(pattern);
- break;
- case "regex":
- expr = pattern;
- break;
- default:
- throw new UnsupportedOperationException("Unsupported syntax \'" + syntax + "\'");
- }
+ case "glob":
+ expr = globToRegex(pattern);
+ break;
+ case "regex":
+ expr = pattern;
+ break;
+ default:
+ throw new UnsupportedOperationException("Unsupported path matcher syntax: \'" + syntax + "\'");
+ }
final Pattern regex = Pattern.compile(expr);
return new PathMatcher() {
@Override
public boolean matches(Path path) {
- return regex.matcher(path.toString()).matches();
+ Matcher m = regex.matcher(path.toString());
+ return m.matches();
}
};
}
@@ -223,7 +230,7 @@ public abstract class BaseFileSystem<T extends Path> extends FileSystem {
@Override
public WatchService newWatchService() throws IOException {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("Watch service N/A");
}
protected T create(String root, String... names) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
index 2bc3542..a74b1c0 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/util/BasePath.java
@@ -20,6 +20,8 @@ package org.apache.sshd.common.file.util;
import java.io.File;
import java.io.IOException;
+import java.net.URI;
+import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.nio.file.ProviderMismatchException;
import java.nio.file.WatchEvent;
@@ -35,9 +37,11 @@ import java.util.Iterator;
import java.util.List;
import java.util.Objects;
+import org.apache.sshd.common.util.GenericUtils;
+
public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSystem<T>> implements Path {
- protected final FS fileSystem;
+ private final FS fileSystem;
protected final String root;
protected final ImmutableList<String> names;
@@ -51,6 +55,7 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
protected T asT() {
return (T) this;
}
+
protected T create(String root, String... names) {
return create(root, new ImmutableList<>(names));
}
@@ -91,7 +96,7 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
@Override
public T getParent() {
- if (names.isEmpty() || names.size() == 1 && root == null) {
+ if (names.isEmpty() || ((names.size() == 1) && (root == null))) {
return null;
}
return create(root, names.subList(0, names.size() - 1));
@@ -104,16 +109,18 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
@Override
public T getName(int index) {
- if (index < 0 || index >= names.size()) {
- throw new IllegalArgumentException();
+ int maxIndex = getNameCount();
+ if ((index < 0) || (index >= maxIndex)) {
+ throw new IllegalArgumentException("Invalid name index " + index + " - not in range [0-" + maxIndex + "]");
}
return create(null, names.subList(index, index + 1));
}
@Override
public T subpath(int beginIndex, int endIndex) {
- if ((beginIndex < 0) || (beginIndex >= names.size()) || (endIndex > names.size()) || (beginIndex >= endIndex)) {
- throw new IllegalArgumentException();
+ int maxIndex = getNameCount();
+ if ((beginIndex < 0) || (beginIndex >= maxIndex) || (endIndex > maxIndex) || (beginIndex >= endIndex)) {
+ throw new IllegalArgumentException("subpath(" + beginIndex + "," + endIndex + ") bad index range - allowed [0-" + maxIndex + "]");
}
return create(null, names.subList(beginIndex, endIndex));
}
@@ -126,9 +133,9 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
public boolean startsWith(Path other) {
T p1 = asT();
T p2 = checkPath(other);
- return p1.getFileSystem().equals(p2.getFileSystem())
- && Objects.equals(p1.root, p2.root)
- && startsWith(p1.names, p2.names);
+ return Objects.equals(p1.getFileSystem(), p2.getFileSystem())
+ && Objects.equals(p1.root, p2.root)
+ && startsWith(p1.names, p2.names);
}
@Override
@@ -156,7 +163,8 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
}
private boolean isNormal() {
- if (getNameCount() == 0 || getNameCount() == 1 && !isAbsolute()) {
+ int count = getNameCount();
+ if ((count == 0) || ((count == 1) && !isAbsolute())) {
return true;
}
boolean foundNonParentName = isAbsolute(); // if there's a root, the path doesn't start with ..
@@ -225,13 +233,13 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
@Override
public T resolve(String other) {
- return resolve(getFileSystem().getPath(other));
+ return resolve(getFileSystem().getPath(other, GenericUtils.EMPTY_STRING_ARRAY));
}
@Override
public Path resolveSibling(Path other) {
if (other == null) {
- throw new NullPointerException();
+ throw new NullPointerException("Missing sibling path argument");
}
T parent = getParent();
return parent == null ? other : parent.resolve(other);
@@ -239,7 +247,7 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
@Override
public Path resolveSibling(String other) {
- return resolveSibling(getFileSystem().getPath(other));
+ return resolveSibling(getFileSystem().getPath(other, GenericUtils.EMPTY_STRING_ARRAY));
}
@Override
@@ -285,18 +293,24 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
}
@Override
- public File toFile() {
- throw new UnsupportedOperationException();
+ public URI toUri() {
+ File file = toFile();
+ return file.toURI();
}
@Override
- public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
- throw new UnsupportedOperationException();
+ public File toFile() {
+ throw new UnsupportedOperationException("To file " + toAbsolutePath() + " N/A");
}
@Override
public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events) throws IOException {
- throw new UnsupportedOperationException();
+ return register(watcher, events, (WatchEvent.Modifier[]) null);
+ }
+
+ @Override
+ public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException {
+ throw new UnsupportedOperationException("Register to watch " + toAbsolutePath() + " N/A");
}
@Override
@@ -350,8 +364,10 @@ public abstract class BasePath<T extends BasePath<T, FS>, FS extends BaseFileSys
throw new ProviderMismatchException();
}
T t = (T) paramPath;
- if (t.fileSystem.provider() != this.fileSystem.provider()) {
- throw new ProviderMismatchException();
+
+ FileSystem fs = t.getFileSystem();
+ if (fs.provider() != this.fileSystem.provider()) {
+ throw new ProviderMismatchException("Mismatched providers for " + t);
}
return t;
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/util/ImmutableList.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/util/ImmutableList.java b/sshd-core/src/main/java/org/apache/sshd/common/file/util/ImmutableList.java
index 88d9f5c..4193fa0 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/util/ImmutableList.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/util/ImmutableList.java
@@ -26,9 +26,9 @@ import java.util.AbstractList;
*/
public class ImmutableList<T> extends AbstractList<T> {
- final T[] data;
- final int from;
- final int to;
+ private final T[] data;
+ private final int from;
+ private final int to;
public ImmutableList(T[] data) {
this(data, 0, data.length);
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java b/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
index 7b60d65..60131ca 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/file/virtualfs/VirtualFileSystemFactory.java
@@ -21,6 +21,7 @@ package org.apache.sshd.common.file.virtualfs;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Paths;
+import java.util.Collections;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -73,7 +74,7 @@ public class VirtualFileSystemFactory implements FileSystemFactory {
@Override
public FileSystem createFileSystem(Session session) throws IOException {
String dir = computeRootDir(session.getUsername());
- return new RootedFileSystemProvider().newFileSystem(Paths.get(dir), null);
+ return new RootedFileSystemProvider().newFileSystem(Paths.get(dir), Collections.<String,Object>emptyMap());
}
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/FileKeyPairProvider.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/FileKeyPairProvider.java b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/FileKeyPairProvider.java
index 3dae6d3..01d6df9 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/FileKeyPairProvider.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/keyprovider/FileKeyPairProvider.java
@@ -105,7 +105,7 @@ public class FileKeyPairProvider extends AbstractKeyPairProvider {
}
@Override
public void remove() {
- throw new UnsupportedOperationException();
+ throw new UnsupportedOperationException("loadKeys(files) Iterator#remove() N/A");
}
private boolean setNextObject() {
while (iterator.hasNext()) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/random/BouncyCastleRandom.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/random/BouncyCastleRandom.java b/sshd-core/src/main/java/org/apache/sshd/common/random/BouncyCastleRandom.java
index de5b12e..eb5967a 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/random/BouncyCastleRandom.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/random/BouncyCastleRandom.java
@@ -87,7 +87,7 @@ public class BouncyCastleRandom implements Random {
} while (bits - val + (n-1) < 0);
return val;
}
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Limit must be positive: " + n);
}
final protected int next(int numBits) {
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
index 2706dca..9df5f4c 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSession.java
@@ -64,6 +64,7 @@ import org.apache.sshd.common.io.IoWriteFuture;
import org.apache.sshd.common.util.CloseableUtils;
import org.apache.sshd.common.util.EventListenerUtils;
import org.apache.sshd.common.util.Readable;
+import org.apache.sshd.common.util.ValidateUtils;
import org.apache.sshd.common.util.buffer.Buffer;
import org.apache.sshd.common.util.buffer.BufferUtils;
import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
@@ -1295,9 +1296,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
*/
@Override
public void addListener(SessionListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException();
- }
+ ValidateUtils.checkNotNull(listener, "addListener(%s) null instance", this);
this.listeners.add(listener);
}
@@ -1441,7 +1440,7 @@ public abstract class AbstractSession extends CloseableUtils.AbstractInnerClosea
public void setException(Throwable cause) {
if (cause == null) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("No cause specified");
}
setValue(cause);
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
index 763ab81..8e16eb7 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/session/AbstractSessionFactory.java
@@ -24,6 +24,7 @@ import java.util.concurrent.CopyOnWriteArrayList;
import org.apache.sshd.common.AbstractSessionIoHandler;
import org.apache.sshd.common.SessionListener;
import org.apache.sshd.common.io.IoSession;
+import org.apache.sshd.common.util.ValidateUtils;
/**
* An abstract base factory of sessions.
@@ -58,9 +59,7 @@ public abstract class AbstractSessionFactory extends AbstractSessionIoHandler {
* @param listener the session listener to add
*/
public void addListener(SessionListener listener) {
- if (listener == null) {
- throw new IllegalArgumentException();
- }
+ ValidateUtils.checkNotNull(listener, "addListener(%s) no listener", this);
this.listeners.add(listener);
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java b/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java
index 1a8bd7e..1bb460f 100644
--- a/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java
+++ b/sshd-core/src/main/java/org/apache/sshd/common/util/SecurityUtils.java
@@ -18,18 +18,16 @@
*/
package org.apache.sshd.common.util;
+import java.security.GeneralSecurityException;
import java.security.KeyFactory;
import java.security.KeyPairGenerator;
import java.security.MessageDigest;
-import java.security.NoSuchAlgorithmException;
-import java.security.NoSuchProviderException;
import java.security.Signature;
import java.util.concurrent.Callable;
import javax.crypto.Cipher;
import javax.crypto.KeyAgreement;
import javax.crypto.Mac;
-import javax.crypto.NoSuchPaddingException;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.slf4j.Logger;
@@ -92,7 +90,7 @@ public class SecurityUtils {
registerBouncyCastle = Boolean.valueOf(prop);
}
}
- if (securityProvider == null && (registerBouncyCastle == null || registerBouncyCastle.booleanValue())) {
+ if ((securityProvider == null) && ((registerBouncyCastle == null) || registerBouncyCastle.booleanValue())) {
// Use an inner class to avoid a strong dependency from SshServer on BouncyCastle
try {
new BouncyCastleRegistration().call();
@@ -127,7 +125,7 @@ public class SecurityUtils {
}
}
- public static synchronized KeyFactory getKeyFactory(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
+ public static synchronized KeyFactory getKeyFactory(String algorithm) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return KeyFactory.getInstance(algorithm);
@@ -136,7 +134,7 @@ public class SecurityUtils {
}
}
- public static synchronized Cipher getCipher(String transformation) throws NoSuchAlgorithmException, NoSuchPaddingException, NoSuchProviderException {
+ public static synchronized Cipher getCipher(String transformation) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return Cipher.getInstance(transformation);
@@ -145,7 +143,7 @@ public class SecurityUtils {
}
}
- public static synchronized MessageDigest getMessageDigest(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
+ public static synchronized MessageDigest getMessageDigest(String algorithm) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return MessageDigest.getInstance(algorithm);
@@ -154,7 +152,7 @@ public class SecurityUtils {
}
}
- public static synchronized KeyPairGenerator getKeyPairGenerator(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
+ public static synchronized KeyPairGenerator getKeyPairGenerator(String algorithm) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return KeyPairGenerator.getInstance(algorithm);
@@ -163,7 +161,7 @@ public class SecurityUtils {
}
}
- public static synchronized KeyAgreement getKeyAgreement(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
+ public static synchronized KeyAgreement getKeyAgreement(String algorithm) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return KeyAgreement.getInstance(algorithm);
@@ -172,7 +170,7 @@ public class SecurityUtils {
}
}
- public static synchronized Mac getMac(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
+ public static synchronized Mac getMac(String algorithm) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return Mac.getInstance(algorithm);
@@ -181,7 +179,7 @@ public class SecurityUtils {
}
}
- public static synchronized Signature getSignature(String algorithm) throws NoSuchAlgorithmException, NoSuchProviderException {
+ public static synchronized Signature getSignature(String algorithm) throws GeneralSecurityException {
register();
if (getSecurityProvider() == null) {
return Signature.getInstance(algorithm);
@@ -189,5 +187,4 @@ public class SecurityUtils {
return Signature.getInstance(algorithm, getSecurityProvider());
}
}
-
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java b/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
index c18d532..0911ca7 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/kex/DHGServer.java
@@ -62,7 +62,6 @@ public class DHGServer extends AbstractDHServerKeyExchange {
}
protected DHGServer(DHFactory factory) {
- super();
this.factory = factory;
}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/main/java/org/apache/sshd/server/sftp/SftpSubsystem.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/main/java/org/apache/sshd/server/sftp/SftpSubsystem.java b/sshd-core/src/main/java/org/apache/sshd/server/sftp/SftpSubsystem.java
index d332508..0fdb213 100644
--- a/sshd-core/src/main/java/org/apache/sshd/server/sftp/SftpSubsystem.java
+++ b/sshd-core/src/main/java/org/apache/sshd/server/sftp/SftpSubsystem.java
@@ -417,7 +417,7 @@ public class SftpSubsystem extends AbstractLoggingBean implements Command, Runna
while (true) {
int length = dis.readInt();
if (length < 5) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Bad length to read: " + length);
}
Buffer buffer = new ByteArrayBuffer(length + 4);
buffer.putInt(length);
@@ -425,7 +425,7 @@ public class SftpSubsystem extends AbstractLoggingBean implements Command, Runna
while (nb > 0) {
int l = dis.read(buffer.array(), buffer.wpos(), nb);
if (l < 0) {
- throw new IllegalArgumentException();
+ throw new IllegalArgumentException("Premature EOF while read length=" + length + " while remain=" + nb);
}
buffer.wpos(buffer.wpos() + l);
nb -= l;
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/ScpTest.java b/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
deleted file mode 100644
index 8b2a90a..0000000
--- a/sshd-core/src/test/java/org/apache/sshd/ScpTest.java
+++ /dev/null
@@ -1,846 +0,0 @@
-/*
- * 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;
-
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.nio.channels.FileChannel;
-import java.nio.file.Path;
-import java.nio.file.attribute.PosixFilePermission;
-import java.util.Collection;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-
-import ch.ethz.ssh2.Connection;
-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.ScpClient;
-import org.apache.sshd.common.scp.ScpTransferEventListener;
-import org.apache.sshd.common.util.OsUtils;
-import org.apache.sshd.server.command.ScpCommandFactory;
-import org.apache.sshd.util.BaseTestSupport;
-import org.apache.sshd.util.BogusPasswordAuthenticator;
-import org.apache.sshd.util.EchoShellFactory;
-import org.apache.sshd.util.JSchLogger;
-import org.apache.sshd.util.SimpleUserInfo;
-import org.apache.sshd.util.Utils;
-import org.junit.After;
-import org.junit.Assume;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-/**
- * Test for SCP support.
- *
- * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
- */
-public class ScpTest extends BaseTestSupport {
-
- private SshServer sshd;
- private int port;
- private com.jcraft.jsch.Session session;
-
- @Before
- public void setUp() throws Exception {
- sshd = SshServer.setUpDefaultServer();
- sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
- sshd.setCommandFactory(new ScpCommandFactory());
- sshd.setShellFactory(new EchoShellFactory());
- sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
- sshd.start();
- port = sshd.getPort();
- }
-
- protected com.jcraft.jsch.Session getJschSession() throws JSchException {
- JSchLogger.init();
- JSch sch = new JSch();
- session = sch.getSession("sshd", "localhost", port);
- session.setUserInfo(new SimpleUserInfo("sshd"));
- session.connect();
- return session;
- }
-
- @After
- public void tearDown() throws Exception {
- if (session != null) {
- session.disconnect();
- }
- sshd.stop(true);
- }
-
- @Test
- @Ignore
- public void testExternal() throws Exception {
- System.out.println("Scp available on port " + port);
- Thread.sleep(5 * 60000);
- }
-
- @Test
- public void testUploadAbsoluteDriveLetter() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
-
- File localDir = assertHierarchyTargetFolderExists(new File(root, "local"));
- assertTrue("Root folder not created", root.exists());
-
- File localFile = new File(localDir, "out.txt");
- writeFile(localFile, data);
-
- File remoteDir = assertHierarchyTargetFolderExists(new File(root, "remote"));
- File remoteFile = new File(remoteDir, "out.txt");
- scp.upload(localFile.getAbsolutePath(), remoteFile.getAbsolutePath().replace(File.separatorChar, '/'));
- assertFileLength(remoteFile, data.length(), 5000);
-
- File secondRemote = new File(remoteDir, "out2.txt");
- scp.upload(localFile.getAbsolutePath(), secondRemote.getAbsolutePath().replace(File.separatorChar, '/'));
- assertFileLength(secondRemote, data.length(), 5000);
-
- File pathRemote = new File(remoteDir, "path.txt");
- scp.upload(localFile.toPath(), pathRemote.getAbsolutePath().replace(File.separatorChar, '/'));
- assertFileLength(pathRemote, data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpUploadOverwrite() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
- root.mkdirs();
- new File(root, "local").mkdirs();
- assertTrue(root.exists());
-
- new File(root, "remote").mkdirs();
- writeFile(new File("target/scp/remote/out.txt"), data + data);
-
- writeFile(new File("target/scp/local/out.txt"), data);
- scp.upload("target/scp/local/out.txt", "target/scp/remote/out.txt");
- assertFileLength(new File("target/scp/remote/out.txt"), data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpUploadZeroLengthFile() throws Exception {
- File root = assertHierarchyTargetFolderExists(new File("target/scp"));
- File local = assertHierarchyTargetFolderExists(new File(root, "local"));
- File remote = assertHierarchyTargetFolderExists(new File(root, "remote"));
- File zeroLocal = new File(local, getCurrentTestName());
-
- try (FileOutputStream fout = new FileOutputStream(zeroLocal)) {
- if (zeroLocal.length() > 0L) {
- FileChannel fch = fout.getChannel();
- try {
- fch.truncate(0L);
- } finally {
- fch.close();
- }
- }
- }
-
- assertEquals("Non-zero size for local file=" + zeroLocal.getAbsolutePath(), 0L, zeroLocal.length());
-
- File zeroRemote = new File(remote, zeroLocal.getName());
- if (zeroRemote.exists()) {
- assertTrue("Failed to delete remote target " + zeroRemote.getAbsolutePath(), zeroRemote.delete());
- }
-
- try (SshClient client = SshClient.setUpDefaultClient()) {
- try {
- client.start();
-
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
- scp.upload("target/scp/local/" + zeroLocal.getName(), "target/scp/remote/" + zeroRemote.getName());
- assertFileLength(zeroRemote, 0L, TimeUnit.SECONDS.toMillis(5L));
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpDownloadZeroLengthFile() throws Exception {
- File root = assertHierarchyTargetFolderExists(new File("target/scp"));
- File local = assertHierarchyTargetFolderExists(new File(root, "local"));
- File remote = assertHierarchyTargetFolderExists(new File(root, "remote"));
- File zeroLocal = new File(local, getCurrentTestName());
- if (zeroLocal.exists()) {
- assertTrue("Failed to delete local target " + zeroLocal.getAbsolutePath(), zeroLocal.delete());
- }
-
- File zeroRemote = new File(remote, zeroLocal.getName());
- try (FileOutputStream fout = new FileOutputStream(zeroRemote)) {
- if (zeroRemote.length() > 0L) {
- FileChannel fch = fout.getChannel();
- try {
- fch.truncate(0L);
- } finally {
- fch.close();
- }
- }
- }
-
- assertEquals("Non-zero size for remote file=" + zeroRemote.getAbsolutePath(), 0L, zeroRemote.length());
-
- try (SshClient client = SshClient.setUpDefaultClient()) {
- try {
- client.start();
-
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
- scp.download("target/scp/remote/" + zeroRemote.getName(), "target/scp/local/" + zeroLocal.getName());
- assertFileLength(zeroLocal, 0L, TimeUnit.SECONDS.toMillis(5L));
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpNativeOnSingleFile() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target" + File.separator + "scp");
- Utils.deleteRecursive(root);
- assertTrue("Failed to create root: " + root.getAbsolutePath(), root.mkdirs());
-
- File local=new File(root, "local");
- assertTrue("Failed to create local folder: " + local.getAbsolutePath(), local.mkdirs());
-
- File remote=new File(root, "remote");
- File localOutFile=new File(local, "out.txt");
- File remoteOutFile=new File(remote, localOutFile.getName());
- String remoteOutPath=remoteOutFile.getAbsolutePath().replace(File.separatorChar, '/');
- writeFile(localOutFile, data);
-
- try {
- scp.upload(localOutFile.getAbsolutePath(), remoteOutPath);
- fail("Expected IOException for 1st time " + remoteOutPath);
- } catch(IOException e) {
- // ok
- }
-
- assertTrue("Failed to create remote folder: " + remote.getAbsolutePath(), remote.mkdirs());
- scp.upload(localOutFile.getAbsolutePath(), remoteOutPath);
- assertFileLength(remoteOutFile, data.length(), 5000);
-
- File secondLocal=new File(local, "out2.txt");
- scp.download(remoteOutPath, secondLocal.getAbsolutePath());
- assertFileLength(secondLocal, data.length(), 5000);
-
- File localPath=new File(local, "path.txt");
- scp.download(remoteOutPath, localPath.toPath());
- assertFileLength(localPath, data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpNativeOnMultipleFiles() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
- root.mkdirs();
- new File(root, "local").mkdirs();
- new File(root, "remote").mkdirs();
- assertTrue(root.exists());
-
- writeFile(new File("target/scp/local/out1.txt"), data);
- writeFile(new File("target/scp/local/out2.txt"), data);
- try {
- scp.upload(new String[]{"target/scp/local/out1.txt", "target/scp/local/out2.txt"}, "target/scp/remote/out.txt");
- fail("Expected IOException");
- } catch (IOException e) {
- // Ok
- }
- writeFile(new File("target/scp/remote/out.txt"), data);
- try {
- scp.upload(new String[]{"target/scp/local/out1.txt", "target/scp/local/out2.txt"}, "target/scp/remote/out.txt");
- fail("Expected IOException");
- } catch (IOException e) {
- // Ok
- }
- new File(root, "remote/dir").mkdirs();
- scp.upload(new String[]{"target/scp/local/out1.txt", "target/scp/local/out2.txt"}, "target/scp/remote/dir");
- assertFileLength(new File("target/scp/remote/dir/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/remote/dir/out2.txt"), data.length(), 5000);
-
- try {
- scp.download(new String[]{"target/scp/remote/dir/out1.txt", "target/scp/remote/dir/out2.txt"}, "target/scp/local/out1.txt");
- fail("Expected IOException");
- } catch (IOException e) {
- // Ok
- }
- try {
- scp.download(new String[]{"target/scp/remote/dir/out1.txt", "target/scp/remote/dir/out2.txt"}, "target/scp/local/dir");
- fail("Expected IOException");
- } catch (IOException e) {
- // Ok
- }
- new File(root, "local/dir").mkdirs();
- scp.download(new String[]{"target/scp/remote/dir/out1.txt", "target/scp/remote/dir/out2.txt"}, "target/scp/local/dir");
- assertFileLength(new File("target/scp/local/dir/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/local/dir/out2.txt"), data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpNativeOnRecursiveDirs() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
- root.mkdirs();
- new File(root, "local").mkdirs();
- new File(root, "remote").mkdirs();
- assertTrue(root.exists());
-
- new File("target/scp/local/dir").mkdirs();
- writeFile(new File("target/scp/local/dir/out1.txt"), data);
- writeFile(new File("target/scp/local/dir/out2.txt"), data);
- scp.upload("target/scp/local/dir", "target/scp/remote/", ScpClient.Option.Recursive);
- assertFileLength(new File("target/scp/remote/dir/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/remote/dir/out2.txt"), data.length(), 5000);
-
- Utils.deleteRecursive(new File("target/scp/local/dir"));
- scp.download("target/scp/remote/dir", "target/scp/local", ScpClient.Option.Recursive);
- assertFileLength(new File("target/scp/local/dir/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/local/dir/out2.txt"), data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpNativeOnDirWithPattern() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
- root.mkdirs();
- new File(root, "local").mkdirs();
- new File(root, "remote").mkdirs();
- assertTrue(root.exists());
-
- writeFile(new File("target/scp/local/out1.txt"), data);
- writeFile(new File("target/scp/local/out2.txt"), data);
- scp.upload("target/scp/local/*", "target/scp/remote/");
- assertFileLength(new File("target/scp/remote/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/remote/out2.txt"), data.length(), 5000);
-
- new File("target/scp/local/out1.txt").delete();
- new File("target/scp/local/out2.txt").delete();
- scp.download("target/scp/remote/*", "target/scp/local");
- assertFileLength(new File("target/scp/local/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/local/out2.txt"), data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpNativeOnMixedDirAndFiles() throws Exception {
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
- root.mkdirs();
- new File(root, "local").mkdirs();
- new File(root, "remote").mkdirs();
- assertTrue(root.exists());
-
- new File("target/scp/local/dir").mkdirs();
- writeFile(new File("target/scp/local/out1.txt"), data);
- writeFile(new File("target/scp/local/dir/out2.txt"), data);
- scp.upload("target/scp/local/*", "target/scp/remote/", ScpClient.Option.Recursive);
- assertFileLength(new File("target/scp/remote/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/remote/dir/out2.txt"), data.length(), 5000);
-
- Utils.deleteRecursive(new File("target/scp/local/out1.txt"));
- Utils.deleteRecursive(new File("target/scp/local/dir"));
- scp.download("target/scp/remote/*", "target/scp/local");
- assertFileLength(new File("target/scp/local/out1.txt"), data.length(), 5000);
- assertFalse(new File("target/scp/local/dir/out2.txt").exists());
-
- Utils.deleteRecursive(new File("target/scp/local/out1.txt"));
- scp.download("target/scp/remote/*", "target/scp/local", ScpClient.Option.Recursive);
- assertFileLength(new File("target/scp/local/out1.txt"), data.length(), 5000);
- assertFileLength(new File("target/scp/local/dir/out2.txt"), data.length(), 5000);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testScpNativePreserveAttributes() throws Exception {
- // Ignore this test if running a Windows system
- Assume.assumeFalse("Skip test for Windows", OsUtils.isWin32());
-
- try (SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try {
- try (ClientSession session = client.connect("test", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("test");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- ScpClient scp = createScpClient(session);
-
- String data = "0123456789\n";
-
- File root = new File("target/scp");
- Utils.deleteRecursive(root);
- root.mkdirs();
- new File(root, "local").mkdirs();
- new File(root, "remote").mkdirs();
- assertTrue(root.exists());
-
- new File("target/scp/local/dir").mkdirs();
- long lastMod = new File("target/scp/local/dir").lastModified() - TimeUnit.DAYS.toMillis(1);
-
- writeFile(new File("target/scp/local/out1.txt"), data);
- writeFile(new File("target/scp/local/dir/out2.txt"), data);
- new File("target/scp/local/out1.txt").setLastModified(lastMod);
- new File("target/scp/local/out1.txt").setExecutable(true, true);
- new File("target/scp/local/out1.txt").setWritable(false, false);
- new File("target/scp/local/dir/out2.txt").setLastModified(lastMod);
- scp.upload("target/scp/local/*", "target/scp/remote/", ScpClient.Option.Recursive, ScpClient.Option.PreserveAttributes);
- assertFileLength(new File("target/scp/remote/out1.txt"), data.length(), 5000);
- assertEquals(lastMod, new File("target/scp/remote/out1.txt").lastModified());
- assertFileLength(new File("target/scp/remote/dir/out2.txt"), data.length(), 5000);
- assertEquals(lastMod, new File("target/scp/remote/dir/out2.txt").lastModified());
-
- Utils.deleteRecursive(new File("target/scp/local"));
- new File("target/scp/local").mkdirs();
- scp.download("target/scp/remote/*", "target/scp/local", ScpClient.Option.Recursive, ScpClient.Option.PreserveAttributes);
- assertFileLength(new File("target/scp/local/out1.txt"), data.length(), 5000);
- assertEquals(lastMod, new File("target/scp/local/out1.txt").lastModified());
- assertFileLength(new File("target/scp/local/dir/out2.txt"), data.length(), 5000);
- assertEquals(lastMod, new File("target/scp/local/dir/out2.txt").lastModified());
- }
- } finally {
- client.stop();
- }
- }
- }
-
- private void writeFile(File file, String data) throws IOException {
- FileOutputStream fos = new FileOutputStream(file);
- try {
- fos.write(data.getBytes());
- } finally {
- fos.close();
- }
- }
-
- @Test
- public void testScp() throws Exception {
- session = getJschSession();
- try {
- String data = "0123456789\n";
-
- String unixDir = "target/scp";
- String fileName = "out.txt";
- String unixPath = unixDir + File.separator + fileName;
- File root = new File(unixDir);
- File target = new File(unixPath);
- Utils.deleteRecursive(root);
- root.mkdirs();
- assertTrue(root.exists());
-
- target.delete();
- assertFalse(target.exists());
- sendFile(unixPath, "out.txt", data);
- assertFileLength(target, data.length(), 5000);
-
- target.delete();
- assertFalse(target.exists());
- sendFile(unixDir, "out.txt", data);
- assertFileLength(target, data.length(), 5000);
-
- sendFileError("target", "scp", "0123456789\n");
-
- readFileError(unixDir);
-
- assertEquals(data, readFile(unixPath));
-
- assertEquals(data, readDir(unixDir));
-
- target.delete();
- root.delete();
-
- sendDir("target", "scp", "out.txt", data);
- assertFileLength(target, data.length(), 5000);
- } finally {
- session.disconnect();
- }
- }
-
- @Test
- public void testWithGanymede() throws Exception {
- // begin client config
- final Connection conn = new Connection("localhost", port);
- try {
- conn.connect(null, 5000, 0);
- conn.authenticateWithPassword("sshd", "sshd");
- final SCPClient scp_client = new SCPClient(conn);
- final Properties props = new Properties();
- props.setProperty("test", "test-passed");
- File f = new File("target/scp/gan");
- Utils.deleteRecursive(f);
- f.mkdirs();
- assertTrue(f.exists());
-
- String name = "test.properties";
- scp_client.put(toBytes(props, ""), name, "target/scp/gan");
- assertTrue(new File(f, name).exists());
- assertTrue(new File(f, name).delete());
-
- name = "test2.properties";
- scp_client.put(toBytes(props, ""), name, "target/scp/gan");
- assertTrue(new File(f, name).exists());
- assertTrue(new File(f, name).delete());
-
- assertTrue(f.delete());
- } finally {
- conn.close();
- }
- }
-
- private byte[] toBytes(final Properties properties, final String comments) {
- try {
- final ByteArrayOutputStream baos = new ByteArrayOutputStream();
- properties.store(baos, comments);
- baos.close();
- return baos.toByteArray();
- } catch (final IOException cause) {
- throw new RuntimeException("Failed to output properties to byte[]", cause);
- }
- }
-
- protected void assertFileLength(File file, long length, long timeout) throws Exception {
- boolean ok = false;
- while (timeout > 0) {
- if (file.exists() && file.length() == length) {
- if (!ok) {
- ok = true;
- } else {
- return;
- }
- } else {
- ok = false;
- }
- Thread.sleep(100);
- timeout -= 100;
- }
- assertTrue("File not found: " + file.getAbsolutePath(), file.exists());
- assertEquals("Mismatched file size for " + file.getAbsolutePath(), length, file.length());
- }
-
- protected String readFile(String path) throws Exception {
- ChannelExec c = (ChannelExec) session.openChannel("exec");
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- c.setCommand("scp -f " + path);
- c.connect();
- os.write(0);
- os.flush();
- String header = readLine(is);
- assertEquals("C0644 11 out.txt", header);
- 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(length, buffer.length);
- assertEquals(0, is.read());
- os.write(0);
- os.flush();
-
- c.disconnect();
- return new String(buffer);
- }
-
- protected String readDir(String path) throws Exception {
- ChannelExec c = (ChannelExec) session.openChannel("exec");
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- c.setCommand("scp -r -f " + path);
- c.connect();
- os.write(0);
- os.flush();
- String header = readLine(is);
- assertTrue(header.startsWith("D0755 0 "));
- os.write(0);
- os.flush();
- header = readLine(is);
- assertEquals("C0644 11 out.txt", header);
- 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(length, buffer.length);
- assertEquals(0, is.read());
- os.write(0);
- os.flush();
- header = readLine(is);
- assertEquals("E", header);
- os.write(0);
- os.flush();
-
- c.disconnect();
- return new String(buffer);
- }
-
- protected String readFileError(String path) throws Exception {
- ChannelExec c = (ChannelExec) session.openChannel("exec");
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- c.setCommand("scp -f " + path);
- c.connect();
- os.write(0);
- os.flush();
- assertEquals(2, is.read());
- c.disconnect();
- return null;
- }
-
- protected void sendFile(String path, String name, String data) throws Exception {
- ChannelExec c = (ChannelExec) session.openChannel("exec");
- c.setCommand("scp -t " + path);
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- c.connect();
- assertEquals(0, is.read());
- os.write(("C7777 " + data.length() + " " + name + "\n").getBytes());
- os.flush();
- assertEquals(0, is.read());
- os.write(data.getBytes());
- os.flush();
- assertEquals(0, is.read());
- os.write(0);
- os.flush();
- Thread.sleep(100);
- c.disconnect();
- }
-
- protected void sendFileError(String path, String name, String data) throws Exception {
- ChannelExec c = (ChannelExec) session.openChannel("exec");
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- c.setCommand("scp -t " + path);
- c.connect();
- assertEquals(0, is.read());
- os.write(("C7777 " + data.length() + " " + name + "\n").getBytes());
- os.flush();
- assertEquals(2, is.read());
- c.disconnect();
- }
-
- protected void sendDir(String path, String dirName, String fileName, String data) throws Exception {
- ChannelExec c = (ChannelExec) session.openChannel("exec");
- OutputStream os = c.getOutputStream();
- InputStream is = c.getInputStream();
- c.setCommand("scp -t -r " + path);
- c.connect();
- assertEquals(0, is.read());
- os.write(("D0755 0 " + dirName + "\n").getBytes());
- os.flush();
- assertEquals(0, is.read());
- os.write(("C7777 " + data.length() + " " + fileName + "\n").getBytes());
- os.flush();
- assertEquals(0, is.read());
- os.write(data.getBytes());
- os.flush();
- assertEquals(0, is.read());
- os.write(0);
- os.flush();
- os.write("E\n".getBytes());
- os.flush();
- assertEquals(0, is.read());
- }
-
- private static String readLine(InputStream in) throws IOException {
- ByteArrayOutputStream baos = new ByteArrayOutputStream();
- for (; ; ) {
- int c = in.read();
- if (c == '\n') {
- return baos.toString();
- } else if (c == -1) {
- throw new IOException("End of stream");
- } else {
- baos.write(c);
- }
- }
- }
-
- private ScpClient createScpClient(ClientSession session) {
- final Logger logger = LoggerFactory.getLogger(getClass().getName() + "[" + getCurrentTestName() + "]");
- return session.createScpClient(new ScpTransferEventListener() {
- @Override
- public void startFolderEvent(FileOperation op, Path file, Set<PosixFilePermission> perms) {
- logEvent("starFolderEvent", op, file, false, -1L, perms, null);
- }
-
- @Override
- public void startFileEvent(FileOperation op, Path file, long length, Set<PosixFilePermission> perms) {
- logEvent("startFileEvent", op, file, true, length, perms, null);
-
- }
-
- @Override
- public void endFolderEvent(FileOperation op, Path file, Set<PosixFilePermission> perms, Throwable thrown) {
- logEvent("endFolderEvent", op, file, false, -1L, perms, thrown);
- }
-
- @Override
- public void endFileEvent(FileOperation op, Path file, long length, Set<PosixFilePermission> perms, Throwable thrown) {
- logEvent("endFileEvent", op, file, true, length, perms, thrown);
- }
-
- private void logEvent(String type, FileOperation op, Path path, boolean isFile, long length, Collection<PosixFilePermission> perms, Throwable t) {
- StringBuilder sb = new StringBuilder(Byte.MAX_VALUE);
- sb.append('\t').append(type)
- .append('[').append(op).append(']')
- .append(' ').append(isFile ? "File" : "Directory").append('=').append(path)
- .append(' ').append("length=").append(length)
- .append(' ').append("perms=").append(perms)
- ;
- if (t != null) {
- sb.append(' ').append("ERROR=").append(t.getClass().getSimpleName()).append(": ").append(t.getMessage());
- }
- logger.info(sb.toString());
- }
- });
- }
-}
[2/3] mina-sshd git commit: [SSHD-471] Auto-detect 'target' folder
location and use it in the tests
Posted by lg...@apache.org.
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java b/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
deleted file mode 100644
index 609d5fb..0000000
--- a/sshd-core/src/test/java/org/apache/sshd/SftpFileSystemTest.java
+++ /dev/null
@@ -1,218 +0,0 @@
-/*
- * 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;
-
-import java.io.File;
-import java.io.IOException;
-import java.net.URI;
-import java.nio.channels.FileChannel;
-import java.nio.channels.FileLock;
-import java.nio.channels.OverlappingFileLockException;
-import java.nio.file.DirectoryStream;
-import java.nio.file.FileAlreadyExistsException;
-import java.nio.file.FileSystem;
-import java.nio.file.FileSystems;
-import java.nio.file.Files;
-import java.nio.file.LinkOption;
-import java.nio.file.NoSuchFileException;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardCopyOption;
-import java.nio.file.attribute.FileTime;
-import java.nio.file.attribute.GroupPrincipal;
-import java.nio.file.attribute.PosixFilePermissions;
-import java.nio.file.attribute.UserPrincipalLookupService;
-import java.nio.file.attribute.UserPrincipalNotFoundException;
-import java.util.Arrays;
-import java.util.Map;
-
-import org.apache.sshd.common.NamedFactory;
-import org.apache.sshd.common.util.OsUtils;
-import org.apache.sshd.server.Command;
-import org.apache.sshd.server.command.ScpCommandFactory;
-import org.apache.sshd.server.sftp.SftpSubsystemFactory;
-import org.apache.sshd.util.BaseTestSupport;
-import org.apache.sshd.util.BogusPasswordAuthenticator;
-import org.apache.sshd.util.EchoShellFactory;
-import org.apache.sshd.util.Utils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-
-public class SftpFileSystemTest extends BaseTestSupport {
-
- private SshServer sshd;
- private int port;
-
- @Before
- public void setUp() throws Exception {
- sshd = SshServer.setUpDefaultServer();
- sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
- sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
- sshd.setCommandFactory(new ScpCommandFactory());
- sshd.setShellFactory(new EchoShellFactory());
- sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
- sshd.start();
- port = sshd.getPort();
- }
-
- @After
- public void tearDown() throws Exception {
- sshd.stop(true);
- }
-
- @Test
- public void testFileSystem() throws Exception {
- Utils.deleteRecursive(new File("target/sftp"));
-
- String uri = "sftp://x:x@localhost:" + port + "/";
-
- try(FileSystem fs = FileSystems.newFileSystem(URI.create(uri), null)) {
- Iterable<Path> rootDirs = fs.getRootDirectories();
- for (Path root : rootDirs) {
- try (DirectoryStream<Path> ds = Files.newDirectoryStream(root)) {
- for (Path child : ds) {
- System.out.println(child);
- }
- } catch(IOException | RuntimeException e) {
- // TODO on Windows one might get share problems for *.sys files
- // e.g. "C:\hiberfil.sys: The process cannot access the file because it is being used by another process"
- // for now, Windows is less of a target so we are lenient with it
- if (OsUtils.isWin32()) {
- System.err.println(e.getClass().getSimpleName() + " while accessing children of root=" + root + ": " + e.getMessage());
- } else {
- throw e;
- }
- }
- }
-
- Path current = fs.getPath(".").toRealPath();
- Path file = fs.getPath("target/sftp/client/test.txt");
- Files.createDirectories(file.getParent());
- Files.write(file, "Hello world\n".getBytes());
- String buf = new String(Files.readAllBytes(file));
- assertEquals("Hello world\n", buf);
-
- Path file2 = fs.getPath("target/sftp/client/test2.txt");
- Path file3 = fs.getPath("target/sftp/client/test3.txt");
- try {
- Files.move(file2, file3);
- fail("Expected an IOException");
- } catch (NoSuchFileException e) {
- // expected
- }
- Files.write(file2, "h".getBytes());
- try {
- Files.move(file, file2);
- fail("Expected an IOException");
- } catch (FileAlreadyExistsException e) {
- // expected
- }
- Files.move(file, file2, StandardCopyOption.REPLACE_EXISTING);
- Files.move(file2, file);
-
- Map<String, Object> attrs = Files.readAttributes(file, "*");
- System.out.println(attrs);
-
- // TODO: symbolic links only work for absolute files
- // Path link = fs.getPath("target/sftp/client/test2.txt");
- // Files.createSymbolicLink(link, link.relativize(file));
- // assertTrue(Files.isSymbolicLink(link));
- // assertEquals("test.txt", Files.readSymbolicLink(link).toString());
-
- // TODO there are many issues with Windows and symbolic links - for now they are of a lesser interest
- if (OsUtils.isUNIX()) {
- Path link = fs.getPath("target/sftp/client/test2.txt");
- Files.createSymbolicLink(link, link.getParent().relativize(file));
- assertTrue("Not a symbolic link: " + link, Files.isSymbolicLink(link));
- assertEquals("test.txt", Files.readSymbolicLink(link).toString());
- Files.delete(link);
- }
-
- attrs = Files.readAttributes(file, "*", LinkOption.NOFOLLOW_LINKS);
- System.out.println(attrs);
-
- buf = new String(Files.readAllBytes(file));
- assertEquals("Hello world\n", buf);
-
- try (FileChannel channel = FileChannel.open(file)) {
- try (FileLock lock = channel.lock()) {
- System.out.println("Locked " + lock.toString());
-
- try (FileChannel channel2 = FileChannel.open(file)) {
- try (FileLock lock2 = channel2.lock()) {
- System.out.println("Locked " + lock2.toString());
- fail("Expected an exception");
- } catch (OverlappingFileLockException e) {
- // expected
- }
- }
-
- }
- }
-
- Files.delete(file);
- }
- }
-
- @Test
- public void testAttributes() throws Exception {
- Utils.deleteRecursive(new File("target/sftp"));
-
- try (FileSystem fs = FileSystems.newFileSystem(URI.create("sftp://x:x@localhost:" + port + "/"), null)) {
- Path file = fs.getPath("target/sftp/client/test.txt");
- Files.createDirectories(file.getParent());
- Files.write(file, "Hello world\n".getBytes());
-
- 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));
-
- FileSystem fileSystem = file.getFileSystem();
- try {
- UserPrincipalLookupService userLookupService = fileSystem.getUserPrincipalLookupService();
- GroupPrincipal group = userLookupService.lookupPrincipalByGroupName("everyone");
- Files.setAttribute(file, "posix:group", group);
- } catch (UserPrincipalNotFoundException e) {
- // Also, according to the Javadoc:
- // "Where an implementation does not support any notion of
- // group then this method always throws UserPrincipalNotFoundException."
- // Therefore we are lenient with this exception for Windows
- if (OsUtils.isWin32()) {
- System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
- } else {
- throw e;
- }
- }
- }
- }
-
- @Test
- public void testRootFileSystem() throws Exception {
- Path rootNative = Paths.get("target/root").toAbsolutePath();
- Utils.deleteRecursive(rootNative.toFile());
- Files.createDirectories(rootNative);
-
- FileSystem fs = FileSystems.newFileSystem(URI.create("root:" + rootNative.toUri().toString() + "!/"), null);
- Files.createDirectories(fs.getPath("test/foo"));
- }
-}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/SftpTest.java b/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
deleted file mode 100644
index b2b0cbd..0000000
--- a/sshd-core/src/test/java/org/apache/sshd/SftpTest.java
+++ /dev/null
@@ -1,606 +0,0 @@
-/*
- * 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;
-
-import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_FILE_ALREADY_EXISTS;
-import static org.apache.sshd.common.sftp.SftpConstants.SSH_FX_NO_SUCH_FILE;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IRUSR;
-import static org.apache.sshd.common.sftp.SftpConstants.S_IWUSR;
-
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.File;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.URI;
-import java.util.Arrays;
-import java.util.EnumSet;
-import java.util.Vector;
-import java.util.concurrent.TimeUnit;
-
-import org.apache.sshd.client.SftpClient;
-import org.apache.sshd.common.NamedFactory;
-import org.apache.sshd.common.util.OsUtils;
-import org.apache.sshd.common.util.buffer.ByteArrayBuffer;
-import org.apache.sshd.server.Command;
-import org.apache.sshd.server.command.ScpCommandFactory;
-import org.apache.sshd.server.sftp.SftpSubsystemFactory;
-import org.apache.sshd.util.BaseTestSupport;
-import org.apache.sshd.util.BogusPasswordAuthenticator;
-import org.apache.sshd.util.EchoShellFactory;
-import org.apache.sshd.util.JSchLogger;
-import org.apache.sshd.util.SimpleUserInfo;
-import org.apache.sshd.util.Utils;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-
-import com.jcraft.jsch.ChannelSftp;
-import com.jcraft.jsch.JSch;
-import com.jcraft.jsch.SftpException;
-
-public class SftpTest extends BaseTestSupport {
-
- private SshServer sshd;
- private int port;
- private com.jcraft.jsch.Session session;
-
- @Before
- public void setUp() throws Exception {
- sshd = SshServer.setUpDefaultServer();
- sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
- sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
- sshd.setCommandFactory(new ScpCommandFactory());
- sshd.setShellFactory(new EchoShellFactory());
- sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
- sshd.start();
- port = sshd.getPort();
-
- JSchLogger.init();
- JSch sch = new JSch();
- session = sch.getSession("sshd", "localhost", port);
- session.setUserInfo(new SimpleUserInfo("sshd"));
- session.connect();
- }
-
- @After
- public void tearDown() throws Exception {
- session.disconnect();
- sshd.stop(true);
- }
-
- @Test
- @Ignore
- public void testExternal() throws Exception {
- System.out.println("SFTP subsystem available on port " + port);
- Thread.sleep(5 * 60000);
- }
-
- @Test
- public void testOpen() throws Exception {
- SshClient client = SshClient.setUpDefaultClient();
- client.start();
-
- try (ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("x");
- session.auth().verify();
-
- String file = "target/sftp/client/testOpen.txt";
- File javaFile = new File(file);
-
- assertHierarchyTargetFolderExists(javaFile.getParentFile());
- javaFile.createNewFile();
- javaFile.setWritable(false, false);
- javaFile.setReadable(false, false);
-
- try (SftpClient sftp = session.createSftpClient()) {
- SftpClient.Handle h;
-
- boolean isWindows = OsUtils.isWin32();
-
- try {
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.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", isWindows);
- sftp.close(h);
- } catch (IOException e) {
- if (isWindows) {
- throw e;
- }
- }
-
- try {
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
- fail("Empty write should have failed");
- } catch (IOException e) {
- // ok
- }
-
- try {
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate));
- // NOTE: on Windows files are always readable
- assertTrue("Empty truncate should have failed", isWindows);
- sftp.close(h);
- } 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);
- assertEquals("Mismatched permissions - 0x" + Integer.toHexString(perms), 0, (perms & permsMask));
-
- javaFile.setWritable(true, false);
-
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Truncate, SftpClient.OpenMode.Write));
- sftp.close(h);
-
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
- byte[] d = "0123456789\n".getBytes();
- sftp.write(h, 0, d, 0, d.length);
- sftp.write(h, d.length, d, 0, d.length);
- sftp.close(h);
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
- sftp.write(h, d.length * 2, d, 0, d.length);
- sftp.close(h);
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Write));
- sftp.write(h, 3, "-".getBytes(), 0, 1);
- sftp.close(h);
-
- try {
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Read));
- // NOTE: on Windows files are always readable
- assertTrue("Data read should have failed", isWindows);
- sftp.close(h);
- } catch (IOException e) {
- if (isWindows) {
- throw e;
- }
- }
-
- javaFile.setReadable(true, false);
-
- h = sftp.open(file, EnumSet.of(SftpClient.OpenMode.Read));
- byte[] buf = new byte[3];
- int l = sftp.read(h, 2l, buf, 0, 3);
- assertEquals("Mismatched read data", "2-4", new String(buf, 0, l));
- sftp.close(h);
- }
- } finally {
- client.stop();
- }
- }
-
- @Test
- public void testClient() throws Exception {
- SshClient client = SshClient.setUpDefaultClient();
- client.start();
- try (ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("x");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- Utils.deleteRecursive(new File("target/sftp"));
- new File("target/sftp").mkdirs();
- new File("target/sftp/client/test.txt").delete();
- new File("target/sftp/client").delete();
-
- try (SftpClient sftp = session.createSftpClient()) {
- sftp.mkdir("target/sftp/client");
-
- SftpClient.Handle h = sftp.open("target/sftp/client/test.txt", EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
- byte[] d = "0123456789\n".getBytes();
- sftp.write(h, 0, d, 0, d.length);
- sftp.write(h, d.length, d, 0, d.length);
-
- SftpClient.Attributes attrs = sftp.stat(h);
- assertNotNull("No handle attributes", attrs);
-
- sftp.close(h);
-
- h = sftp.openDir("target/sftp/client");
- SftpClient.DirEntry[] dir = sftp.readDir(h);
- assertNotNull("No dir entries", dir);
- assertEquals("Mismatced number of dir entries", 1, dir.length);
- assertNull("Unexpected entry read", sftp.readDir(h));
- sftp.close(h);
-
- sftp.remove("target/sftp/client/test.txt");
-
- byte[] workBuf = new byte[1024 * 128];
- try (OutputStream os = sftp.write("target/sftp/client/test.txt")) {
- os.write(workBuf);
- }
-
- try (InputStream is = sftp.read("target/sftp/client/test.txt")) {
- int readLen = is.read(workBuf);
- assertEquals("Mismatched read data length", workBuf.length, readLen);
-
- int i = is.read();
- assertEquals("Unexpected read past EOF", -1, i);
- }
-
- SftpClient.Attributes attributes = sftp.stat("target/sftp/client/test.txt");
- assertTrue("Test file not detected as regular", attributes.isRegularFile());
-
- attributes = sftp.stat("target/sftp/client");
- assertTrue("Test directory not reported as such", attributes.isDirectory());
-
- int nb = 0;
- for (SftpClient.DirEntry entry : sftp.readDir("target/sftp/client")) {
- assertNotNull("Unexpected null entry", entry);
- nb++;
- }
- assertEquals("Mismatched read dir entries", 1, nb);
-
- sftp.remove("target/sftp/client/test.txt");
-
- sftp.rmdir("target/sftp/client/");
- }
- } finally {
- client.stop();
- }
- }
-
- /**
- * 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()) {
- client.start();
-
- try(ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("x");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- Utils.deleteRecursive(new File("target/sftp"));
- new File("target/sftp").mkdirs();
- new File("target/sftp/client").delete();
-
- try(SftpClient sftp = session.createSftpClient()) {
- sftp.mkdir("target/sftp/client");
-
- uploadAndVerifyFile(sftp, 0, "emptyFile.txt");
- uploadAndVerifyFile(sftp, 1000, "smallFile.txt");
- uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN - 1, "bufferMaxLenMinusOneFile.txt");
- uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN, "bufferMaxLenFile.txt");
- // were chunking not implemented, these would fail. these sizes should invoke our internal chunking mechanism
- uploadAndVerifyFile(sftp, ByteArrayBuffer.MAX_LEN + 1, "bufferMaxLenPlusOneFile.txt");
- uploadAndVerifyFile(sftp, (int)(1.5 * ByteArrayBuffer.MAX_LEN), "1point5BufferMaxLenFile.txt");
- uploadAndVerifyFile(sftp, (2 * ByteArrayBuffer.MAX_LEN) - 1, "2TimesBufferMaxLenMinusOneFile.txt");
- uploadAndVerifyFile(sftp, 2 * ByteArrayBuffer.MAX_LEN, "2TimesBufferMaxLenFile.txt");
- uploadAndVerifyFile(sftp, (2 * ByteArrayBuffer.MAX_LEN) + 1, "2TimesBufferMaxLenPlusOneFile.txt");
- uploadAndVerifyFile(sftp, 200000, "largerFile.txt");
-
- // test erroneous calls that check for negative values
- testInvalidParams(sftp);
-
- // cleanup
- sftp.rmdir("target/sftp/client");
- }
- } finally {
- client.stop();
- }
- }
- }
-
- private void testInvalidParams(SftpClient sftp) throws Exception {
- // generate random file and upload it
- final String filePath = "target/sftp/client/invalid";
- SftpClient.Handle handle = sftp.open(filePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
- String randomData = randomString(5);
- try {
- sftp.write(handle, -1, randomData.getBytes(), 0, 0);
- fail("should not have been able to write file with invalid file offset");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- sftp.write(handle, 0, randomData.getBytes(), -1, 0);
- fail("should not have been able to write file with invalid source offset");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- sftp.write(handle, 0, randomData.getBytes(), 0, -1);
- fail("should not have been able to write file with invalid length");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- sftp.write(handle, 0, randomData.getBytes(), 0, randomData.length() + 1);
- fail("should not have been able to write file with length bigger than array itself (no offset)");
- } catch (IllegalArgumentException e) {
- // expected
- }
- try {
- sftp.write(handle, 0, randomData.getBytes(), randomData.length(), 1);
- fail("should not have been able to write file with length bigger than array itself (with offset)");
- } catch (IllegalArgumentException e) {
- // expected
- }
-
- // cleanup
- sftp.close(handle);
- sftp.remove(filePath);
- assertFalse("file should not be there", new File(filePath).exists());
- }
-
- private void uploadAndVerifyFile(SftpClient sftp, int size, String filename) throws Exception {
- // generate random file and upload it
- final String filePath = "target/sftp/client/" + filename;
- SftpClient.Handle handle = sftp.open(filePath, EnumSet.of(SftpClient.OpenMode.Write, SftpClient.OpenMode.Create));
- String randomData = randomString(size);
- sftp.write(handle, 0, randomData.getBytes(), 0, randomData.length());
- sftp.close(handle);
-
- // verify results
- File resultFile = new File(filePath);
- assertTrue("file should exist on disk", resultFile.exists());
- assertTrue("file contents should match", randomData.equals(readFile(filePath)));
-
- // cleanup
- sftp.remove(filePath);
- assertFalse("file should have been removed", resultFile.exists());
- }
-
- @Test
- public void testSftp() throws Exception {
- String d = "0123456789\n";
-
- File root = new File("target/sftp");
- File target = new File("target/sftp/out.txt");
- Utils.deleteRecursive(root);
- root.mkdirs();
- assertTrue(root.exists());
-
- for (int j = 10; j <= 10; j++) {
- String data = "";
- for (int i = 0; i < j; i++) {
- data = data + d;
- }
-
- target.delete();
- assertFalse(target.exists());
- sendFile("target/sftp/out.txt", data);
- assertFileLength(target, data.length(), 5000);
-
- target.delete();
- assertFalse(target.exists());
- }
- root.delete();
- }
-
- @Test
- public void testReadWriteWithOffset() throws Exception {
- File root = new File("target/sftp");
- Utils.deleteRecursive(root);
- assertHierarchyTargetFolderExists(root);
-
- String unixPath = "target/sftp/out.txt";
- File target = new File(unixPath);
-
- ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
- c.connect();
- try {
- c.put(new ByteArrayInputStream("0123456789".getBytes()), unixPath);
-
- assertTrue("Target not created after initial write: " + target.getAbsolutePath(), target.exists());
- assertEquals("0123456789", readFile(unixPath));
-
- try(OutputStream os = c.put(unixPath, null, ChannelSftp.APPEND, -5)) {
- os.write("a".getBytes());
- }
- } finally {
- c.disconnect();
- }
-
- assertTrue("Target not created after data update: " + target.getAbsolutePath(), target.exists());
- assertEquals("Mismatched file data", "01234a6789", readFile(unixPath));
-
- assertTrue("Failed to delete " + target.getAbsolutePath(), target.delete());
- assertFalse("Target not deleted: " + target.getAbsolutePath(), target.exists());
- root.delete();
- }
-
- @Test
- public void testReadDir() throws Exception {
- ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
- c.connect();
- try {
- URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
- URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
- String path = new File(base.relativize(url).getPath()).getParent() + "/";
- path = path.replace('\\', '/');
- Vector<?> res = c.ls(path);
- for (Object f : res) {
- System.out.println(f.toString());
- }
- } finally {
- c.disconnect();
- }
- }
-
- @Test
- public void testRealPath() throws Exception {
- ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
- c.connect();
-
- try {
- URI url = getClass().getClassLoader().getResource(SshClient.class.getName().replace('.', '/') + ".class").toURI();
- URI base = new File(System.getProperty("user.dir")).getAbsoluteFile().toURI();
- String path = new File(base.relativize(url).getPath()).getParent() + "/";
- path = path.replace('\\', '/');
- String real = c.realpath(path);
- System.out.println(real);
- try {
- real = c.realpath(path + "/foobar");
- System.out.println(real);
- fail("Expected SftpException");
- } catch (SftpException e) {
- // ok
- }
- } finally {
- c.disconnect();
- }
- }
-
- @Test
- public void testRename() throws Exception {
- try(SshClient client = SshClient.setUpDefaultClient()) {
- client.start();
-
- try(ClientSession session = client.connect("x", "localhost", port).await().getSession()) {
- session.addPasswordIdentity("x");
- session.auth().verify(5L, TimeUnit.SECONDS);
-
- Utils.deleteRecursive(new File("target/sftp"));
- new File("target/sftp").mkdirs();
- new File("target/sftp/client").delete();
-
- try(SftpClient sftp = session.createSftpClient()) {
- try (OutputStream os = sftp.write("target/sftp/test.txt")) {
- os.write("Hello world!\n".getBytes());
- }
-
- try {
- sftp.rename("target/sftp/test2.txt", "target/sftp/test3.txt");
- fail("Expected an SftpException");
- } catch (org.apache.sshd.client.SftpException e) {
- assertEquals(SSH_FX_NO_SUCH_FILE, e.getStatus());
- }
-
- try (OutputStream os = sftp.write("target/sftp/test2.txt")) {
- os.write("H".getBytes());
- }
-
- try {
- sftp.rename("target/sftp/test.txt", "target/sftp/test2.txt");
- fail("Expected an SftpException");
- } catch (org.apache.sshd.client.SftpException e) {
- assertEquals(SSH_FX_FILE_ALREADY_EXISTS, e.getStatus());
- }
- sftp.rename("target/sftp/test.txt", "target/sftp/test2.txt", SftpClient.CopyMode.Overwrite);
- }
- } finally {
- client.stop();
- }
- }
- }
-
- @Test
- public void testCreateSymbolicLink() throws Exception {
- // Do not execute on windows as the file system does not support symlinks
- if (System.getProperty("os.name").toLowerCase().contains("win")) {
- return;
- }
-
- File root = new File("target/sftp");
- String unixPath = "target/sftp/out.txt";
- String linkUnixPath = "target/sftp/link.txt";
- File target = new File(unixPath);
- File link = new File(linkUnixPath);
- Utils.deleteRecursive(root);
- root.mkdirs();
- assertTrue(root.exists());
-
- ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
- c.connect();
- try {
- c.put(new ByteArrayInputStream("0123456789".getBytes()), unixPath);
-
- assertTrue(target.exists());
- assertEquals("0123456789", readFile(unixPath));
-
- c.symlink(unixPath, linkUnixPath);
-
- assertTrue(link.exists());
- assertEquals("0123456789", readFile(linkUnixPath));
-
- String str1 = c.readlink(linkUnixPath);
- String str2 = c.realpath(unixPath);
- assertEquals(str1, str2);
- } finally {
- c.disconnect();
- }
- }
-
- protected void assertFileLength(File file, long length, long timeout) throws Exception {
- boolean ok = false;
- while (timeout > 0) {
- if (file.exists() && file.length() == length) {
- if (!ok) {
- ok = true;
- } else {
- return;
- }
- } else {
- ok = false;
- }
- Thread.sleep(100);
- timeout -= 100;
- }
- assertTrue(file.exists());
- assertEquals(length, file.length());
- }
-
- protected String readFile(String path) throws Exception {
- ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
- c.connect();
-
- try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
- InputStream is = c.get(path)) {
-
- byte[] buffer = new byte[256];
- int count;
- while (-1 != (count = is.read(buffer))) {
- bos.write(buffer, 0, count);
- }
-
- return bos.toString();
- } finally {
- c.disconnect();
- }
- }
-
- protected void sendFile(String path, String data) throws Exception {
- ChannelSftp c = (ChannelSftp) session.openChannel("sftp");
- c.connect();
- try {
- c.put(new ByteArrayInputStream(data.getBytes()), path);
- } finally {
- c.disconnect();
- }
- }
-
- private String randomString(int size) {
- StringBuilder sb = new StringBuilder(size);
- for (int i = 0; i < size; i++) {
- sb.append((char) ((i % 10) + '0'));
- }
- return sb.toString();
- }
-
-}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/client/ScpTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/ScpTest.java b/sshd-core/src/test/java/org/apache/sshd/client/ScpTest.java
new file mode 100644
index 0000000..2fb871a
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/ScpTest.java
@@ -0,0 +1,935 @@
+/*
+ * 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.client;
+
+import java.io.ByteArrayOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.nio.channels.FileChannel;
+import java.nio.file.FileSystem;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.StandardOpenOption;
+import java.nio.file.attribute.PosixFilePermission;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+
+import org.apache.sshd.ClientSession;
+import org.apache.sshd.SshClient;
+import org.apache.sshd.SshServer;
+import org.apache.sshd.common.Session;
+import org.apache.sshd.common.file.FileSystemFactory;
+import org.apache.sshd.common.file.root.RootedFileSystemProvider;
+import org.apache.sshd.common.scp.ScpTransferEventListener;
+import org.apache.sshd.common.util.OsUtils;
+import org.apache.sshd.server.command.ScpCommandFactory;
+import org.apache.sshd.util.BaseTestSupport;
+import org.apache.sshd.util.BogusPasswordAuthenticator;
+import org.apache.sshd.util.EchoShellFactory;
+import org.apache.sshd.util.JSchLogger;
+import org.apache.sshd.util.SimpleUserInfo;
+import org.apache.sshd.util.Utils;
+import org.junit.After;
+import org.junit.Assume;
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import ch.ethz.ssh2.Connection;
+import ch.ethz.ssh2.SCPClient;
+
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+
+/**
+ * Test for SCP support.
+ *
+ * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a>
+ */
+public class ScpTest extends BaseTestSupport {
+
+ private SshServer sshd;
+ private int port;
+ private com.jcraft.jsch.Session session;
+ private final FileSystemFactory fileSystemFactory;
+
+ public ScpTest() throws IOException {
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String,Object>emptyMap());
+ fileSystemFactory = new FileSystemFactory() {
+ @Override
+ public FileSystem createFileSystem(Session session) throws IOException {
+ return fileSystem;
+ }
+ };
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ sshd = SshServer.setUpDefaultServer();
+ sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
+ sshd.setCommandFactory(new ScpCommandFactory());
+ sshd.setShellFactory(new EchoShellFactory());
+ sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+ sshd.setFileSystemFactory(fileSystemFactory);
+ sshd.start();
+ port = sshd.getPort();
+ }
+
+ protected com.jcraft.jsch.Session getJschSession() throws JSchException {
+ JSchLogger.init();
+ JSch sch = new JSch();
+ session = sch.getSession("sshd", "localhost", port);
+ session.setUserInfo(new SimpleUserInfo("sshd"));
+ session.connect();
+ return session;
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (session != null) {
+ session.disconnect();
+ }
+
+ if (sshd != null) {
+ sshd.stop(true);
+ }
+ }
+
+ @Test
+ @Ignore
+ public void testExternal() throws Exception {
+ System.out.println("Scp available on port " + port);
+ Thread.sleep(5 * 60000);
+ }
+
+ @Test
+ public void testUploadAbsoluteDriveLetter() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try {
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path localFile = localDir.resolve(getCurrentTestName() + "-1.txt");
+ byte[] data = writeFile(localFile, (getCurrentTestName() + "\n"));
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ Path remoteFile = remoteDir.resolve(localFile.getFileName().toString());
+ String localPath = localFile.toString();
+ String remotePath = Utils.resolveRelativeRemotePath(parentPath, remoteFile);
+ scp.upload(localPath, remotePath);
+ assertFileLength(remoteFile, data.length, 5000);
+
+ Path secondRemote = remoteDir.resolve(getCurrentTestName() + "-2.txt");
+ String secondPath = Utils.resolveRelativeRemotePath(parentPath, secondRemote);
+ scp.upload(localPath, secondPath);
+ assertFileLength(secondRemote, data.length, 5000);
+
+ Path pathRemote = remoteDir.resolve(getCurrentTestName() + "-path.txt");
+ String pathPath = Utils.resolveRelativeRemotePath(parentPath, pathRemote);
+ scp.upload(localFile, pathPath);
+ assertFileLength(pathRemote, data.length, 5000);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpUploadOverwrite() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try {
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ String data = getCurrentTestName() + "\n";
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path localFile = localDir.resolve(getCurrentTestName() + ".txt");
+ writeFile(localFile, data);
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ Path remoteFile = remoteDir.resolve(localFile.getFileName());
+ writeFile(remoteFile, data + data);
+
+ String remotePath = Utils.resolveRelativeRemotePath(parentPath, remoteFile);
+ scp.upload(localFile.toString(), remotePath);
+ assertFileLength(remoteFile, data.length(), 5000);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpUploadZeroLengthFile() throws Exception {
+ Path targetPath = detectTargetFolder().toPath();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ Path zeroLocal = localDir.resolve(getCurrentTestName());
+
+ try (FileChannel fch = FileChannel.open(zeroLocal, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
+ if (fch.size() > 0L) {
+ fch.truncate(0L);
+ }
+ }
+ assertEquals("Non-zero size for local file=" + zeroLocal, 0L, Files.size(zeroLocal));
+
+ Path zeroRemote = remoteDir.resolve(zeroLocal.getFileName());
+ if (Files.exists(zeroRemote)) {
+ Files.delete(zeroRemote);
+ }
+
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ try {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ String remotePath = Utils.resolveRelativeRemotePath(targetPath.getParent(), zeroRemote);
+ scp.upload(zeroLocal.toString(), remotePath);
+ assertFileLength(zeroRemote, 0L, TimeUnit.SECONDS.toMillis(5L));
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpDownloadZeroLengthFile() throws Exception {
+ Path targetPath = detectTargetFolder().toPath();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ Path zeroLocal = localDir.resolve(getCurrentTestName());
+ if (Files.exists(zeroLocal)) {
+ Files.delete(zeroLocal);
+ }
+
+ Path zeroRemote = remoteDir.resolve(zeroLocal.getFileName());
+ try (FileChannel fch = FileChannel.open(zeroRemote, StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING)) {
+ if (fch.size() > 0L) {
+ fch.truncate(0L);
+ }
+ }
+ assertEquals("Non-zero size for remote file=" + zeroRemote, 0L, Files.size(zeroRemote));
+
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ try {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ String remotePath = Utils.resolveRelativeRemotePath(targetPath.getParent(), zeroRemote);
+ scp.download(remotePath, zeroLocal.toString());
+ assertFileLength(zeroLocal, 0L, TimeUnit.SECONDS.toMillis(5L));
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpNativeOnSingleFile() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try {
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ String data = getCurrentTestName() + "\n";
+
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path localOutFile = localDir.resolve(getCurrentTestName() + "-1.txt");
+ writeFile(localOutFile, data);
+
+ Path remoteDir = scpRoot.resolve("remote");
+ Path remoteOutFile = remoteDir.resolve(localOutFile.getFileName());
+ 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) {
+ // ok
+ }
+
+ Files.createDirectories(remoteDir);
+ scp.upload(localOutPath, remoteOutPath);
+ assertFileLength(remoteOutFile, data.length(), 5000);
+
+ Path secondLocal = localDir.resolve(localOutFile.getFileName());
+ scp.download(remoteOutPath, Utils.resolveRelativeRemotePath(parentPath, secondLocal));
+ assertFileLength(secondLocal, data.length(), 5000);
+
+ Path localPath = localDir.resolve(getCurrentTestName() + "-path.txt");
+ scp.download(remoteOutPath, Utils.resolveRelativeRemotePath(parentPath, localPath));
+ assertFileLength(localPath, data.length(), 5000);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpNativeOnMultipleFiles() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try {
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path local1 = localDir.resolve(getCurrentTestName() + "-1.txt");
+ byte[] data = writeFile(local1, getCurrentTestName() + "\n");
+
+ Path local2 = localDir.resolve(getCurrentTestName() + "-2.txt");
+ Files.write(local2, data);
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ Path remote1 = remoteDir.resolve(local1.getFileName());
+ String remote1Path = Utils.resolveRelativeRemotePath(parentPath, remote1);
+ 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);
+ fail("Unexpected upload success to existing remote file: " + remote1Path);
+ } catch (IOException e) {
+ // Ok
+ }
+
+ Path remoteSubDir = assertHierarchyTargetFolderExists(remoteDir.resolve("dir"));
+ scp.upload(locals, Utils.resolveRelativeRemotePath(parentPath, remoteSubDir));
+
+ Path remoteSub1 = remoteSubDir.resolve(local1.getFileName());
+ assertFileLength(remoteSub1, data.length, 5000);
+
+ Path remoteSub2 = remoteSubDir.resolve(local2.getFileName());
+ assertFileLength(remoteSub2, data.length, 5000);
+
+ String[] remotes = {
+ Utils.resolveRelativeRemotePath(parentPath, remoteSub1),
+ Utils.resolveRelativeRemotePath(parentPath, remoteSub2),
+ };
+
+ try {
+ scp.download(remotes, Utils.resolveRelativeRemotePath(parentPath, local1));
+ fail("Unexpected download success to existing local file: " + local1);
+ } catch (IOException e) {
+ // Ok
+ }
+
+ Path localSubDir = localDir.resolve("dir");
+ try {
+ scp.download(remotes, localSubDir);
+ fail("Unexpected download success to non-existing folder: " + localSubDir);
+ } catch (IOException e) {
+ // Ok
+ }
+
+ Files.createDirectories(localSubDir);
+ scp.download(remotes, localSubDir);
+
+ assertFileLength(localSubDir.resolve(remoteSub1.getFileName()), data.length, 5000);
+ assertFileLength(localSubDir.resolve(remoteSub2.getFileName()), data.length, 5000);
+ }
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpNativeOnRecursiveDirs() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = scpRoot.resolve("local");
+ Path localSubDir = assertHierarchyTargetFolderExists(localDir.resolve("dir"));
+ Path localSub1 = localSubDir.resolve(getCurrentTestName() + "-1.txt");
+ byte[] data = writeFile(localSub1, getCurrentTestName() + "\n");
+ Path localSub2 = localSubDir.resolve(getCurrentTestName() + "-2.txt");
+ Files.write(localSub2, data);
+
+ 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, 5000);
+ assertFileLength(remoteSubDir.resolve(localSub2.getFileName()), data.length, 5000);
+
+ Utils.deleteRecursive(localSubDir);
+
+ scp.download(Utils.resolveRelativeRemotePath(parentPath, remoteSubDir), localDir, ScpClient.Option.Recursive);
+ assertFileLength(localSub1, data.length, 5000);
+ assertFileLength(localSub2, data.length, 5000);
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpNativeOnDirWithPattern() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = assertHierarchyTargetFolderExists(scpRoot.resolve("local"));
+ Path local1 = localDir.resolve(getCurrentTestName() + "-1.txt");
+ byte[] data = writeFile(local1, getCurrentTestName() + "\n");
+ Path local2 = localDir.resolve(getCurrentTestName() + "-2.txt");
+ Files.write(local2, data);
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ String remotePath = Utils.resolveRelativeRemotePath(parentPath, remoteDir);
+ scp.upload(localDir.toString() + File.separator + "*", remotePath);
+ assertFileLength(remoteDir.resolve(local1.getFileName()), data.length, 5000);
+ assertFileLength(remoteDir.resolve(local2.getFileName()), data.length, 5000);
+
+ Files.delete(local1);
+ Files.delete(local2);
+ scp.download(remotePath + "/*", localDir);
+ assertFileLength(local1, data.length, 5000);
+ assertFileLength(local2, data.length, 5000);
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpNativeOnMixedDirAndFiles() throws Exception {
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = scpRoot.resolve("local");
+ Path localSubDir = assertHierarchyTargetFolderExists(localDir.resolve("dir"));
+ Path local1 = localDir.resolve(getCurrentTestName() + "-1.txt");
+ byte[] data = writeFile(local1, getCurrentTestName() + "\n");
+ Path localSub2 = localSubDir.resolve(getCurrentTestName() + "-2.txt");
+ Files.write(localSub2, data);
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ String remotePath = Utils.resolveRelativeRemotePath(parentPath, remoteDir);
+ scp.upload(localDir.toString() + File.separator + "*", remotePath, ScpClient.Option.Recursive);
+ assertFileLength(remoteDir.resolve(local1.getFileName()), data.length, 5000);
+
+ Path remoteSubDir = remoteDir.resolve(localSubDir.getFileName());
+ assertFileLength(remoteSubDir.resolve(localSub2.getFileName()), data.length, 5000);
+
+ Files.delete(local1);
+ Utils.deleteRecursive(localSubDir);
+
+ scp.download(remotePath + "/*", localDir);
+ assertFileLength(local1, data.length, 5000);
+ assertFalse("Unexpected recursive local file: " + localSub2, Files.exists(localSub2));
+
+ Files.delete(local1);
+ scp.download(remotePath + "/*", localDir, ScpClient.Option.Recursive);
+ assertFileLength(local1, data.length, 5000);
+ assertFileLength(localSub2, data.length, 5000);
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ @Test
+ public void testScpNativePreserveAttributes() throws Exception {
+ // Ignore this test if running a Windows system
+ Assume.assumeFalse("Skip test for Windows", OsUtils.isWin32());
+
+ try (SshClient client = SshClient.setUpDefaultClient()) {
+ client.start();
+
+
+ try (ClientSession session = client.connect(getCurrentTestName(), "localhost", port).await().getSession()) {
+ session.addPasswordIdentity(getCurrentTestName());
+ session.auth().verify(5L, TimeUnit.SECONDS);
+
+ ScpClient scp = createScpClient(session);
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ Path scpRoot = Utils.resolve(targetPath, "scp", getClass().getSimpleName());
+ Utils.deleteRecursive(scpRoot);
+
+ Path localDir = scpRoot.resolve("local");
+ Path localSubDir = assertHierarchyTargetFolderExists(localDir.resolve("dir"));
+ long lastMod = Files.getLastModifiedTime(localSubDir).toMillis() - TimeUnit.DAYS.toMillis(1);
+ Path local1 = localDir.resolve(getCurrentTestName() + "-1.txt");
+ byte[] data = writeFile(local1, getCurrentTestName() + "\n");
+ File lclFile1 = local1.toFile();
+ lclFile1.setLastModified(lastMod);
+ lclFile1.setExecutable(true, true);
+ lclFile1.setWritable(false, false);
+
+ Path localSub2 = localSubDir.resolve(getCurrentTestName() + "-2.txt");
+ Files.write(localSub2, data);
+ File lclSubFile2 = localSub2.toFile();
+ lclSubFile2.setLastModified(lastMod);
+
+ Path remoteDir = assertHierarchyTargetFolderExists(scpRoot.resolve("remote"));
+ String remotePath = Utils.resolveRelativeRemotePath(parentPath, remoteDir);
+ scp.upload(localDir.toString() + File.separator + "*", remotePath, ScpClient.Option.Recursive, ScpClient.Option.PreserveAttributes);
+
+ Path remote1 = remoteDir.resolve(local1.getFileName());
+ assertFileLength(remote1, data.length, 5000);
+
+ File remFile1 = remote1.toFile();
+ assertEquals("Mismatched uploaded last-modified time for " + remFile1, lastMod, remFile1.lastModified());
+
+ Path remoteSubDir = remoteDir.resolve(localSubDir.getFileName());
+ Path remoteSub2 = remoteSubDir.resolve(localSub2.getFileName());
+ assertFileLength(remoteSub2, data.length, 5000);
+
+ File remSubFile2 = remoteSub2.toFile();
+ assertEquals("Mismatched uploaded last-modified time for " + remSubFile2, lastMod, remSubFile2.lastModified());
+
+ Utils.deleteRecursive(localDir);
+ Files.createDirectories(localDir);
+
+ scp.download(remotePath + "/*", localDir, ScpClient.Option.Recursive, ScpClient.Option.PreserveAttributes);
+ assertFileLength(local1, data.length, 5000);
+ assertEquals("Mismatched downloaded last-modified time for " + lclFile1, lastMod, lclFile1.lastModified());
+ assertFileLength(localSub2, data.length, 5000);
+ assertEquals("Mismatched downloaded last-modified time for " + lclSubFile2, lastMod, lclSubFile2.lastModified());
+ } finally {
+ client.stop();
+ }
+ }
+ }
+
+ private static byte[] writeFile(Path path, String data) throws IOException {
+ try(OutputStream fos = Files.newOutputStream(path)) {
+ byte[] bytes = data.getBytes();
+ fos.write(bytes);
+ return bytes;
+ }
+ }
+
+ @Test
+ public void testJschScp() throws Exception {
+ session = getJschSession();
+ try {
+ String data = getCurrentTestName() + "\n";
+
+ String unixDir = "target/scp";
+ String fileName = getCurrentTestName() + ".txt";
+ String unixPath = unixDir + "/" + fileName;
+ File root = new File(unixDir);
+ File target = new File(unixPath);
+ Utils.deleteRecursive(root);
+ root.mkdirs();
+ assertTrue(root.exists());
+
+ target.delete();
+ assertFalse(target.exists());
+ sendFile(unixPath, fileName, data);
+ assertFileLength(target, data.length(), 5000);
+
+ target.delete();
+ assertFalse(target.exists());
+ sendFile(unixDir, fileName, data);
+ assertFileLength(target, data.length(), 5000);
+
+ sendFileError("target", "scp", 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", "scp", fileName, data);
+ assertFileLength(target, data.length(), 5000);
+ } finally {
+ session.disconnect();
+ }
+ }
+
+ @Test
+ public void testWithGanymede() throws Exception {
+ // begin client config
+ final Connection conn = new Connection("localhost", port);
+ try {
+ conn.connect(null, 5000, 0);
+ conn.authenticateWithPassword("sshd", "sshd");
+ final SCPClient scp_client = new SCPClient(conn);
+ final Properties props = new Properties();
+ props.setProperty("test", "test-passed");
+ File f = new File("target/scp/gan");
+ Utils.deleteRecursive(f);
+ f.mkdirs();
+ assertTrue(f.exists());
+
+ String name = "test.properties";
+ scp_client.put(toBytes(props, ""), name, "target/scp/gan");
+ assertTrue(new File(f, name).exists());
+ assertTrue(new File(f, name).delete());
+
+ name = "test2.properties";
+ scp_client.put(toBytes(props, ""), name, "target/scp/gan");
+ assertTrue(new File(f, name).exists());
+ assertTrue(new File(f, name).delete());
+
+ assertTrue(f.delete());
+ } finally {
+ conn.close();
+ }
+ }
+
+ private byte[] toBytes(final Properties properties, final String comments) {
+ try(ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
+ properties.store(baos, comments);
+ baos.close();
+ return baos.toByteArray();
+ } catch(IOException cause) {
+ throw new RuntimeException("Failed to output properties to byte[]", cause);
+ }
+ }
+
+ protected String readFile(String path, long expectedSize) throws Exception {
+ ChannelExec c = (ChannelExec) session.openChannel("exec");
+ c.setCommand("scp -f " + path);
+ c.connect();
+
+ int namePos = path.lastIndexOf('/');
+ String fileName = (namePos >= 0) ? path.substring(namePos + 1) : path;
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+
+ os.write(0);
+ os.flush();
+ String header = readLine(is);
+ assertEquals("Mismatched header for " + path, "C0644 " + expectedSize + " " + fileName, header);
+
+ 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);
+ assertAckReceived(is, "Read data of " + path);
+
+ os.write(0);
+ os.flush();
+
+ return new String(buffer);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected String readDir(String path, String fileName, long expectedSize) throws Exception {
+ ChannelExec c = (ChannelExec) session.openChannel("exec");
+ c.setCommand("scp -r -f " + path);
+ c.connect();
+
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+ os.write(0);
+ os.flush();
+
+ String header = readLine(is);
+ assertTrue("Bad header prefix for " + path + ": " + header, header.startsWith("D0755 0 "));
+ os.write(0);
+ os.flush();
+
+ header = readLine(is);
+ assertEquals("Mismatched dir header for " + path, "C0644 " + expectedSize + " " + fileName, header);
+ 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 buffer size for " + path, length, buffer.length);
+ assertAckReceived(is, "Read date of " + path);
+
+ os.write(0);
+ os.flush();
+
+ header = readLine(is);
+ assertEquals("Mismatched end value for " + path, "E", header);
+ os.write(0);
+ os.flush();
+
+ return new String(buffer);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected String readFileError(String path) throws Exception {
+ ChannelExec c = (ChannelExec) session.openChannel("exec");
+ String command = "scp -f " + path;
+ c.setCommand(command);
+ c.connect();
+
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+
+ os.write(0);
+ os.flush();
+ assertEquals("Mismatched response for command: " + command, 2, is.read());
+ return null;
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected void sendFile(String path, String name, String data) throws Exception {
+ ChannelExec c = (ChannelExec) session.openChannel("exec");
+ String command = "scp -t " + path;
+ c.setCommand(command);
+ c.connect();
+
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+
+ assertAckReceived(is, command);
+ assertAckReceived(os, is, "C7777 " + data.length() + " " + name);
+
+ os.write(data.getBytes());
+ os.flush();
+ assertAckReceived(is, "Sent data (length=" + data.length() + ") for " + path + "[" + name + "]");
+
+ os.write(0);
+ os.flush();
+
+ Thread.sleep(100);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected void assertAckReceived(OutputStream os, InputStream is, String command) throws IOException {
+ os.write((command + "\n").getBytes());
+ os.flush();
+ assertAckReceived(is, command);
+ }
+
+ protected void assertAckReceived(InputStream is, String command) throws IOException {
+ assertEquals("No ACK for command=" + command, 0, is.read());
+ }
+
+ protected void sendFileError(String path, String name, String data) throws Exception {
+ ChannelExec c = (ChannelExec) session.openChannel("exec");
+ String command = "scp -t " + path;
+ c.setCommand(command);
+ c.connect();
+
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+
+ assertAckReceived(is, command);
+
+ command = "C7777 " + data.length() + " " + name;
+ os.write((command + "\n").getBytes());
+ os.flush();
+ assertEquals("Mismatched response for command=" + command, 2, is.read());
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ protected void sendDir(String path, String dirName, String fileName, String data) throws Exception {
+ ChannelExec c = (ChannelExec) session.openChannel("exec");
+ String command = "scp -t -r " + path;
+ c.setCommand(command);
+ c.connect();
+
+ try(OutputStream os = c.getOutputStream();
+ InputStream is = c.getInputStream()) {
+
+ assertAckReceived(is, command);
+ assertAckReceived(os, is, "D0755 0 " + dirName);
+ assertAckReceived(os, is, "C7777 " + data.length() + " " + fileName);
+
+ os.write(data.getBytes());
+ os.flush();
+ assertAckReceived(is, "Send data of " + path);
+
+ os.write(0);
+ os.flush();
+
+ os.write("E\n".getBytes());
+ os.flush();
+ assertAckReceived(is, "Signal end of " + path);
+ } finally {
+ c.disconnect();
+ }
+ }
+
+ private static String readLine(InputStream in) throws IOException {
+ OutputStream baos = new ByteArrayOutputStream();
+ try {
+ for (; ; ) {
+ int c = in.read();
+ if (c == '\n') {
+ return baos.toString();
+ } else if (c == -1) {
+ throw new IOException("End of stream");
+ } else {
+ baos.write(c);
+ }
+ }
+ } finally {
+ baos.close();
+ }
+ }
+
+ private ScpClient createScpClient(ClientSession session) {
+ final Logger logger = LoggerFactory.getLogger(getClass().getName() + "[" + getCurrentTestName() + "]");
+ return session.createScpClient(new ScpTransferEventListener() {
+ @Override
+ public void startFolderEvent(FileOperation op, Path file, Set<PosixFilePermission> perms) {
+ logEvent("starFolderEvent", op, file, false, -1L, perms, null);
+ }
+
+ @Override
+ public void startFileEvent(FileOperation op, Path file, long length, Set<PosixFilePermission> perms) {
+ logEvent("startFileEvent", op, file, true, length, perms, null);
+
+ }
+
+ @Override
+ public void endFolderEvent(FileOperation op, Path file, Set<PosixFilePermission> perms, Throwable thrown) {
+ logEvent("endFolderEvent", op, file, false, -1L, perms, thrown);
+ }
+
+ @Override
+ public void endFileEvent(FileOperation op, Path file, long length, Set<PosixFilePermission> perms, Throwable thrown) {
+ logEvent("endFileEvent", op, file, true, length, perms, thrown);
+ }
+
+ private void logEvent(String type, FileOperation op, Path path, boolean isFile, long length, Collection<PosixFilePermission> perms, Throwable t) {
+ StringBuilder sb = new StringBuilder(Byte.MAX_VALUE);
+ sb.append('\t').append(type)
+ .append('[').append(op).append(']')
+ .append(' ').append(isFile ? "File" : "Directory").append('=').append(path)
+ .append(' ').append("length=").append(length)
+ .append(' ').append("perms=").append(perms)
+ ;
+ if (t != null) {
+ sb.append(' ').append("ERROR=").append(t.getClass().getSimpleName()).append(": ").append(t.getMessage());
+ }
+ logger.info(sb.toString());
+ }
+ });
+ }
+}
http://git-wip-us.apache.org/repos/asf/mina-sshd/blob/b6166cc8/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpFileSystemTest.java
----------------------------------------------------------------------
diff --git a/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpFileSystemTest.java b/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpFileSystemTest.java
new file mode 100644
index 0000000..3187f63
--- /dev/null
+++ b/sshd-core/src/test/java/org/apache/sshd/client/sftp/SftpFileSystemTest.java
@@ -0,0 +1,260 @@
+/*
+ * 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.client.sftp;
+
+import java.io.IOException;
+import java.net.URI;
+import java.nio.channels.FileChannel;
+import java.nio.channels.FileLock;
+import java.nio.channels.OverlappingFileLockException;
+import java.nio.file.DirectoryStream;
+import java.nio.file.FileAlreadyExistsException;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.LinkOption;
+import java.nio.file.NoSuchFileException;
+import java.nio.file.Path;
+import java.nio.file.StandardCopyOption;
+import java.nio.file.attribute.FileTime;
+import java.nio.file.attribute.GroupPrincipal;
+import java.nio.file.attribute.PosixFilePermissions;
+import java.nio.file.attribute.UserPrincipalLookupService;
+import java.nio.file.attribute.UserPrincipalNotFoundException;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Map;
+
+import org.apache.sshd.SshServer;
+import org.apache.sshd.common.NamedFactory;
+import org.apache.sshd.common.Session;
+import org.apache.sshd.common.file.FileSystemFactory;
+import org.apache.sshd.common.file.root.RootedFileSystemProvider;
+import org.apache.sshd.common.util.OsUtils;
+import org.apache.sshd.server.Command;
+import org.apache.sshd.server.command.ScpCommandFactory;
+import org.apache.sshd.server.sftp.SftpSubsystemFactory;
+import org.apache.sshd.util.BaseTestSupport;
+import org.apache.sshd.util.BogusPasswordAuthenticator;
+import org.apache.sshd.util.EchoShellFactory;
+import org.apache.sshd.util.Utils;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+public class SftpFileSystemTest extends BaseTestSupport {
+
+ private SshServer sshd;
+ private int port;
+ private final FileSystemFactory fileSystemFactory;
+
+ public SftpFileSystemTest() throws IOException {
+ Path targetPath = detectTargetFolder().toPath();
+ Path parentPath = targetPath.getParent();
+ final FileSystem fileSystem = new RootedFileSystemProvider().newFileSystem(parentPath, Collections.<String,Object>emptyMap());
+ fileSystemFactory = new FileSystemFactory() {
+ @Override
+ public FileSystem createFileSystem(Session session) throws IOException {
+ return fileSystem;
+ }
+ };
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ sshd = SshServer.setUpDefaultServer();
+ sshd.setKeyPairProvider(Utils.createTestHostKeyProvider());
+ sshd.setSubsystemFactories(Arrays.<NamedFactory<Command>>asList(new SftpSubsystemFactory()));
+ sshd.setCommandFactory(new ScpCommandFactory());
+ sshd.setShellFactory(new EchoShellFactory());
+ sshd.setPasswordAuthenticator(new BogusPasswordAuthenticator());
+ sshd.setFileSystemFactory(fileSystemFactory);
+ sshd.start();
+ port = sshd.getPort();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ if (sshd != null) {
+ sshd.stop(true);
+ }
+ }
+
+ @Test
+ public void testFileSystem() throws IOException {
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+
+ try(FileSystem fs = FileSystems.newFileSystem(URI.create("sftp://x:x@localhost:" + port + "/"), Collections.<String,Object>emptyMap())) {
+ Iterable<Path> rootDirs = fs.getRootDirectories();
+ for (Path root : rootDirs) {
+ String rootName = root.toString();
+ try (DirectoryStream<Path> ds = Files.newDirectoryStream(root)) {
+ for (Path child : ds) {
+ System.out.append('\t').append('[').append(rootName).append("] ").println(child);
+ }
+ } catch(IOException | RuntimeException e) {
+ // TODO on Windows one might get share problems for *.sys files
+ // e.g. "C:\hiberfil.sys: The process cannot access the file because it is being used by another process"
+ // for now, Windows is less of a target so we are lenient with it
+ if (OsUtils.isWin32()) {
+ System.err.println(e.getClass().getSimpleName() + " while accessing children of root=" + root + ": " + e.getMessage());
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ Path current = fs.getPath(".").toRealPath().normalize();
+ System.out.append("CWD: ").println(current);
+
+ Path parentPath = targetPath.getParent();
+ Path clientFolder = lclSftp.resolve("client");
+ String remFile1Path = Utils.resolveRelativeRemotePath(parentPath, clientFolder.resolve(getCurrentTestName() + "-1.txt"));
+ Path file1 = fs.getPath(remFile1Path);
+ Files.createDirectories(file1.getParent());
+
+ String expected="Hello world: " + getCurrentTestName();
+ {
+ Files.write(file1, expected.getBytes());
+ String buf = new String(Files.readAllBytes(file1));
+ assertEquals("Mismatched read test data", expected, buf);
+ }
+
+ String remFile2Path = Utils.resolveRelativeRemotePath(parentPath, clientFolder.resolve(getCurrentTestName() + "-2.txt"));
+ Path file2 = fs.getPath(remFile2Path);
+ String remFile3Path = Utils.resolveRelativeRemotePath(parentPath, clientFolder.resolve(getCurrentTestName() + "-3.txt"));
+ Path file3 = fs.getPath(remFile3Path);
+ try {
+ Files.move(file2, file3);
+ fail("Unexpected success in moving " + file2 + " => " + file3);
+ } catch (NoSuchFileException e) {
+ // expected
+ }
+
+ Files.write(file2, "h".getBytes());
+ try {
+ Files.move(file1, file2);
+ fail("Unexpected success in moving " + file1 + " => " + file2);
+ } catch (FileAlreadyExistsException e) {
+ // expected
+ }
+ Files.move(file1, file2, StandardCopyOption.REPLACE_EXISTING);
+ Files.move(file2, file1);
+
+ Map<String, Object> attrs = Files.readAttributes(file1, "*");
+ System.out.append(file1.toString()).append(" attributes: ").println(attrs);
+
+ // TODO: symbolic links only work for absolute files
+ // Path link = fs.getPath("target/sftp/client/test2.txt");
+ // Files.createSymbolicLink(link, link.relativize(file));
+ // assertTrue(Files.isSymbolicLink(link));
+ // assertEquals("test.txt", Files.readSymbolicLink(link).toString());
+
+ // TODO there are many issues with Windows and symbolic links - for now they are of a lesser interest
+ if (OsUtils.isUNIX()) {
+ Path link = fs.getPath(remFile2Path);
+ Path linkParent = link.getParent();
+ Path relPath = linkParent.relativize(file1);
+ Files.createSymbolicLink(link, relPath);
+ assertTrue("Not a symbolic link: " + link, Files.isSymbolicLink(link));
+
+ Path symLink = Files.readSymbolicLink(link);
+ assertEquals("mismatched symbolic link name", relPath.toString(), symLink.toString());
+ Files.delete(link);
+ }
+
+ attrs = Files.readAttributes(file1, "*", LinkOption.NOFOLLOW_LINKS);
+ System.out.append(file1.toString()).append(" no-follow attributes: ").println(attrs);
+
+ assertEquals("Mismatched symlink data", expected, new String(Files.readAllBytes(file1)));
+
+ try (FileChannel channel = FileChannel.open(file1)) {
+ try (FileLock lock = channel.lock()) {
+ System.out.println("Locked " + lock.toString());
+
+ try (FileChannel channel2 = FileChannel.open(file1)) {
+ try (FileLock lock2 = channel2.lock()) {
+ System.out.println("Locked " + lock2.toString());
+ fail("Unexpected success in re-locking " + file1);
+ } catch (OverlappingFileLockException e) {
+ // expected
+ }
+ }
+ }
+ }
+
+ Files.delete(file1);
+ }
+ }
+
+ @Test
+ public void testAttributes() throws IOException {
+ Path targetPath = detectTargetFolder().toPath();
+ Path lclSftp = Utils.resolve(targetPath, "sftp", getClass().getSimpleName());
+ Utils.deleteRecursive(lclSftp);
+
+ try (FileSystem fs = FileSystems.newFileSystem(URI.create("sftp://x:x@localhost:" + port + "/"), null)) {
+ Path parentPath = targetPath.getParent();
+ Path clientFolder = lclSftp.resolve("client");
+ String remFilePath = Utils.resolveRelativeRemotePath(parentPath, clientFolder.resolve(getCurrentTestName() + ".txt"));
+ Path file = fs.getPath(remFilePath);
+ Files.createDirectories(file.getParent());
+ Files.write(file, (getCurrentTestName() + "\n").getBytes());
+
+ 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));
+
+ FileSystem fileSystem = file.getFileSystem();
+ try {
+ UserPrincipalLookupService userLookupService = fileSystem.getUserPrincipalLookupService();
+ GroupPrincipal group = userLookupService.lookupPrincipalByGroupName("everyone");
+ Files.setAttribute(file, "posix:group", group);
+ } catch (UserPrincipalNotFoundException e) {
+ // Also, according to the Javadoc:
+ // "Where an implementation does not support any notion of
+ // group then this method always throws UserPrincipalNotFoundException."
+ // Therefore we are lenient with this exception for Windows
+ if (OsUtils.isWin32()) {
+ System.err.println(e.getClass().getSimpleName() + ": " + e.getMessage());
+ } else {
+ throw e;
+ }
+ }
+ }
+ }
+
+ @Test
+ public void testRootFileSystem() throws IOException {
+ Path targetPath = detectTargetFolder().toPath();
+ Path rootNative = targetPath.resolve("root").toAbsolutePath();
+ Utils.deleteRecursive(rootNative);
+ Files.createDirectories(rootNative);
+
+ try(FileSystem fs = FileSystems.newFileSystem(URI.create("root:" + rootNative.toUri().toString() + "!/"), null)) {
+ Path dir = Files.createDirectories(fs.getPath("test/foo"));
+ System.out.println("Created " + dir);
+ }
+ }
+}