java Mina sftp_java – 使用Apache Mina作为模拟/内存SFTP服务器进行单元测试
我正在解決如何使用Apache Mina的麻煩.他們的文檔對我無能為力的大腦來說有一點不足.我已經看到了有用的起始代碼
Java SFTP server library?
我無法想像的是如何使用它.我想設置一個檢查我的sftp代碼的單元測試,使用Mina作為一種模擬服務器,即能夠寫一個單元測試,如:
@Before
public void beforeTestSetup() {
sshd = SshServer.setUpDefaultServer();
sshd.setPort(22);
sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser"));
List> userAuthFactories = new ArrayList>();
userAuthFactories.add(new UserAuthNone.Factory());
sshd.setUserAuthFactories(userAuthFactories);
sshd.setPublickeyAuthenticator(new PublickeyAuthenticator());
sshd.setCommandFactory(new ScpCommandFactory());
List> namedFactoryList = new ArrayList>();
namedFactoryList.add(new SftpSubsystem.Factory());
sshd.setSubsystemFactories(namedFactoryList);
try {
sshd.start();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testGetFile() {
}
問題是在testGetFile()中放入什么.
我一直在瀏覽測試代碼,想知道上面是否需要更多配置來指定根目錄,用戶名和身份驗證密鑰文件名.那么我需要使用客戶端或我自己的SFTP api代碼來獲取和拉取文件?
我相信這是一個很好的API,只是沒有很多的指導,任何人都可以幫忙?
這是我做的(JUnit):
@Test
public void testPutAndGetFile() throws JSchException,SftpException,IOException
{
JSch jsch = new JSch();
Hashtable config = new Hashtable();
config.put("StrictHostKeyChecking","no");
JSch.setConfig(config);
Session session = jsch.getSession( "remote-username","localhost",PORT);
session.setPassword("remote-password");
session.connect();
Channel channel = session.openChannel( "sftp" );
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
final String testFileContents = "some file contents";
String uploadedFileName = "uploadFile";
sftpChannel.put(new ByteArrayInputStream(testFileContents.getBytes()),uploadedFileName);
String downloadedFileName = "downLoadFile";
sftpChannel.get(uploadedFileName,downloadedFileName);
File downloadedFile = new File(downloadedFileName);
Assert.assertTrue(downloadedFile.exists());
String fileData = getFileContents(downloadedFile);
Assert.assertEquals(testFileContents,fileData);
if (sftpChannel.isConnected()) {
sftpChannel.exit();
System.out.println("Disconnected channel");
}
if (session.isConnected()) {
session.disconnect();
System.out.println("Disconnected session");
}
}
private String getFileContents(File downloadedFile)
throws FileNotFoundException,IOException
{
StringBuffer fileData = new StringBuffer();
BufferedReader reader = new BufferedReader(new FileReader(downloadedFile));
try {
char[] buf = new char[1024];
for(int numRead = 0; (numRead = reader.read(buf)) != -1; buf = new char[1024]) {
fileData.append(String.valueOf(buf,numRead));
}
} finally {
reader.close();
}
return fileData.toString();
}
總結
以上是生活随笔為你收集整理的java Mina sftp_java – 使用Apache Mina作为模拟/内存SFTP服务器进行单元测试的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ESN简介
- 下一篇: java中this.value_java