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