Advertisement
Guest User

Untitled

a guest
Apr 25th, 2016
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.63 KB | None | 0 0
  1. package io.forward.ftp
  2.  
  3. import java.io.{File, FileOutputStream, InputStream}
  4.  
  5. import org.apache.commons.net.ftp._
  6. import scala.util.Try
  7.  
  8. final class FTP() {
  9.  
  10. private val client = new FTPClient
  11.  
  12. def login(username: String, password: String): Try[Boolean] = Try {
  13. client.login(username, password)
  14. }
  15.  
  16. def connect(host: String): Try[Unit] = Try {
  17. client.connect(host)
  18. client.enterLocalPassiveMode()
  19. }
  20.  
  21. def connected: Boolean = client.isConnected
  22.  
  23. def disconnect(): Unit = client.disconnect()
  24.  
  25. def canConnect(host: String): Boolean = {
  26. client.connect(host)
  27. val connectionWasEstablished = connected
  28. client.disconnect()
  29. connectionWasEstablished
  30. }
  31.  
  32. def listFiles(dir: Option[String] = None): List[FTPFile] =
  33. dir.fold(client.listFiles)(client.listFiles).toList
  34.  
  35. def connectWithAuth(host: String,
  36. username: String = "anonymous",
  37. password: String = "") : Try[Boolean] = {
  38. for {
  39. connection <- connect(host)
  40. login <- login(username, password)
  41. } yield login
  42. }
  43.  
  44. def cd(path: String): Boolean =
  45. client.changeWorkingDirectory(path)
  46.  
  47. def filesInCurrentDirectory: Seq[String] =
  48. listFiles().map(_.getName)
  49.  
  50. def downloadFileStream(remote: String): InputStream = {
  51. val stream = client.retrieveFileStream(remote)
  52. client.completePendingCommand()
  53. stream
  54. }
  55.  
  56. def downloadFile(remote: String): Boolean = {
  57. val os = new FileOutputStream(new File(remote))
  58. client.retrieveFile(remote, os)
  59. }
  60.  
  61. def uploadFile(remote: String, input: InputStream): Boolean =
  62. client.storeFile(remote, input)
  63. }
  64. Status API Training Shop Blog About
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement