FakeFtpServer.java revision 2a0a3f946dba517a01cc26278f905156857c9c91
1/*
2 * Copyright 2008 the original author or authors.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package org.mockftpserver.fake;
17
18import org.mockftpserver.core.command.CommandHandler;
19import org.mockftpserver.core.command.CommandNames;
20import org.mockftpserver.core.server.AbstractFtpServer;
21import org.mockftpserver.fake.command.*;
22import org.mockftpserver.fake.filesystem.FileSystem;
23
24import java.util.HashMap;
25import java.util.List;
26import java.util.Map;
27
28/**
29 * <b>FakeFtpServer</b> is the top-level class for a "fake" implementation of an FTP Server,
30 * suitable for testing FTP client code or standing in for a live FTP server.
31 * <p/>
32 * <b>FakeFtpServer</b> provides a high-level abstraction for an FTP Server and is suitable
33 * for most testing and simulation scenarios. You define a filesystem (internal, in-memory) containing
34 * an arbitrary set of files and directories. These files and directories can (optionally) have
35 * associated access permissions. You also configure a set of one or more user accounts that
36 * control which users can login to the FTP server, and their home (default) directories. The
37 * user account is also used when assigning file and directory ownership for new files.
38 * <p> <b>FakeFtpServer</b> processes FTP client requests and responds with reply codes and
39 * reply messages consistent with its configuration and the contents of its internal filesystem,
40 * including file and directory permissions, if they have been configured.
41 * <p/>
42 * <b>FakeFtpServer</b> can be fully configured programmatically or within the
43 * <a href="http://www.springframework.org/">Spring Framework</a> or other dependency-injection container.
44 * <p/>
45 * In general the steps for setting up and starting the <b>FakeFtpServer</b> are:
46 * <ol>
47 * <li>Create a new <b>FakeFtpServer</b> instance, and optionally set the server control port.</li>
48 * <li>Create and configure a <b>FileSystem</b>, and attach to the <b>FakeFtpServer</b> instance.</li>
49 * <li>Create and configure one or more <b>UserAccount</b> objects and attach to the <b>FakeFtpServer</b> instance.</li>
50 * </ol>
51 * <h4>Example Code</h4>
52 * <pre><code>
53 * FakeFtpServer fakeFtpServer = new FakeFtpServer();
54 * <p/>
55 * FileSystem fileSystem = new WindowsFakeFileSystem();
56 * fileSystem.add(new DirectoryEntry("c:\\"));
57 * fileSystem.add(new DirectoryEntry("c:\\data"));
58 * fileSystem.add(new FileEntry("c:\\data\\file1.txt", "abcdef 1234567890"));
59 * fileSystem.add(new FileEntry("c:\\data\\run.exe"));
60 * fakeFtpServer.setFileSystem(fileSystem);
61 * <p/>
62 * // Create UserAccount with username, password, home-directory
63 * UserAccount userAccount = new UserAccount("joe", "joe123", "c:\\");
64 * fakeFtpServer.addUserAccounts(userAccount);
65 * <p/>
66 * fakeFtpServer.start();
67 * </code></pre>
68 * <p/>
69 * <h4>Example Code with Permissions</h4>
70 * You can optionally set the permissions and owner/group for each file and directory, as in the following example.
71 * <pre><code>
72 * FileSystem fileSystem = new UnixFakeFileSystem();
73 * DirectoryEntry directoryEntry1 = new DirectoryEntry("/");
74 * directoryEntry1.setPermissions(new Permissions("rwxrwx---"));
75 * directoryEntry1.setOwner("joe");
76 * directoryEntry1.setGroup("dev");
77 * <p/>
78 * DirectoryEntry directoryEntry2 = new DirectoryEntry("/data");
79 * directoryEntry2.setPermissions(Permissions.ALL);
80 * directoryEntry2.setOwner("joe");
81 * directoryEntry2.setGroup("dev");
82 * <p/>
83 * FileEntry fileEntry1 = new FileEntry("/data/file1.txt", "abcdef 1234567890");
84 * fileEntry1.setPermissionsFromString("rw-rw-rw-");
85 * fileEntry1.setOwner("joe");
86 * fileEntry1.setGroup("dev");
87 * <p/>
88 * FileEntry fileEntry2 = new FileEntry("/data/run.exe");
89 * fileEntry2.setPermissionsFromString("rwxrwx---");
90 * fileEntry2.setOwner("mary");
91 * fileEntry2.setGroup("dev");
92 * <p/>
93 * fileSystem.add(directoryEntry1);
94 * fileSystem.add(directoryEntry2);
95 * fileSystem.add(fileEntry1);
96 * fileSystem.add(fileEntry2);
97 * <p/>
98 * FakeFtpServer fakeFtpServer = new FakeFtpServer();
99 * fakeFtpServer.setFileSystem(fileSystem);
100 * <p/>
101 * // Create UserAccount with username, password, home-directory
102 * UserAccount userAccount = new UserAccount("joe", "joe123", "/");
103 * fakeFtpServer.addUserAccounts(userAccount);
104 * <p/>
105 * fakeFtpServer.start();
106 * </code></pre>
107 * <p/>
108 * <h4>FTP Server Control Port</h4>
109 * By default, <b>MockFtpServer</b> binds to the server control port of 21. You can use a different server
110 * control port by setting the the <code>serverControlPort</code> property. This is usually necessary
111 * when running on Unix or some other system where that port number is already in use or cannot be bound
112 * from a user process.
113 * <p/>
114 * <h4>Other Configuration</h4>
115 * The <code>systemName</code> property specifies the value returned by the <code>SYST</code>
116 * command. Note that this is typically used by an FTP client to determine how to parse
117 * system-dependent reply text, such as directory listings. This value defaults to <code>"WINDOWS"</code>.
118 * <p/>
119 * The <code>helpText</code> property specifies a <i>Map</i> of help text replies sent by the
120 * <code>HELP</code> command. The keys in that <i>Map</i> correspond to the command names passed as
121 * parameters to the <code>HELP</code> command. An entry with the key of an empty string ("") indicates the
122 * text used as the default help text when no command name parameter is specified for the <code>HELP</code> command.
123 * <p/>
124 * <h4>FTP Command Reply Text ResourceBundle</h4>
125 * The default text asociated with each FTP command reply code is contained within the
126 * "ReplyText.properties" ResourceBundle file. You can customize these messages by providing a
127 * locale-specific ResourceBundle file on the CLASSPATH, according to the normal lookup rules of
128 * the ResourceBundle class (e.g., "ReplyText_de.properties"). Alternatively, you can
129 * completely replace the ResourceBundle file by calling the calling the
130 * {@link #setReplyTextBaseName(String)} method.
131 *
132 * @author Chris Mair
133 * @version $Revision$ - $Date$
134 */
135public class FakeFtpServer extends AbstractFtpServer implements ServerConfiguration {
136
137    private FileSystem fileSystem;
138    private String systemName = "WINDOWS";
139    private Map helpText = new HashMap();
140    private Map userAccounts = new HashMap();
141
142    public FileSystem getFileSystem() {
143        return fileSystem;
144    }
145
146    public void setFileSystem(FileSystem fileSystem) {
147        this.fileSystem = fileSystem;
148    }
149
150    public String getSystemName() {
151        return systemName;
152    }
153
154    public void setSystemName(String systemName) {
155        this.systemName = systemName;
156    }
157
158    public Map getHelpText() {
159        return helpText;
160    }
161
162    public void setHelpText(Map helpText) {
163        this.helpText = helpText;
164    }
165
166    public FakeFtpServer() {
167        setCommandHandler(CommandNames.ACCT, new AcctCommandHandler());
168        setCommandHandler(CommandNames.ABOR, new AborCommandHandler());
169        setCommandHandler(CommandNames.ALLO, new AlloCommandHandler());
170        setCommandHandler(CommandNames.APPE, new AppeCommandHandler());
171        setCommandHandler(CommandNames.CONNECT, new ConnectCommandHandler());
172        setCommandHandler(CommandNames.CWD, new CwdCommandHandler());
173        setCommandHandler(CommandNames.CDUP, new CdupCommandHandler());
174        setCommandHandler(CommandNames.DELE, new DeleCommandHandler());
175        setCommandHandler(CommandNames.HELP, new HelpCommandHandler());
176        setCommandHandler(CommandNames.LIST, new ListCommandHandler());
177        setCommandHandler(CommandNames.MKD, new MkdCommandHandler());
178        setCommandHandler(CommandNames.MODE, new ModeCommandHandler());
179        setCommandHandler(CommandNames.NLST, new NlstCommandHandler());
180        setCommandHandler(CommandNames.NOOP, new NoopCommandHandler());
181        setCommandHandler(CommandNames.PASS, new PassCommandHandler());
182        setCommandHandler(CommandNames.PASV, new PasvCommandHandler());
183        setCommandHandler(CommandNames.PWD, new PwdCommandHandler());
184        setCommandHandler(CommandNames.PORT, new PortCommandHandler());
185        setCommandHandler(CommandNames.QUIT, new QuitCommandHandler());
186        setCommandHandler(CommandNames.REIN, new ReinCommandHandler());
187        setCommandHandler(CommandNames.REST, new RestCommandHandler());
188        setCommandHandler(CommandNames.RETR, new RetrCommandHandler());
189        setCommandHandler(CommandNames.RMD, new RmdCommandHandler());
190        setCommandHandler(CommandNames.RNFR, new RnfrCommandHandler());
191        setCommandHandler(CommandNames.RNTO, new RntoCommandHandler());
192        setCommandHandler(CommandNames.SITE, new SiteCommandHandler());
193        setCommandHandler(CommandNames.STOR, new StorCommandHandler());
194        setCommandHandler(CommandNames.STOU, new StouCommandHandler());
195        setCommandHandler(CommandNames.STRU, new StruCommandHandler());
196        setCommandHandler(CommandNames.SYST, new SystCommandHandler());
197        setCommandHandler(CommandNames.TYPE, new TypeCommandHandler());
198        setCommandHandler(CommandNames.USER, new UserCommandHandler());
199        setCommandHandler(CommandNames.XPWD, new PwdCommandHandler());
200    }
201
202    /**
203     * Initialize a CommandHandler that has been registered to this server. If the CommandHandler implements
204     * the <code>ServerConfigurationAware</code> interface, then set its <code>ServerConfiguration</code>
205     * property to <code>this</code>.
206     *
207     * @param commandHandler - the CommandHandler to initialize
208     */
209    protected void initializeCommandHandler(CommandHandler commandHandler) {
210        if (commandHandler instanceof ServerConfigurationAware) {
211            ServerConfigurationAware sca = (ServerConfigurationAware) commandHandler;
212            sca.setServerConfiguration(this);
213        }
214    }
215
216    /**
217     * @return the {@link UserAccount}        configured for this server for the specified user name
218     */
219    public UserAccount getUserAccount(String username) {
220        return (UserAccount) userAccounts.get(username);
221    }
222
223    /**
224     * Return the help text for a command or the default help text if no command name is specified
225     *
226     * @param name - the command name; may be empty or null to indicate  a request for the default help text
227     * @return the help text for the named command or the default help text if no name is supplied
228     */
229    public String getHelpText(String name) {
230        String key = name == null ? "" : name;
231        return (String) helpText.get(key);
232    }
233
234    /**
235     * Add a single UserAccount. If an account with the same <code>username</code> already exists,
236     * it will be replaced.
237     *
238     * @param userAccount - the UserAccount to add
239     */
240    public void addUserAccount(UserAccount userAccount) {
241        userAccounts.put(userAccount.getUsername(), userAccount);
242    }
243
244    /**
245     * Add the UserAccount objects in the <code>userAccountList</code> to the set of UserAccounts.
246     *
247     * @param userAccountList - the List of UserAccount objects to add
248     */
249    public void setUserAccounts(List userAccountList) {
250        for (int i = 0; i < userAccountList.size(); i++) {
251            UserAccount userAccount = (UserAccount) userAccountList.get(i);
252            userAccounts.put(userAccount.getUsername(), userAccount);
253        }
254    }
255
256}