{"id":10074,"date":"2013-04-04T15:26:42","date_gmt":"2013-04-04T09:56:42","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=10074"},"modified":"2013-07-13T11:34:24","modified_gmt":"2013-07-13T06:04:24","slug":"using-ftp-with-grails","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/using-ftp-with-grails\/","title":{"rendered":"Using Ftp with Grails"},"content":{"rendered":"<p>In one of my Grails project I need to drop files over ftp server. Using\u00a0<a title=\"JSch\" href=\"http:\/\/www.jcraft.com\/jsch\/\" target=\"_blank\">JSch<\/a>\u00a0one can easily transfer files over sftp. Just follow the below steps.<br \/>\n1. Add the below dependency to Grails project <em>&#8220;grails-app\/conf\/BuildConfig.groovy&#8221;<\/em> file<\/p>\n<p>[sourcecode language=&#8221;groovy&#8221;]<br \/>\ndependencies {<br \/>\n        compile &#8216;com.jcraft:jsch:0.1.49&#8217;<br \/>\n    }<br \/>\n[\/sourcecode]<\/p>\n<p>2. Create a class for adding ftp credentials information. e.g. &#8220;FtpCredentail&#8221;<\/p>\n<p>[sourcecode language=&#8221;groovy&#8221;]<br \/>\nclass FtpCredential {<\/p>\n<p>    String server<br \/>\n    String username<br \/>\n    String password<br \/>\n    String remoteBaseDir<br \/>\n    Integer port<br \/>\n}<br \/>\n[\/sourcecode]<\/p>\n<p>3. Create a service named &#8220;FtpService&#8221; and add the following code into it<\/p>\n<p>[sourcecode language=&#8221;groovy&#8221;]<br \/>\nimport com.jcraft.jsch.Channel<br \/>\nimport com.jcraft.jsch.ChannelSftp<br \/>\nimport com.jcraft.jsch.JSch<br \/>\nimport com.jcraft.jsch.Session<\/p>\n<p>class FtpService {<br \/>\n    def grailsApplication<\/p>\n<p>    static transactional = true<\/p>\n<p>    def save(InputStream inputStream, String fileName, FtpCredential ftpCredential) {<br \/>\n        connect(ftpCredential) { ChannelSftp sftp -&gt;<br \/>\n            sftp.put inputStream, fileName<br \/>\n        }<br \/>\n    }<\/p>\n<p>    def load(String fileName, FtpCredential ftpCredential) {<br \/>\n        connect(ftpCredential, { ChannelSftp sftp -&gt;<br \/>\n            File outputFile = File.createTempFile(fileName,&#8221;)<br \/>\n            outputFile?.newOutputStream() &lt;&lt; sftp.get(fileName)<br \/>\n            outputFile<br \/>\n        }, false)<br \/>\n    }<\/p>\n<p>    def delete(String fileName, FtpCredential ftpCredential) throws Throwable {<br \/>\n        connect(ftpCredential) { ChannelSftp sftp -&gt;<br \/>\n            sftp.rm fileName<br \/>\n        }<br \/>\n    }<\/p>\n<p>    def makeDir(String directoryName, FtpCredential ftpCredential) {<br \/>\n        connect(ftpCredential) { ChannelSftp sftp -&gt;<br \/>\n            sftp.mkdir directoryName<br \/>\n        }<br \/>\n    }<\/p>\n<p>    private def connect(FtpCredential ftpCredential, Closure c, boolean disconnectOnFinish = true) {<br \/>\n        Session session = null<br \/>\n        ChannelSftp sftp = null<br \/>\n        try {<br \/>\n            JSch jSch = new JSch()<br \/>\n            session = jSch.getSession username, ftpCredential?.server, ftpCredential?.port<br \/>\n            session.setConfig &quot;StrictHostKeyChecking&quot;, &quot;no&quot;<br \/>\n            File keyFile = new File(&quot;${grailsApplication.config.pathToKeyFile}&quot;)<br \/>\n            if (ftpCredential?.password) {<br \/>\n                session.password = ftpCredential?.password<br \/>\n            } else {<br \/>\n                jSch.addIdentity(keyFile?.absolutePath)<br \/>\n            }<br \/>\n            session.connect()<br \/>\n            Channel sFtpChannel = session.openChannel &quot;sftp&quot;<br \/>\n            sFtpChannel.connect()<br \/>\n            sftp = sFtpChannel as ChannelSftp<br \/>\n            sftp.cd ftpCredential?.remoteBaseDir<br \/>\n            c.call sftp<br \/>\n        } catch (Exception ex) {<br \/>\n            ex.printStackTrace()<br \/>\n        } finally {<br \/>\n            if (disconnectOnFinish) {<br \/>\n                sftp?.exit()<br \/>\n                session?.disconnect()<br \/>\n            }<br \/>\n        }<br \/>\n    }<br \/>\n}<br \/>\n[\/sourcecode]<br \/>\n<strong>Note:<\/strong> In the above code at <em>line number 44<\/em>.<br \/>\n[sourcecode language=&#8221;groovy&#8221;]<br \/>\nFile keyFile = new File(&quot;${grailsApplication.config.pathToKeyFile}&quot;)<br \/>\n[\/sourcecode]<br \/>\nThe code looks for private key provided by ftp server for password-less log in. One should define the property named &#8220;<em>pathToKeyFile<\/em>&#8221; in &#8220;<em>grails-app\/conf\/Config.groovy<\/em>&#8221; with value equals to the path of key file.<br \/>\n<br \/>\nNow you are ready to use the newly created FtpService service methods. Such as:<\/p>\n<ol>\n<li><em>save(inputStream, fileName, ftpCredential)<\/em> for saving file over ftp.<\/li>\n<li><em>load(fileName, ftpCredential)<\/em> for getting file from ftp.<\/li>\n<li><em>delete(fileName, ftpCredential)<\/em> for deleting file over ftp.<\/li>\n<li><em>makeDir(directoryName, ftpCredential)<\/em> for creating directory over ftp.<\/li>\n<\/ol>\n<h2>Example<\/h2>\n<p>For saving file over ftp one can use FtpService <strong>save<\/strong> method as shown below<br \/>\n[sourcecode language=&#8221;groovy&#8221;]<br \/>\n File file = File.createTempFile(&quot;temp&quot;,&quot;txt&quot;)<br \/>\n FtpCredential ftpCredential = new FtpCredential(server: &lt;server&gt;, username: &lt;username&gt;, password: &lt;password&gt;, port: &lt;server_port&gt;, remoteBaseDir: &lt;remote_base_directory&gt;)<br \/>\n InputStream inputStream = new BufferedInputStream(new FileInputStream(file))<br \/>\n ftpService.save(inputStream, &quot;fileNameToBeSavedOverFTPServer&quot;, ftpCredential)<br \/>\n[\/sourcecode]<br \/>\n<br \/>\n<em>Please share your feedback and suggestions.<\/em><\/p>\n<hr \/>\n<p style=\"text-align: right\"><strong><em><a title=\"JSch Examples\" href=\"http:\/\/www.jcraft.com\/jsch\/examples\/\" target=\"_blank\">Click here to read more <em>JSch<\/em> examples \u00bb<\/a><\/em><\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In one of my Grails project I need to drop files over ftp server. Using\u00a0JSch\u00a0one can easily transfer files over sftp. Just follow the below steps. 1. Add the below dependency to Grails project &#8220;grails-app\/conf\/BuildConfig.groovy&#8221; file [sourcecode language=&#8221;groovy&#8221;] dependencies { compile &#8216;com.jcraft:jsch:0.1.49&#8217; } [\/sourcecode] 2. Create a class for adding ftp credentials information. e.g. &#8220;FtpCredentail&#8221; [&hellip;]<\/p>\n","protected":false},"author":57,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":14},"categories":[7],"tags":[815,4840,9,1154,1153,1152,553],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/10074"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/57"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=10074"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/10074\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=10074"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=10074"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=10074"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}