diff --git a/FTPGui/build.gradle b/FTPGui/build.gradle new file mode 100644 index 0000000..a6c21b3 --- /dev/null +++ b/FTPGui/build.gradle @@ -0,0 +1,27 @@ +plugins { + id 'java-library' +} + +dependencies { + api 'org.apache.commons:commons-math3:3.6.1' + + implementation 'com.google.guava:guava:23.0' + + compile group: 'org.jetbrains', name: 'annotations', version: '15.0' + compile group: 'commons-io', name: 'commons-io', version: '2.6' + + testCompile group: 'org.hamcrest', name: 'hamcrest-all', version: '1.3' + testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: '5.1.0' + testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-params', version: '5.0.0-M4' + + testImplementation 'junit:junit:4.12' +} + +repositories { + jcenter() +} + +task wrapper(type: Wrapper) { + description = 'Generates gradlew[.bat] scripts' + gradleVersion = '4.6' +} \ No newline at end of file diff --git a/FTPGui/gradle/wrapper/gradle-wrapper.jar b/FTPGui/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..91ca28c Binary files /dev/null and b/FTPGui/gradle/wrapper/gradle-wrapper.jar differ diff --git a/FTPGui/gradle/wrapper/gradle-wrapper.properties b/FTPGui/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..16d2805 --- /dev/null +++ b/FTPGui/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-4.7-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/FTPGui/gradlew b/FTPGui/gradlew new file mode 100755 index 0000000..2c9b727 --- /dev/null +++ b/FTPGui/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:utf=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/FTPGui/gradlew.bat b/FTPGui/gradlew.bat new file mode 100644 index 0000000..f955316 --- /dev/null +++ b/FTPGui/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/FTPGui/settings.gradle b/FTPGui/settings.gradle new file mode 100644 index 0000000..5e1a3a9 --- /dev/null +++ b/FTPGui/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'FTPGUI' + diff --git a/FTPGui/src/main/java/FTPApplication.java b/FTPGui/src/main/java/FTPApplication.java new file mode 100644 index 0000000..c3b4bf4 --- /dev/null +++ b/FTPGui/src/main/java/FTPApplication.java @@ -0,0 +1,11 @@ +import java.io.IOException; + +@SuppressWarnings("unused") +public class FTPApplication { + + private static void init(final String url) throws IOException { + final FTPWindow window = new FTPWindow(url); + window.setVisible(true); + } + +} diff --git a/FTPGui/src/main/java/FTPWindow.java b/FTPGui/src/main/java/FTPWindow.java new file mode 100644 index 0000000..4a32582 --- /dev/null +++ b/FTPGui/src/main/java/FTPWindow.java @@ -0,0 +1,139 @@ +import impl.FTPClient; +import impl.FTPFile; + +import javax.swing.*; +import javax.swing.border.EmptyBorder; +import javax.swing.tree.*; +import java.awt.*; +import java.awt.event.*; +import java.io.File; +import java.io.IOException; +import java.util.*; +import java.util.List; + +import static javax.swing.JOptionPane.showMessageDialog; + +class FTPWindow extends JFrame { + + private final FTPClient client; + private TreePath pathToFile; + + FTPWindow(final String url) throws IOException { + super("FTP"); + client = new FTPClient(url); + setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + setResizable(false); + + final JPanel mainPanel = new JPanel(); + mainPanel.setBorder(new EmptyBorder(20, 20, 20, 20)); + mainPanel.setLayout(new BorderLayout()); + + final JTree tree = initTree(); + tree.setEditable(false); + tree.addKeyListener(new KeyAdapter() { + @Override + public void keyPressed(final KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_ENTER) { + downloadFile(pathToFile); + } + } + }); + + tree.addTreeSelectionListener(e -> pathToFile = e.getPath()); + mainPanel.add(tree); + + final JButton downloadButton = new JButton("Download"); + downloadButton.addActionListener(e -> downloadFile(pathToFile)); + mainPanel.add(downloadButton, BorderLayout.SOUTH); + + setContentPane(mainPanel); + setSize(700, 700); + } + + private void downloadFile(final TreePath path) { + if (path == null) { + showMessageDialog(null, "No file chosen"); + return; + } + final FTPFile targetFile = + (FTPFile) ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); + if (targetFile.isDirectory()) { + showMessageDialog(null, "Unable to download directory"); + return; + } + final StringJoiner joiner = new StringJoiner(File.separator); + for (final Object pathFile : path.getPath()) { + joiner.add(pathFile.toString()); + } + + final JFileChooser chooser = new JFileChooser(); + chooser.setCurrentDirectory(new File(".")); + chooser.setDialogTitle("Chose target location"); + chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); + + chooser.setAcceptAllFileFilterUsed(true); + chooser.setApproveButtonText("Save"); + + if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) { + final File destination = chooser.getSelectedFile(); + try { + client.get(joiner.toString(), + destination.toString() + File.separator + targetFile.name()); + } catch (final IOException e) { + showMessageDialog(null, + "Unable to download file. Canceled with error: " + e.getMessage()); + } + } + } + + private JTree initTree() { + final DefaultMutableTreeNode top = + new DefaultMutableTreeNode(new FTPFile("./", true)); + createInnerFiles(top); + + final JTree tree = new JTree(top); + tree.getSelectionModel().setSelectionMode + (TreeSelectionModel.SINGLE_TREE_SELECTION); + + return tree; + } + + /** + * The method adds all inner files of the directory to the tree. + * + * @param root target node + */ + private void createInnerFiles(final DefaultMutableTreeNode root) { + final String url = getURL(root); + List files = Collections.emptyList(); + try { + files = client.list(url); + } catch (final IOException e) { + showMessageDialog(null, + "Fatal error happened. Application will be closed with error: " + e.getMessage()); + System.exit(1); + } + for (final FTPFile file : files) { + final DefaultMutableTreeNode node = + new DefaultMutableTreeNode(file, file.isDirectory()); + root.add(node); + if (file.isDirectory()) { + createInnerFiles(node); + } + } + } + + /** + * The method get path to node. + * */ + private static String getURL(final DefaultMutableTreeNode node) { + final StringJoiner joiner = new StringJoiner(File.separator); + final TreeNode[] path = node.getPath(); + for (final TreeNode pathNode : path) { + joiner.add(pathNode.toString()); + } + return joiner.toString(); + } +} + + diff --git a/FTPGui/src/main/java/abstractServer/AbstractBlockingServer.java b/FTPGui/src/main/java/abstractServer/AbstractBlockingServer.java new file mode 100644 index 0000000..31fcd3b --- /dev/null +++ b/FTPGui/src/main/java/abstractServer/AbstractBlockingServer.java @@ -0,0 +1,146 @@ +package abstractServer; + +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; +import java.util.TreeSet; + +@SuppressWarnings("unused") +public abstract class AbstractBlockingServer implements Server { + + @NotNull + private final ServerSocket server; + private final int port; + + @NotNull + private final Thread mainThread; + + private volatile boolean ceaseWorking; + private volatile boolean serverClosed; + + private final Set sessions = new TreeSet<>(); + private int sessionsProcessed = 0; + private final List errors = new ArrayList<>(); + + protected AbstractBlockingServer(final int port) throws IOException { + server = new ServerSocket(port); + this.port = port; + mainThread = new Thread(this::work); + mainThread.start(); + } + + /** + * The method shuts down server. + *

+ * Server will not accept connections anymore after this method was executed. + * Every present session will be closed. + * + * This is blocking method. You may interrupt this method for your own risk. + * In that case, it is not guaranteed that every port will be released by the time + * of the method end. + */ + @Override + public synchronized void shutDown() { + if (ceaseWorking || serverClosed) { + return; + } + ceaseWorking = true; + try { + server.close(); + mainThread.join(); + } catch (@NotNull final IOException e) { + errors.add(e); + } catch (@NotNull final InterruptedException e) { // If we do not want to wait for shutdown + // do nothing + } + + } + + /** + * This method checks if any error occurred. + * + * @return true if any error occurred during work and false otherwise. + */ + public boolean anyErrorOccurred() { + return errors.size() != 0; + } + + /** + * Method to track all errors, occurred during work. + * + * @return list of occurred errors. + */ + @NotNull + public List getErrors() { + return errors; + } + + private void work() { + System.out.println("Server was initialized on port " + port); + + // working until error or shutdown + while (!ceaseWorking) { + final Socket socket; + try { + socket = server.accept(); // must be closed by session + System.out.println("New connection on port " + socket.getPort()); + final Session session = newSession(socket, sessionsProcessed++); + handleSession(session); + } catch (@NotNull final IOException e) { + if (e instanceof SocketException && ceaseWorking) { + break; // server was turned off + } + errors.add(e); // Shutdown if any error occurred + break; + } + } + + + // shutting down server if error happened + if (!server.isClosed()) { + try { + server.close(); + } catch (@NotNull final IOException e) { + errors.add(e); // store all exceptions + } + } + + // closing current connections + closeSessions(); + + serverClosed = true; + System.out.println("Server was shut down"); + } + + @Override + public void closeSession(@NotNull final Session session) { + sessions.remove(session); + session.close(); + } + + protected abstract Session newSession(final Socket socket, int number); + + private void closeSessions() { + for (final Session session : sessions) { + session.close(); + } + } + + private void handleSession(@NotNull final Session session) { + sessions.add(session); + session.run(); // starts session + } +} + + + + + + + diff --git a/FTPGui/src/main/java/abstractServer/AbstractBlockingSession.java b/FTPGui/src/main/java/abstractServer/AbstractBlockingSession.java new file mode 100644 index 0000000..6af133e --- /dev/null +++ b/FTPGui/src/main/java/abstractServer/AbstractBlockingSession.java @@ -0,0 +1,141 @@ +package abstractServer; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.ArrayList; +import java.util.List; +import java.util.concurrent.Executor; +import java.util.concurrent.Executors; + +/** + * Abstract class to process one client connection. + * + * By default creates threads to process reading and writing. Every task from the client will + * be added to the ThreadPool. + * + * Also this class takes socket to work with as an input parameter, therefore this class + * must close the socket when it is not needed anymore (on {@link Session#close()} method call). + */ +public abstract class AbstractBlockingSession implements Session { + + private final int id; + @NotNull + private final Socket socket; + private final Server server; + + @NotNull + private final Executor executor; + private DataOutputStream os; + + private final List errors = new ArrayList<>(); + + protected AbstractBlockingSession(final Socket socket, final int id, final Server server) { + this.socket = socket; + this.id = id; + this.server = server; + executor = Executors.newSingleThreadExecutor(); + + try { + os = new DataOutputStream(socket.getOutputStream()); + } catch (@NotNull final IOException e) { + closeSession(e); + } + } + + protected void closeSession(@Nullable final Exception e) { + if (e != null) { + errors.add(e); + } + server.closeSession(this); + } + + // all docs inherited from Session interface + @Override + public void run() { + new Thread(this::processRead).start(); + } + + @Override + public int id() { + return id; + } + + @Override + public void close() { + // we need two block in case of error happened in one of them + try { + os.close(); + } catch (@NotNull final IOException e) { + errors.add(e); + e.printStackTrace(); + } + + try { + socket.close(); + } catch (@NotNull final IOException e) { + errors.add(e); + e.printStackTrace(); + } + } + + @Override + public boolean anyErrorOccurred() { + return errors.size() != 0; + } + + @NotNull + @Override + public List getErrors() { + return errors; + } + + protected void sendToClient(@NotNull final byte[] buf) { + executor.execute(() -> { + try { + os.write(buf); + os.flush(); + } catch (@NotNull final IOException e) { + closeSession(e); + } + }); + } + + protected void sendToClient(final long x) { + executor.execute(() -> { + try { + os.writeLong(x); + os.flush(); + } catch (@NotNull final IOException e) { + closeSession(e); + } + }); + } + + @SuppressWarnings("SameParameterValue") + protected void sendToClient(@NotNull final byte[] buf, final int offset, final int length) { + executor.execute(() -> { + try { + os.write(buf, offset, length); + os.flush(); + } catch (@NotNull final IOException e) { + closeSession(e); + } + }); + } + + private void processRead() { + try (final DataInputStream is = new DataInputStream(socket.getInputStream())) { + processInput(is); + } catch (@NotNull final IOException e) { + closeSession(e); + } + } + + protected abstract void processInput(final DataInputStream is) throws IOException; + +} diff --git a/FTPGui/src/main/java/abstractServer/Server.java b/FTPGui/src/main/java/abstractServer/Server.java new file mode 100644 index 0000000..76216bd --- /dev/null +++ b/FTPGui/src/main/java/abstractServer/Server.java @@ -0,0 +1,19 @@ +package abstractServer; + +/** + * Server interface. Might have different architectures. + */ +public interface Server { + + /** + * Turns off the server. It is required, that any implementation releases + + * every port, used by server. + */ + void shutDown(); + + /** + * Call this method to close one exact session. + */ + void closeSession(Session session); +} diff --git a/FTPGui/src/main/java/abstractServer/Session.java b/FTPGui/src/main/java/abstractServer/Session.java new file mode 100644 index 0000000..d02ff12 --- /dev/null +++ b/FTPGui/src/main/java/abstractServer/Session.java @@ -0,0 +1,57 @@ +package abstractServer; + +import org.jetbrains.annotations.NotNull; + +import java.io.Closeable; +import java.util.Collections; +import java.util.List; + +/** + * This interface provides session methods to work with one exact client. + */ +@SuppressWarnings("unused") +public interface Session extends Comparable, Closeable { + + /** + * Id is required to implement comparable method, therefore server might + * be able to store sessions in set. + * + * @return session id + */ + int id(); + + /** + * The method must be used to close all resources, such as sockets, Readers e.t.c. + */ + @Override + void close(); + + @Override + default int compareTo(@NotNull final Session o) { + return id() - o.id(); + } + + /** + * Starts to process the session. For example, this method might start reading + * and writing threads. + */ + void run(); + + /** + * This method checks if any error occurred. + * + * @return true if any error occurred during work and false otherwise. + */ + default boolean anyErrorOccurred() { + return false; + } + + /** + * Method to track all errors, occurred during work. + * + * @return list of occurred errors. + */ + default List getErrors() { + return Collections.emptyList(); + } +} diff --git a/FTPGui/src/main/java/impl/FTPClient.java b/FTPGui/src/main/java/impl/FTPClient.java new file mode 100644 index 0000000..3484f74 --- /dev/null +++ b/FTPGui/src/main/java/impl/FTPClient.java @@ -0,0 +1,108 @@ +package impl; + +import org.jetbrains.annotations.NotNull; + +import java.io.*; +import java.net.Socket; +import java.util.ArrayList; +import java.util.LinkedList; +import java.util.List; + +/** + * This class provides methods to work with impl.FTPServer. These are: + * + * {@link FTPClient#list(String)} -- prints all files in the target directory. + * + * {@link FTPClient#get(String, String)} -- downloads and saves file from the + * server to the target file. + */ +@SuppressWarnings({"unused", "WeakerAccess"}) +public class FTPClient { + + private final static int BUF_SIZE = 2048; + + @NotNull + final private DataOutputStream os; + @NotNull + final private DataInputStream is; + + /** + * Creates new client, that connected to the impl.FTPServer. + * + * @param url servers url. + * @param port port to connect. + * @throws IOException if any IOException occurred. + */ + public FTPClient(final String url, final int port) throws IOException { + final Socket socket = new Socket(url, port); + os = new DataOutputStream(socket.getOutputStream()); + is = new DataInputStream(socket.getInputStream()); + } + + /** + * Creates new client, that connected to the impl.FTPServer. + * + * @param url servers url. + * @throws IOException if any IOException occurred. + */ + public FTPClient(final String url) throws IOException { + this(url, FTPServer.DEFAULT_PORT); + } + + /** + * Prints list of all files (including folders), inside the source folder. + * + * Also for every file prints whether the file is a directory or not. + * + * @param source target folder. + * @throws IOException if any IOException occurred. + */ + public List list(@NotNull final String source) throws IOException { + os.writeInt(1); + os.writeUTF(source); + os.flush(); + + final List list = new LinkedList<>(); + + final int number = is.readInt(); + for (int i = 0; i < number; i++) { + final String name = is.readUTF(); + final boolean isFolder = is.readBoolean(); + final FTPFile file = new FTPFile(name, isFolder); + list.add(file); + } + return list; + } + + /** + * Downloads file from the server to the file with specified name. If file with + * the given name already exists, FileAlreadyExistsException will be thrown. + * + * @param source target file. + * @param destination path, to save file. + * @throws IOException if any IOException occurred. + */ + public void get(@NotNull final String source, @NotNull final String destination) throws IOException { + os.writeInt(2); + os.writeUTF(source); + os.flush(); + + final File file = new File(destination); + if (!file.createNewFile()) { + throw new FileAlreadyExistsException(); + } + final byte[] buf = new byte[BUF_SIZE]; + try (final FileOutputStream os = new FileOutputStream(file)) { + final long size = is.readLong(); + int readSize = 0; + int bytesRead; + while (readSize != size) { + bytesRead = is.read(buf); + readSize += bytesRead; + os.write(buf, 0, bytesRead); + } + } + } + + private class FileAlreadyExistsException extends RuntimeException {} +} diff --git a/FTPGui/src/main/java/impl/FTPFile.java b/FTPGui/src/main/java/impl/FTPFile.java new file mode 100644 index 0000000..e4a7b73 --- /dev/null +++ b/FTPGui/src/main/java/impl/FTPFile.java @@ -0,0 +1,25 @@ +package impl; + +public class FTPFile { + + private final boolean isDirectory; + private final String utf; + + public FTPFile(final String utf, final boolean isDirectory) { + this.isDirectory = isDirectory; + this.utf = utf; + } + + public String name() { + return utf; + } + + public boolean isDirectory() { + return isDirectory; + } + + @Override + public String toString() { + return name(); + } +} diff --git a/FTPGui/src/main/java/impl/FTPServer.java b/FTPGui/src/main/java/impl/FTPServer.java new file mode 100644 index 0000000..0c86da8 --- /dev/null +++ b/FTPGui/src/main/java/impl/FTPServer.java @@ -0,0 +1,64 @@ +package impl; + +import abstractServer.AbstractBlockingServer; +import abstractServer.Session; +import org.jetbrains.annotations.NotNull; + +import java.io.IOException; +import java.net.Socket; + +/** + * impl.FTPServer class. Has factory init method and shutDown method. Also it is possible + * to track mistakes, that happened during server work. + *

+ * Server may accept a lot of clients and work with them in distinct thread by {@link FTPSession} + * class. In fact all possibilities of server are described in {@link FTPSession}. + *

+ * Server will shut down if any error occurred during it's work (not just in one created session). + **/ +@SuppressWarnings("unused") +public class FTPServer extends AbstractBlockingServer { + + @SuppressWarnings("WeakerAccess") + public final static int DEFAULT_PORT = 9996; + + private FTPServer(final int port) throws IOException { + super(port); + } + + private FTPServer() throws IOException { + this(DEFAULT_PORT); + } + + @NotNull + @Override + protected Session newSession(final Socket socket, final int number) { + return new FTPSession(socket, number, this); + } + + /** + * Creates new impl.FTPServer on {@link FTPServer#DEFAULT_PORT} port. + * + * @return new impl.FTPServer on default port. + * @throws IOException if IOException happened while creating new server. + */ + @SuppressWarnings({"WeakerAccess", "UnusedReturnValue"}) + public static FTPServer init() throws IOException { + return new FTPServer(); + } + + /** + * Creates new impl.FTPServer on target port. + * + * @param port port to create server on. + * @return new impl.FTPServer on default port. + * @throws IOException if IOException happened while creating new server. + */ + public static FTPServer init(final int port) throws IOException { + return new FTPServer(port); + } + + public static void main(final String[] args) throws IOException { + init(); + } +} diff --git a/FTPGui/src/main/java/impl/FTPSession.java b/FTPGui/src/main/java/impl/FTPSession.java new file mode 100644 index 0000000..64c858b --- /dev/null +++ b/FTPGui/src/main/java/impl/FTPSession.java @@ -0,0 +1,84 @@ +package impl; + +import abstractServer.AbstractBlockingSession; +import abstractServer.Server; +import org.jetbrains.annotations.NotNull; + +import java.io.*; +import java.net.Socket; +import java.util.Objects; + +class FTPSession extends AbstractBlockingSession { + + private static final int BUF_SIZE = 2048; + + FTPSession(@NotNull final Socket socket, final int id, final Server server) { + super(socket, id, server); + } + + @Override + protected void processInput(@NotNull final DataInputStream is) throws IOException { + while (true) { + final int query = is.readInt(); + final String path = is.readUTF(); + switch (query) { + case 1: + sendList(path); + break; + case 2: + sendFile(path); + break; + case 3: + closeSession(null); + return; + default: + // do nothing, unknown command + } + } + } + + private void sendList(@NotNull final String path) { + try (final ByteArrayOutputStream bos = new ByteArrayOutputStream(BUF_SIZE); + final DataOutputStream os = new DataOutputStream(bos)) { + + final File target = new File(path); + if (!target.isDirectory()) { + os.writeInt(0); + } else { + os.writeInt(Objects.requireNonNull(target.listFiles()).length); + for (final File file : Objects.requireNonNull(target.listFiles())) { + os.writeUTF(file.getName()); + os.writeBoolean(file.isDirectory()); + } + } + sendToClient(bos.toByteArray()); + + } catch (@NotNull final IOException e) { + closeSession(e); + } + } + + private void sendFile(@NotNull final String path) { + final File target = new File(path); + if (!target.isFile() || !target.canRead()) { + sendToClient(0); + return; + } + sendToClient(target.length()); + final byte[] buf = new byte[BUF_SIZE]; + try (final InputStream is = new FileInputStream(target)) { + + int bytesRead; + while (true) { + bytesRead = is.read(buf); + if (bytesRead == -1) { + break; + } + sendToClient(buf, 0, bytesRead); + } + + } catch (@NotNull final IOException e) { + closeSession(e); + } + } +}