So I’ve been preparing this module to do sftp / ftp / and file system manipulations in groovy.
I’ve got it running as a service in grails, with a page setup for testing.
Its really important that if your testing this class out in windows, you turn off your firewall.
I wasted like 2 hours trying to figure out why I kept getting errors.
Now I would like to turn this functionality into a .jar for standalone execution and injection into other projects.
You will need the ant-jsch.jar and jsch-0.1.33.jar, google guave, and apache commons net.
I some how automagically installed the ant-jsch and jsch jars in a way that doesn’t require import statements.
Credit due to
https://gist.github.com/1135043 for FTP code.
http://groovy-almanac.org/scp-with-groovy-and-antbuilder/ for SCP with ANT trick.
and an article I don’t recall the URL to on google guava for file system manipulation
import groovy.util.AntBuilder
import com.google.common.io.*
import org.apache.commons.net.ftp.FTPClient
class FileService {
def boolean fileSystemMove(String from, String to){
try{
Files.move( new File(from), new File(to) )
}catch(Throwable t){
println 'filesystem error' + t;
return false
}
return true;
}
def boolean fileSystemCopy(String from, String to){
try{
Files.copy( new File(from), new File(to) )
}catch(Throwable t){
return false
}
return true;
}
def boolean sftpCopyTo( String host, String user, String passwd, String destination, String fileurl ){
def ant = new AntBuilder();
ant.scp(
file: fileurl,
todir:"${user}@${host}:${destination}",
trust:true,
verbose:true,
password:passwd)
}
def boolean sftpCopyFrom( String host, String user, String passwd, String destination, String fileurl ){
def ant = new AntBuilder();
ant.scp(
file: "${user}@${host}:${fileurl}" ,
todir: destination,
verbose:true,
trust:true,
password:passwd)
}
def boolean ftpCopyFrom( String host, String user, String passwd, String destination, String fileurl ){
try{
def String fileName = fileurl.split('/')[-1];
new FTPClient().with {
connect host
//enterLocalPassiveMode()
type(BINARY_FILE_TYPE)
login user, passwd
changeWorkingDirectory destination
def incomingFile = new File(fileurl)
incomingFile.withOutputStream { ostream -> retrieveFile fileName, ostream }
disconnect()
}
true
}catch (Throwable t) {
false
}
}
def boolean ftpCopyTo( String host, String user, String passwd, String destination, String fileurl ){
try{
def String fileName = fileurl.split('/')[-1];
def FTPClient ftp = new FTPClient();
ftp.connect host
ftp.type(ftp.BINARY_FILE_TYPE)
ftp.login user, passwd
ftp.changeWorkingDirectory destination
def InputStream input = new FileInputStream(fileurl);
ftp.storeFile(fileName , input)
ftp.disconnect()
true
} catch ( Throwable t ) {
false
}
}
}
