AbstractFtpServer.java revision 35db51a87c51dc0c4bbb5bc1eaf1a283b68a44b5
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 * ({@link 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 e.printStackTrace(); 212 throw new MockFtpServerException(e); 213 } 214 catch (InterruptedException e) { 215 e.printStackTrace(); 216 throw new MockFtpServerException(e); 217 } 218 LOG.info("Server stopped."); 219 } 220 } 221 222 /** 223 * Stop this server instance and wait for it to terminate. 224 */ 225 public void stop() { 226 227 LOG.trace("Stopping the server..."); 228 terminate = true; 229 230 try { 231 if (serverThread != null) { 232 serverThread.join(); 233 } 234 } 235 catch (InterruptedException e) { 236 e.printStackTrace(); 237 throw new MockFtpServerException(e); 238 } 239 } 240 241 /** 242 * Return the CommandHandler defined for the specified command name 243 * 244 * @param name - the command name 245 * @return the CommandHandler defined for name 246 */ 247 public CommandHandler getCommandHandler(String name) { 248 return (CommandHandler) commandHandlers.get(Command.normalizeName(name)); 249 } 250 251 /** 252 * Override the default CommandHandlers with those in the specified Map of 253 * commandName>>CommandHandler. This will only override the default CommandHandlers 254 * for the keys in <code>commandHandlerMapping</code>. All other default CommandHandler 255 * mappings remain unchanged. 256 * 257 * @param commandHandlerMapping - the Map of commandName->CommandHandler; these override the defaults 258 * @throws org.mockftpserver.core.util.AssertFailedException 259 * - if the commandHandlerMapping is null 260 */ 261 public void setCommandHandlers(Map commandHandlerMapping) { 262 Assert.notNull(commandHandlerMapping, "commandHandlers"); 263 for (Iterator iter = commandHandlerMapping.keySet().iterator(); iter.hasNext();) { 264 String commandName = (String) iter.next(); 265 setCommandHandler(commandName, (CommandHandler) commandHandlerMapping.get(commandName)); 266 } 267 } 268 269 /** 270 * Set the CommandHandler for the specified command name. If the CommandHandler implements 271 * the {@link org.mockftpserver.core.command.ReplyTextBundleAware} interface and its <code>replyTextBundle</code> attribute 272 * is null, then set its <code>replyTextBundle</code> to the <code>replyTextBundle</code> of 273 * this StubFtpServer. 274 * 275 * @param commandName - the command name to which the CommandHandler will be associated 276 * @param commandHandler - the CommandHandler 277 * @throws org.mockftpserver.core.util.AssertFailedException 278 * - if the commandName or commandHandler is null 279 */ 280 public void setCommandHandler(String commandName, CommandHandler commandHandler) { 281 Assert.notNull(commandName, "commandName"); 282 Assert.notNull(commandHandler, "commandHandler"); 283 commandHandlers.put(Command.normalizeName(commandName), commandHandler); 284 initializeCommandHandler(commandHandler); 285 } 286 287 /** 288 * Set the reply text ResourceBundle to a new ResourceBundle with the specified base name, 289 * accessible on the CLASSPATH. See {@link java.util.ResourceBundle#getBundle(String)}. 290 * 291 * @param baseName - the base name of the resource bundle, a fully qualified class name 292 */ 293 public void setReplyTextBaseName(String baseName) { 294 replyTextBundle = ResourceBundle.getBundle(baseName); 295 } 296 297 /** 298 * Return the ReplyText ResourceBundle. Set the bundle through the {@link #setReplyTextBaseName(String)} method. 299 * 300 * @return the reply text ResourceBundle 301 */ 302 public ResourceBundle getReplyTextBundle() { 303 return replyTextBundle; 304 } 305 306 /** 307 * Set the port number to which the server control connection socket will bind. The default value is 21. 308 * 309 * @param serverControlPort - the port number for the server control connection ServerSocket 310 */ 311 public void setServerControlPort(int serverControlPort) { 312 this.serverControlPort = serverControlPort; 313 } 314 315 //------------------------------------------------------------------------- 316 // Internal Helper Methods 317 //------------------------------------------------------------------------- 318 319 /** 320 * Return true if this server is fully shutdown -- i.e., there is no active (alive) threads and 321 * all sockets are closed. This method is intended for testing only. 322 * 323 * @return true if this server is fully shutdown 324 */ 325 public boolean isShutdown() { 326 boolean shutdown = !serverThread.isAlive() && serverSocket.isClosed(); 327 328 for (Iterator iter = sessions.keySet().iterator(); iter.hasNext();) { 329 SessionInfo sessionInfo = (SessionInfo) iter.next(); 330 shutdown = shutdown && sessionInfo.socket.isClosed() && !sessionInfo.thread.isAlive(); 331 } 332 return shutdown; 333 } 334 335 /** 336 * Return true if this server has started -- i.e., there is an active (alive) server threads 337 * and non-null server socket. This method is intended for testing only. 338 * 339 * @return true if this server has started 340 */ 341 public boolean isStarted() { 342 return serverThread != null && serverThread.isAlive() && serverSocket != null; 343 } 344 345 //------------------------------------------------------------------------------------ 346 // Abstract method declarations 347 //------------------------------------------------------------------------------------ 348 349 /** 350 * Initialize a CommandHandler that has been registered to this server. What "initialization" 351 * means is dependent on the subclass implementation. 352 * 353 * @param commandHandler - the CommandHandler to initialize 354 */ 355 protected abstract void initializeCommandHandler(CommandHandler commandHandler); 356 357}