AbstractFtpServer.java revision 2076c899605689976d8f9b3d012817e4931d535f
1/*
2 * Copyright 2007 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.core.server;
17
18import org.apache.log4j.Logger;
19import org.mockftpserver.core.MockFtpServerException;
20import org.mockftpserver.core.command.Command;
21import org.mockftpserver.core.command.CommandHandler;
22import org.mockftpserver.core.session.DefaultSession;
23import org.mockftpserver.core.session.Session;
24import org.mockftpserver.core.socket.DefaultServerSocketFactory;
25import org.mockftpserver.core.socket.ServerSocketFactory;
26import org.mockftpserver.core.util.Assert;
27
28import java.io.IOException;
29import java.net.ServerSocket;
30import java.net.Socket;
31import java.net.SocketTimeoutException;
32import java.util.HashMap;
33import java.util.Iterator;
34import java.util.Map;
35import java.util.ResourceBundle;
36
37/**
38 * <b>StubFtpServer</b> is the top-level class for a "stub" implementation of an FTP Server,
39 * suitable for testing FTP client code or standing in for a live FTP server. It supports
40 * the main FTP commands by defining handlers for each of the corresponding low-level FTP
41 * server commands (e.g. RETR, DELE, LIST). These handlers implement the {@link org.mockftpserver.core.command.CommandHandler}
42 * interface.
43 * <p/>
44 * <b>StubFtpServer</b> works out of the box with default command handlers that return
45 * success reply codes and empty data (for retrieved files, directory listings, etc.).
46 * The command handler for any command can be easily configured to return custom data
47 * or reply codes. Or it can be replaced with a custom {@link org.mockftpserver.core.command.CommandHandler}
48 * implementation. This allows simulation of a complete range of both success and
49 * failure scenarios. The command handlers can also be interrogated to verify command
50 * invocation data such as command parameters and timestamps.
51 * <p/>
52 * <b>StubFtpServer</b> can be fully configured programmatically or within a Spring Framework
53 * (http://www.springframework.org/) or similar container.
54 * <p/>
55 * <h4>Starting the StubFtpServer</h4>
56 * Here is how to start the <b>StubFtpServer</b> with the default configuration.
57 * <pre><code>
58 * StubFtpServer stubFtpServer = new StubFtpServer();
59 * stubFtpServer.start();
60 * </code></pre>
61 * <p/>
62 * <h4>Retrieving Command Handlers</h4>
63 * You can retrieve the existing {@link org.mockftpserver.core.command.CommandHandler} defined for an FTP server command
64 * by calling the {@link #getCommandHandler(String)} method, passing in the FTP server
65 * command name. For example:
66 * <pre><code>
67 * PwdCommandHandler pwdCommandHandler = (PwdCommandHandler) stubFtpServer.getCommandHandler("PWD");
68 * </code></pre>
69 * <p/>
70 * <h4>Replacing Command Handlers</h4>
71 * You can replace the existing {@link org.mockftpserver.core.command.CommandHandler} defined for an FTP server command
72 * by calling the {@link #setCommandHandler(String, org.mockftpserver.core.command.CommandHandler)} method, passing
73 * in the FTP server command name and {@link org.mockftpserver.core.command.CommandHandler} instance. For example:
74 * <pre><code>
75 * PwdCommandHandler pwdCommandHandler = new PwdCommandHandler();
76 * pwdCommandHandler.setDirectory("some/dir");
77 * stubFtpServer.setCommandHandler("PWD", pwdCommandHandler);
78 * </code></pre>
79 * You can also replace multiple command handlers at once by using the {@link #setCommandHandlers(java.util.Map)}
80 * method. That is especially useful when configuring the server through the <b>Spring Framework</b>.
81 * <h4>FTP Command Reply Text ResourceBundle</h4>
82 * <p/>
83 * The default text asociated with each FTP command reply code is contained within the
84 * "ReplyText.properties" ResourceBundle file. You can customize these messages by providing a
85 * locale-specific ResourceBundle file on the CLASSPATH, according to the normal lookup rules of
86 * the ResourceBundle class (e.g., "ReplyText_de.properties"). Alternatively, you can
87 * completely replace the ResourceBundle file by calling the calling the
88 * {@link #setReplyTextBaseName(String)} method.
89 *
90 * @author Chris Mair
91 * @version $Revision$ - $Date$
92 */
93public abstract class AbstractFtpServer implements Runnable {
94
95    /**
96     * Default basename for reply text ResourceBundle
97     */
98    public static final String REPLY_TEXT_BASENAME = "ReplyText";
99    private static final int DEFAULT_SERVER_CONTROL_PORT = 21;
100
101    protected Logger LOG = Logger.getLogger(getClass());
102
103    // Simple value object that holds the socket and thread for a single session
104    private static class SessionInfo {
105        private Socket socket;
106        private Thread thread;
107    }
108
109    private ServerSocketFactory serverSocketFactory = new DefaultServerSocketFactory();
110    private ServerSocket serverSocket = null;
111    private ResourceBundle replyTextBundle;
112    private volatile boolean terminate = false;
113    private Map commandHandlers;
114    private Thread serverThread;
115    private int serverControlPort = DEFAULT_SERVER_CONTROL_PORT;
116    private final Object startLock = new Object();
117
118    // Map of Session -> SessionInfo
119    private Map sessions = new HashMap();
120
121    /**
122     * Create a new instance. Initialize the default command handlers and
123     * reply text ResourceBundle.
124     */
125    public AbstractFtpServer() {
126        replyTextBundle = ResourceBundle.getBundle(REPLY_TEXT_BASENAME);
127        commandHandlers = new HashMap();
128    }
129
130    /**
131     * Start a new Thread for this server instance
132     */
133    public void start() {
134        serverThread = new Thread(this);
135
136        synchronized (startLock) {
137            try {
138                // Start here in case server thread runs faster than main thread.
139                // See https://sourceforge.net/tracker/?func=detail&atid=1006533&aid=1925590&group_id=208647
140                serverThread.start();
141
142                // Wait until the server thread is initialized
143                startLock.wait();
144            }
145            catch (InterruptedException e) {
146                e.printStackTrace();
147                throw new MockFtpServerException(e);
148            }
149        }
150    }
151
152    /**
153     * The logic for the server thread
154     *
155     * @see Runnable#run()
156     */
157    public void run() {
158        try {
159            LOG.info("Starting the server on port " + serverControlPort);
160            serverSocket = serverSocketFactory.createServerSocket(serverControlPort);
161
162            // Notify to allow the start() method to finish and return
163            synchronized (startLock) {
164                startLock.notify();
165            }
166
167            serverSocket.setSoTimeout(500);
168            while (!terminate) {
169                try {
170                    Socket clientSocket = serverSocket.accept();
171                    LOG.info("Connection accepted from host " + clientSocket.getInetAddress());
172
173                    DefaultSession session = new DefaultSession(clientSocket, commandHandlers);
174                    Thread sessionThread = new Thread(session);
175                    sessionThread.start();
176
177                    SessionInfo sessionInfo = new SessionInfo();
178                    sessionInfo.socket = clientSocket;
179                    sessionInfo.thread = sessionThread;
180                    sessions.put(session, sessionInfo);
181                }
182                catch (SocketTimeoutException socketTimeoutException) {
183                    LOG.trace("Socket accept() timeout");
184                }
185            }
186        }
187        catch (IOException e) {
188            LOG.error("Error", e);
189        }
190        finally {
191
192            LOG.debug("Cleaning up server...");
193
194            try {
195                if (serverSocket != null) {
196                    serverSocket.close();
197                }
198
199                for (Iterator iter = sessions.keySet().iterator(); iter.hasNext();) {
200                    Session session = (Session) iter.next();
201                    SessionInfo sessionInfo = (SessionInfo) sessions.get(session);
202                    session.close();
203                    sessionInfo.thread.join(500L);
204                    Socket sessionSocket = sessionInfo.socket;
205                    if (sessionSocket != null) {
206                        sessionSocket.close();
207                    }
208                }
209            }
210            catch (IOException e) {
211                LOG.error("Error cleaning up server", e);
212            }
213            catch (InterruptedException e) {
214                LOG.error("Error cleaning up server", e);
215            }
216            LOG.info("Server stopped.");
217        }
218    }
219
220    /**
221     * Stop this server instance and wait for it to terminate.
222     */
223    public void stop() {
224
225        LOG.trace("Stopping the server...");
226        terminate = true;
227
228        try {
229            if (serverThread != null) {
230                serverThread.join();
231            }
232        }
233        catch (InterruptedException e) {
234            e.printStackTrace();
235            throw new MockFtpServerException(e);
236        }
237    }
238
239    /**
240     * Return the CommandHandler defined for the specified command name
241     *
242     * @param name - the command name
243     * @return the CommandHandler defined for name
244     */
245    public CommandHandler getCommandHandler(String name) {
246        return (CommandHandler) commandHandlers.get(Command.normalizeName(name));
247    }
248
249    /**
250     * Override the default CommandHandlers with those in the specified Map of
251     * commandName>>CommandHandler. This will only override the default CommandHandlers
252     * for the keys in <code>commandHandlerMapping</code>. All other default CommandHandler
253     * mappings remain unchanged.
254     *
255     * @param commandHandlerMapping - the Map of commandName->CommandHandler; these override the defaults
256     * @throws org.mockftpserver.core.util.AssertFailedException
257     *          - if the commandHandlerMapping is null
258     */
259    public void setCommandHandlers(Map commandHandlerMapping) {
260        Assert.notNull(commandHandlerMapping, "commandHandlers");
261        for (Iterator iter = commandHandlerMapping.keySet().iterator(); iter.hasNext();) {
262            String commandName = (String) iter.next();
263            setCommandHandler(commandName, (CommandHandler) commandHandlerMapping.get(commandName));
264        }
265    }
266
267    /**
268     * Set the CommandHandler for the specified command name. If the CommandHandler implements
269     * the {@link org.mockftpserver.core.command.ReplyTextBundleAware} interface and its <code>replyTextBundle</code> attribute
270     * is null, then set its <code>replyTextBundle</code> to the <code>replyTextBundle</code> of
271     * this StubFtpServer.
272     *
273     * @param commandName    - the command name to which the CommandHandler will be associated
274     * @param commandHandler - the CommandHandler
275     * @throws org.mockftpserver.core.util.AssertFailedException
276     *          - if the commandName or commandHandler is null
277     */
278    public void setCommandHandler(String commandName, CommandHandler commandHandler) {
279        Assert.notNull(commandName, "commandName");
280        Assert.notNull(commandHandler, "commandHandler");
281        commandHandlers.put(Command.normalizeName(commandName), commandHandler);
282        initializeCommandHandler(commandHandler);
283    }
284
285    /**
286     * Set the reply text ResourceBundle to a new ResourceBundle with the specified base name,
287     * accessible on the CLASSPATH. See {@link java.util.ResourceBundle#getBundle(String)}.
288     *
289     * @param baseName - the base name of the resource bundle, a fully qualified class name
290     */
291    public void setReplyTextBaseName(String baseName) {
292        replyTextBundle = ResourceBundle.getBundle(baseName);
293    }
294
295    /**
296     * Return the ReplyText ResourceBundle. Set the bundle through the  {@link #setReplyTextBaseName(String)}  method.
297     *
298     * @return the reply text ResourceBundle
299     */
300    public ResourceBundle getReplyTextBundle() {
301        return replyTextBundle;
302    }
303
304    /**
305     * Set the port number to which the server control connection socket will bind. The default value is 21.
306     *
307     * @param serverControlPort - the port number for the server control connection ServerSocket
308     */
309    public void setServerControlPort(int serverControlPort) {
310        this.serverControlPort = serverControlPort;
311    }
312
313    //-------------------------------------------------------------------------
314    // Internal Helper Methods
315    //-------------------------------------------------------------------------
316
317    /**
318     * Return true if this server is fully shutdown -- i.e., there is no active (alive) threads and
319     * all sockets are closed. This method is intended for testing only.
320     *
321     * @return true if this server is fully shutdown
322     */
323    public boolean isShutdown() {
324        boolean shutdown = !serverThread.isAlive() && serverSocket.isClosed();
325
326        for (Iterator iter = sessions.keySet().iterator(); iter.hasNext();) {
327            SessionInfo sessionInfo = (SessionInfo) iter.next();
328            shutdown = shutdown && sessionInfo.socket.isClosed() && !sessionInfo.thread.isAlive();
329        }
330        return shutdown;
331    }
332
333    /**
334     * Return true if this server has started -- i.e., there is an active (alive) server threads
335     * and non-null server socket. This method is intended for testing only.
336     *
337     * @return true if this server has started
338     */
339    public boolean isStarted() {
340        return serverThread != null && serverThread.isAlive() && serverSocket != null;
341    }
342
343    //------------------------------------------------------------------------------------
344    // Abstract method declarations
345    //------------------------------------------------------------------------------------
346
347    /**
348     * Initialize a CommandHandler that has been registered to this server. What "initialization"
349     * means is dependent on the subclass implementation.
350     *
351     * @param commandHandler - the CommandHandler to initialize
352     */
353    protected abstract void initializeCommandHandler(CommandHandler commandHandler);
354
355}