2012-08-07 17 views
13

Estoy teniendo problemas para encontrar la manera de usar Apache Mina. Su documentación es un poco escasa para que mi cerebro sin talento funcione. He visto el útil código de inicio en Java SFTP server library?Usando Apache Mina como un Servidor SFTP Simulado/en Memoria para Prueba de Unidad

Lo que no puedo entender es cómo usarlo. Quiero fijar una unidad de prueba que comprueba mi código SFTP, utilizando Mina como una especie de simulacro de servidor, es decir, ser capaz de escribir una prueba unitaria como:

@Before 
public void beforeTestSetup() { 
    sshd = SshServer.setUpDefaultServer(); 
    sshd.setPort(22); 
    sshd.setKeyPairProvider(new SimpleGeneratorHostKeyProvider("hostkey.ser")); 

    List<NamedFactory<UserAuth>> userAuthFactories = new ArrayList<NamedFactory<UserAuth>>(); 
    userAuthFactories.add(new UserAuthNone.Factory()); 
    sshd.setUserAuthFactories(userAuthFactories); 
    sshd.setPublickeyAuthenticator(new PublickeyAuthenticator()); 


    sshd.setCommandFactory(new ScpCommandFactory()); 

    List<NamedFactory<Command>> namedFactoryList = new ArrayList<NamedFactory<Command>>(); 
    namedFactoryList.add(new SftpSubsystem.Factory()); 
    sshd.setSubsystemFactories(namedFactoryList); 

    try { 
     sshd.start(); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 
} 

@Test 
public void testGetFile() { 

} 

La cuestión es qué poner en testGetFile().

He estado rastreando el código de prueba preguntándome si se necesita más configuración en lo anterior para especificar un directorio raíz, un nombre de usuario y un nombre de archivo de clave de autenticación. Entonces, ¿tendré que obtener y extraer archivos de él usando un cliente o mi propio código api de SFTP?

Estoy seguro de que esta es una API excelente, simplemente no hay mucha instrucción, ¿alguien puede ayudar?

Respuesta

7

Aquí es lo que hice (JUnit):

@Test 
    public void testPutAndGetFile() throws JSchException, SftpException, IOException 
    { 
    JSch jsch = new JSch(); 

    Hashtable<String, String> config = new Hashtable<String, String>(); 
    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, 0, numRead)); 
     } 
    } finally {  
     reader.close(); 
    } 

    return fileData.toString(); 
    }