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