View Javadoc

1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.commons.vfs.provider.ftp;
18  
19  import org.apache.commons.net.ftp.FTP;
20  import org.apache.commons.net.ftp.FTPClient;
21  import org.apache.commons.net.ftp.FTPClientConfig;
22  import org.apache.commons.net.ftp.FTPReply;
23  import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
24  import org.apache.commons.vfs.FileSystemException;
25  import org.apache.commons.vfs.FileSystemOptions;
26  import org.apache.commons.vfs.util.UserAuthenticatorUtils;
27  
28  import java.io.IOException;
29  
30  /***
31   * Create a FtpClient instance
32   *
33   * @author <a href="mailto:imario@apache.org">Mario Ivankovits</a>
34   * @version $Revision: 480428 $ $Date: 2006-11-29 07:15:24 +0100 (Mi, 29 Nov 2006) $
35   */
36  public class FtpClientFactory
37  {
38      private FtpClientFactory()
39      {
40      }
41  
42      /***
43       * Creates a new connection to the server.
44       */
45      public static FTPClient createConnection(String hostname, int port, char[] username, char[] password, String workingDirectory, FileSystemOptions fileSystemOptions) throws FileSystemException
46      {
47          // Determine the username and password to use
48          if (username == null)
49          {
50              username = "anonymous".toCharArray();
51          }
52  
53          if (password == null)
54          {
55              password = "anonymous".toCharArray();
56          }
57  
58          try
59          {
60              final FTPClient client = new FTPClient();
61  
62              String key = FtpFileSystemConfigBuilder.getInstance().getEntryParser(fileSystemOptions);
63              if (key != null)
64              {
65              	FTPClientConfig config = new FTPClientConfig(key);
66              	
67              	String serverLanguageCode = FtpFileSystemConfigBuilder.getInstance().getServerLanguageCode(fileSystemOptions);
68              	if (serverLanguageCode != null)
69              	{
70              		config.setServerLanguageCode(serverLanguageCode);
71              	}
72              	String defaultDateFormat = FtpFileSystemConfigBuilder.getInstance().getDefaultDateFormat(fileSystemOptions);
73              	if (defaultDateFormat != null)
74              	{
75              		config.setDefaultDateFormatStr(defaultDateFormat);
76              	}
77              	String recentDateFormat = FtpFileSystemConfigBuilder.getInstance().getRecentDateFormat(fileSystemOptions);
78              	if (recentDateFormat != null)
79              	{
80              		config.setRecentDateFormatStr(recentDateFormat);
81              	}
82              	String serverTimeZoneId = FtpFileSystemConfigBuilder.getInstance().getServerTimeZoneId(fileSystemOptions);
83              	if (serverTimeZoneId != null)
84              	{
85              		config.setServerTimeZoneId(serverTimeZoneId);
86              	}
87              	String[] shortMonthNames = FtpFileSystemConfigBuilder.getInstance().getShortMonthNames(fileSystemOptions);
88              	if (shortMonthNames != null)
89              	{
90              		StringBuffer shortMonthNamesStr = new StringBuffer(40);
91              		for (int i = 0; i<shortMonthNames.length; i++)
92              		{
93              			if (shortMonthNamesStr.length()>0)
94              			{
95              				shortMonthNamesStr.append("|");
96              			}
97              			shortMonthNamesStr.append(shortMonthNames[i]);            			
98              		}
99              		config.setShortMonthNames(shortMonthNamesStr.toString());
100             	}
101             	
102             	client.configure(config);
103             }
104             
105             FTPFileEntryParserFactory myFactory = FtpFileSystemConfigBuilder.getInstance().getEntryParserFactory(fileSystemOptions);
106             if (myFactory != null)
107             {
108                 client.setParserFactory(myFactory);
109             }
110 
111             try
112             {
113                 client.connect(hostname, port);
114 
115                 int reply = client.getReplyCode();
116                 if (!FTPReply.isPositiveCompletion(reply))
117                 {
118                     throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
119                 }
120 
121                 // Login
122                 if (!client.login(
123 					UserAuthenticatorUtils.toString(username),
124 					UserAuthenticatorUtils.toString(password)))
125                 {
126                     throw new FileSystemException("vfs.provider.ftp/login.error", new Object[]{hostname, UserAuthenticatorUtils.toString(username)}, null);
127                 }
128 
129                 // Set binary mode
130                 if (!client.setFileType(FTP.BINARY_FILE_TYPE))
131                 {
132                     throw new FileSystemException("vfs.provider.ftp/set-binary.error", hostname);
133                 }
134 
135                 // Set dataTimeout value
136                 Integer dataTimeout = FtpFileSystemConfigBuilder.getInstance().getDataTimeout(fileSystemOptions);
137                 if (dataTimeout != null)
138                 {
139                     client.setDataTimeout(dataTimeout.intValue());
140                 }
141 
142                 // Change to root by default
143                 // All file operations a relative to the filesystem-root
144                 // String root = getRoot().getName().getPath();
145 
146                 Boolean userDirIsRoot = FtpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(fileSystemOptions);
147                 if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
148                 {
149                     if (!client.changeWorkingDirectory(workingDirectory))
150                     {
151                         throw new FileSystemException("vfs.provider.ftp/change-work-directory.error", workingDirectory);
152                     }
153                 }
154 
155                 Boolean passiveMode = FtpFileSystemConfigBuilder.getInstance().getPassiveMode(fileSystemOptions);
156                 if (passiveMode != null && passiveMode.booleanValue())
157                 {
158                     client.enterLocalPassiveMode();
159                 }
160             }
161             catch (final IOException e)
162             {
163                 if (client.isConnected())
164                 {
165                     client.disconnect();
166                 }
167                 throw e;
168             }
169 
170             return client;
171         }
172         catch (final Exception exc)
173         {
174             throw new FileSystemException("vfs.provider.ftp/connect.error", new Object[]{hostname}, exc);
175         }
176     }
177 }