View Javadoc
1   /*
2    * Copyright (c) MuleSoft, Inc.  All rights reserved.  http://www.mulesoft.com
3    * The software in this package is published under the terms of the CPAL v1.0
4    * license, a copy of which has been included with this distribution in the
5    * LICENSE.txt file.
6    */
7   package org.mule.transport.ftp;
8   
9   import org.mule.api.endpoint.EndpointURI;
10  
11  import java.io.IOException;
12  
13  import org.apache.commons.net.ftp.FTP;
14  import org.apache.commons.net.ftp.FTPClient;
15  import org.apache.commons.net.ftp.FTPReply;
16  import org.apache.commons.pool.PoolableObjectFactory;
17  
18  public class FtpConnectionFactory implements PoolableObjectFactory
19  {
20      private EndpointURI uri;
21  
22      public FtpConnectionFactory(EndpointURI uri)
23      {
24          this.uri = uri;
25      }
26  
27      public Object makeObject() throws Exception
28      {
29          FTPClient client = new FTPClient();
30          if (uri.getPort() > 0)
31          {
32              client.connect(uri.getHost(), uri.getPort());
33          }
34          else
35          {
36              client.connect(uri.getHost());
37          }
38          if (!FTPReply.isPositiveCompletion(client.getReplyCode()))
39          {
40              throw new IOException("Ftp connect failed: " + client.getReplyCode());
41          }
42          if (!client.login(uri.getUser(), uri.getPassword()))
43          {
44              throw new IOException("Ftp login failed: " + client.getReplyCode());
45          }
46          if (!client.setFileType(FTP.BINARY_FILE_TYPE))
47          {
48              throw new IOException("Ftp error. Couldn't set BINARY transfer type: " + client.getReplyCode());
49          }
50          return client;
51      }
52  
53      public void destroyObject(Object obj) throws Exception
54      {
55          FTPClient client = (FTPClient) obj;
56          client.logout();
57          client.disconnect();
58      }
59  
60      public boolean validateObject(Object obj)
61      {
62          FTPClient client = (FTPClient) obj;
63          try
64          {
65              return client.sendNoOp();
66          }
67          catch (IOException e)
68          {
69              return false;
70          }
71      }
72  
73      public void activateObject(Object obj) throws Exception
74      {
75          // nothing to do
76      }
77  
78      public void passivateObject(Object obj) throws Exception
79      {
80          // nothing to do
81      }
82  }
83