/*
* pjftp FTP server.
* Copyright (C) 2012 Dmitriy Simbiriatin <dmitriy.simbiriatin@gmail.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ds.pjftp.main;
import ds.pjftp.utils.NotNull;
import java.net.Socket;
import java.io.IOException;
import java.io.BufferedReader;
import ds.pjftp.command.Command;
import ds.pjftp.command.Commands;
import ds.pjftp.log.LogWrapper;
import ds.pjftp.settings.ServerSettings;
import ds.pjftp.settings.SettingsHolder;
import ds.pjftp.utils.IOUtils;
/**
* This class interprets client's requests and invokes appropriate
* handler for specified ftp command.
*/
public class Interpreter implements Runnable {
private final LogWrapper logger = LogWrapper.get(Interpreter.class.getName());
private final ClientSession session;
/**
* Constructs Interpreter object.
* @param client client to be handled.
* @throws IOException if failed to initialize client's session.
*/
public Interpreter(@NotNull final Socket client) throws IOException {
session = new ClientSession(client);
}
public void run() {
try {
interpretClientRequest();
} catch (Exception ex) {
logger.error("Failed to process client's request: {0}", ex);
} finally {
IOUtils.close(session.getClient());
}
}
/**
* Interprets client's request and invokes appropriate handler.
*/
private void interpretClientRequest() throws IOException {
final ServerSettings settings = SettingsHolder.getInstance().getSettings();
session.replyWithSpace(220, settings.getWelcomeMessage());
ClientRequest request = null;
while ((request = session.readRequest()) != null) {
final String reqCmd = request.getCommand();
final String reqArg = request.getArgument();
final Command command = Commands.get(reqCmd);
if (command != null) {
command.invoke(session, reqArg);
} else {
session.replyWithSpace(500, "Command {} isn't supported", reqCmd);
}
session.setLastRequest(request);
}
}
}