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