|
| 1 | +import java.io.File; |
| 2 | +import java.io.FileNotFoundException; |
| 3 | +import java.io.FileOutputStream; |
| 4 | +import java.io.IOException; |
| 5 | +import java.util.Properties; |
| 6 | + |
| 7 | +import com.jcraft.jsch.Channel; |
| 8 | +import com.jcraft.jsch.ChannelSftp; |
| 9 | +import com.jcraft.jsch.JSch; |
| 10 | +import com.jcraft.jsch.JSchException; |
| 11 | +import com.jcraft.jsch.Session; |
| 12 | +import com.jcraft.jsch.SftpException; |
| 13 | + |
| 14 | +/** |
| 15 | + * |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @author amitb |
| 20 | + * |
| 21 | + */ |
| 22 | +public class RemoteFileTransferService { |
| 23 | + |
| 24 | + private static Session sshSession; |
| 25 | + |
| 26 | + public static ChannelSftp connect(String host, int port, String username, String password) { |
| 27 | + ChannelSftp sftpChannel = null; |
| 28 | + JSch jsch = new JSch(); |
| 29 | + |
| 30 | + try { |
| 31 | + // host login info |
| 32 | + sshSession = jsch.getSession(username, host, port); |
| 33 | + sshSession.setPassword(password); |
| 34 | + |
| 35 | + Properties sshConfiguration = new Properties(); |
| 36 | + sshConfiguration.put("StrictHostKeyChecking", "no"); |
| 37 | + sshSession.setConfig(sshConfiguration); |
| 38 | + |
| 39 | + // connects to the remote host |
| 40 | + sshSession.connect(); |
| 41 | + |
| 42 | + Channel channel = sshSession.openChannel("sftp"); |
| 43 | + channel.connect(); |
| 44 | + sftpChannel = (ChannelSftp) channel; |
| 45 | + } catch (JSchException e) { |
| 46 | + // prblem connecting remote host |
| 47 | + e.printStackTrace(); |
| 48 | + } |
| 49 | + |
| 50 | + return sftpChannel; |
| 51 | + } |
| 52 | + |
| 53 | + public static void disconnect() { |
| 54 | + if (sshSession != null) { |
| 55 | + sshSession.disconnect(); |
| 56 | + } |
| 57 | + } |
| 58 | + |
| 59 | + public static void downloadRemoteFile(String downloadFilePath, String saveFilePath, ChannelSftp sftpChannel) { |
| 60 | + FileOutputStream fileOutputStream = null; |
| 61 | + try { |
| 62 | + File outputFile = new File(saveFilePath); |
| 63 | + fileOutputStream = new FileOutputStream(outputFile); |
| 64 | + sftpChannel.get(saveFilePath, fileOutputStream); |
| 65 | + } catch (FileNotFoundException e) { |
| 66 | + e.printStackTrace(); |
| 67 | + } catch (SftpException e) { |
| 68 | + e.printStackTrace(); |
| 69 | + } finally { |
| 70 | + if(fileOutputStream != null) { |
| 71 | + try { |
| 72 | + fileOutputStream.close(); |
| 73 | + } catch (IOException e) { |
| 74 | + e.printStackTrace(); |
| 75 | + } |
| 76 | + } |
| 77 | + } |
| 78 | + } |
| 79 | + |
| 80 | +} |
0 commit comments