Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juev/8eff922dd1dbf808bdf7873d09961e42 to your computer and use it in GitHub Desktop.
Save juev/8eff922dd1dbf808bdf7873d09961e42 to your computer and use it in GitHub Desktop.
FtpClient Connection Timeouts
import org.apache.commons.net.ftp.*
import java.io.InputStream
import java.io.ByteArrayInputStream
String ftphost = "127.0.0.1"
String ftpuser = "test"
String ftppwd = "test"
int ftpport = 21
String ftpDir = "tmp/FTP"
int TENSECONDS = 10*1000
int THIRTYSECONDS = 30*1000
//Declare FTP client
FTPClient ftp = new FTPClient()
try
{
ftp.setConnectTimeout(TENSECONDS)
ftp.setDefaultTimeout(TENSECONDS)
ftp.connect(ftphost, ftpport)
//30 seconds to log on. Also 30 seconds to change to working directory.
ftp.setSoTimeout(THIRTYSECONDS)
def reply = ftp.getReplyCode()
if (!FTPReply.isPositiveCompletion(reply))
{
throw new Exception("Unable to connect to FTP server")
}
if (!ftp.login(ftpuser, ftppwd))
{
throw new Exception("Unable to login to FTP server")
}
if (!ftp.changeWorkingDirectory(ftpDir))
{
throw new Exception("Unable to change working directory on FTP server")
}
//Change the timeout here for a large file transfer that will take over 30 seconds
//ftp.setSoTimeout(THIRTYSECONDS);
ftp.setFileType(FTPClient.ASCII_FILE_TYPE)
ftp.enterLocalPassiveMode()
String filetxt = "Some String file content"
InputStream is = new ByteArrayInputStream(filetxt.getBytes('US-ASCII'))
try
{
if (!ftp.storeFile("myFile.txt", is))
{
throw new Exception("Unable to write file to FTP server")
}
//Make sure to always close the inputStream
}
finally
{
is.close()
}
}
catch(Exception e)
{
//handle exceptions here by logging or auditing
}
finally
{
//if the IO is timed out or force disconnected, exceptions may be thrown when trying to logout/disconnect
try
{
//10 seconds to log off. Also 10 seconds to disconnect.
ftp.setSoTimeout(TENSECONDS);
ftp.logout();
//depending on the state of the server the .logout() may throw an exception,
//we want to ensure complete disconnect.
}
catch(Exception innerException)
{
//You potentially just want to log that there was a logout exception.
}
finally
{
//Make sure to always disconnect. If not, there is a chance you will leave hanging sockects
ftp.disconnect();
}
}
return true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment