diff --git a/.travis.yml b/.travis.yml index aac6a7a..b9018d1 100644 --- a/.travis.yml +++ b/.travis.yml @@ -3,4 +3,8 @@ language: java sudo: false notifications: - email: false \ No newline at end of file + email: false + +env: + - TEST_DIR=SimpleFTP +script: cd $TEST_DIR && ./gradlew clean check \ No newline at end of file diff --git a/SimpleFTP/FTPClient/build.gradle b/SimpleFTP/FTPClient/build.gradle new file mode 100644 index 0000000..c73fa91 --- /dev/null +++ b/SimpleFTP/FTPClient/build.gradle @@ -0,0 +1,14 @@ +group 'ru.spbau.dkaznacheev' +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/SimpleFTP/FTPClient/src/main/java/ru/spbau/dkaznacheev/simpleftp/Client.java b/SimpleFTP/FTPClient/src/main/java/ru/spbau/dkaznacheev/simpleftp/Client.java new file mode 100644 index 0000000..77cb2ed --- /dev/null +++ b/SimpleFTP/FTPClient/src/main/java/ru/spbau/dkaznacheev/simpleftp/Client.java @@ -0,0 +1,89 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import java.io.*; +import java.net.ConnectException; +import java.net.Socket; +import java.net.UnknownHostException; +import java.util.Scanner; + +public class Client { + + /** + * Downloads a file from sever + * @param in inputstream of a socket + * @param name name of the file + */ + private static void receiveFile(DataInputStream in, String name) throws IOException{ + long length = in.readLong(); + if (length == 0) { + System.out.println("No such file"); + return; + } + try (FileOutputStream out = new FileOutputStream(simpleName(name))) { + byte[] buffer = new byte[4096]; + long remaining = length; + int read; + while ((read = in.read(buffer, 0, (int) Math.min(buffer.length, remaining))) > 0) { + remaining -= read; + out.write(buffer); + } + } + } + + /** + * Returns simple file name of the filepath. + * @param path path to file + * @return filename + */ + private static String simpleName(String path) { + return new File(path).getName(); + } + + public static void main(String[] args) { + try ( + Socket socket = new Socket("127.0.0.1", 8080); + PrintWriter out = new PrintWriter(socket.getOutputStream(), true); + DataInputStream in = new DataInputStream(socket.getInputStream()); + Scanner stdIn = new Scanner(System.in) + ) { + ResponseCode fromServer; + String fromUser; + boolean exit = false; + while (!exit) { + fromUser = stdIn.nextLine(); + if (fromUser != null) { + out.println(fromUser); + } + fromServer = ResponseCode.values()[in.readInt()]; + switch (fromServer) { + case CLOSE_CONNECTION: { + exit = true; + break; + } + case INVALID_COMMAND: { + System.out.println("Invalid command"); + break; + } + case FOLDER_DESCRIPTION: { + FolderDescription description = FolderDescription.read(in); + description.print(); + break; + } + case FILE_SEND: { + String[] parts = fromUser.split(" "); + receiveFile(in, parts[1]); + break; + } + } + } + + } catch (UnknownHostException e) { + System.err.println("Unknown host"); + } catch (ConnectException e) { + System.err.println("Connection refused"); + } catch (IOException e) { + e.printStackTrace(); + } + } +} + diff --git a/SimpleFTP/FTPServer/build.gradle b/SimpleFTP/FTPServer/build.gradle new file mode 100644 index 0000000..c73fa91 --- /dev/null +++ b/SimpleFTP/FTPServer/build.gradle @@ -0,0 +1,14 @@ +group 'ru.spbau.dkaznacheev' +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/SimpleFTP/FTPServer/src/main/java/ru/spbau/dkaznacheev/simpleftp/Server.java b/SimpleFTP/FTPServer/src/main/java/ru/spbau/dkaznacheev/simpleftp/Server.java new file mode 100644 index 0000000..d184aa8 --- /dev/null +++ b/SimpleFTP/FTPServer/src/main/java/ru/spbau/dkaznacheev/simpleftp/Server.java @@ -0,0 +1,111 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.net.SocketException; + +import static ru.spbau.dkaznacheev.simpleftp.ResponseCode.*; + +/** + * Simple FTP server that can handle multiple clients and send files over sockets. + */ +public class Server { + + /** + * Sends file over ServerSocket's DataOutputStream. + * @param name filename + * @param out output stream + */ + private static void sendFile(String name, DataOutputStream out) throws IOException{ + File file = new File(name); + if (!file.exists()) { + out.writeLong(0); + return; + } + out.writeLong(file.length()); + byte[] buffer = new byte[4096]; + int read; + try (FileInputStream in = new FileInputStream(file)) { + while ((read = in.read(buffer)) > -1) { + out.write(buffer, 0, read); + } + } + + } + + /** + * Client handler, runs in a separate thread as long as there is a connectin with a client. + */ + private static class FTPThread extends Thread { + + /** + * Socket f server-client connection + */ + private Socket socket; + + public FTPThread(Socket socket) { + this.socket = socket; + } + + @Override + public void run() { + try ( + DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + BufferedReader in = new BufferedReader( + new InputStreamReader(socket.getInputStream())) + ) { + String inputLine; + while ((inputLine = in.readLine()) != null) { + if (inputLine.equals("0")) { + out.writeInt(CLOSE_CONNECTION.ordinal()); + break; + } + + String[] parts = inputLine.split(" "); + if (parts.length != 2) { + out.writeInt(INVALID_COMMAND.ordinal()); + continue; + } + String command = parts[0]; + String path = parts[1]; + + if (command.equals("1")) { + FolderDescription description = FolderDescription.describeFolder(path); + out.writeInt(FOLDER_DESCRIPTION.ordinal()); + description.write(out); + } else if (command.equals("2")) { + out.writeInt(FILE_SEND.ordinal()); + sendFile(path, out); + } else { + out.writeInt(INVALID_COMMAND.ordinal()); + } + } + socket.close(); + } catch (SocketException e) { + System.out.println("Goodbye"); + } + catch (IOException e) { + System.err.println("IOException on thread " + Thread.currentThread().getName()); + } + } + } + + public static void main(String[] args) { + ServerSocket serverSocket; + try { + serverSocket = new ServerSocket(8080); + } catch (IOException e) { + System.err.println("Error creating server"); + return; + } + while (true) { + try { + Socket clientSocket = serverSocket.accept(); + new FTPThread(clientSocket).start(); + } catch (IOException e) { + System.err.println("Exception on client connecting"); + } + } + } +} diff --git a/SimpleFTP/build.gradle b/SimpleFTP/build.gradle new file mode 100644 index 0000000..fc18ffe --- /dev/null +++ b/SimpleFTP/build.gradle @@ -0,0 +1,14 @@ +group 'ru.spbau.dkaznacheev.simpleftp' +version '1.0-SNAPSHOT' + +apply plugin: 'java' + +sourceCompatibility = 1.8 + +repositories { + mavenCentral() +} + +dependencies { + testCompile group: 'junit', name: 'junit', version: '4.12' +} diff --git a/SimpleFTP/gradle/wrapper/gradle-wrapper.jar b/SimpleFTP/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..048d015 Binary files /dev/null and b/SimpleFTP/gradle/wrapper/gradle-wrapper.jar differ diff --git a/SimpleFTP/gradle/wrapper/gradle-wrapper.properties b/SimpleFTP/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..33b8486 --- /dev/null +++ b/SimpleFTP/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +#Wed May 30 23:52:07 MSK 2018 +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-3.5-rc-2-bin.zip diff --git a/SimpleFTP/gradlew b/SimpleFTP/gradlew new file mode 100755 index 0000000..4453cce --- /dev/null +++ b/SimpleFTP/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:name=$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/SimpleFTP/gradlew.bat b/SimpleFTP/gradlew.bat new file mode 100644 index 0000000..e95643d --- /dev/null +++ b/SimpleFTP/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/SimpleFTP/settings.gradle b/SimpleFTP/settings.gradle new file mode 100644 index 0000000..84ede45 --- /dev/null +++ b/SimpleFTP/settings.gradle @@ -0,0 +1,2 @@ +rootProject.name = 'SimpleFTP' + diff --git a/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/Client.java b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/Client.java new file mode 100644 index 0000000..67d5ff1 --- /dev/null +++ b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/Client.java @@ -0,0 +1,154 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import java.io.*; +import java.net.Socket; +import java.util.Scanner; + +/** + * Client class for SimpleFTP. It can print folder descriptions and download files. + */ +public class Client { + /** + * Code for sending folder description request. + */ + private static final int FOLDER_CODE = 1; + + /** + * Code for sending file download request. + */ + private static final int FILE_CODE = 2; + + /** + * Client's input stream. + */ + private final DataInputStream in; + + /** + * Client's output stream. + */ + private final DataOutputStream out; + + public Client(Socket socket) throws IOException { + in = new DataInputStream(socket.getInputStream()); + out = new DataOutputStream(socket.getOutputStream());//PrintWriter(socket.getOutputStream()); + } + + /** + * Sends a query to describe folder and recieves a FolderDescription. + * @param path path to folder + * @return FolderDescription of a folder + */ + public FolderDescription describeFolderQuery(String path) throws QueryFormatException, IOException { + out.writeInt(FOLDER_CODE); + out.writeUTF(path); + ResponseCode fromServer = ResponseCode.values()[in.readInt()]; + switch (fromServer) { + case INVALID_COMMAND: { + throw new QueryFormatException(); + } + case FOLDER_DESCRIPTION: { + return read(); + } + default: { + return null; + } + } + } + + /** + * Sends a query to download file and downloads it. + * @param filename path to file + */ + public void getFileQuery(String filename) throws IOException, QueryFormatException { + out.writeInt(FILE_CODE); + out.writeUTF(filename); + ResponseCode fromServer = ResponseCode.values()[in.readInt()]; + switch (fromServer) { + case INVALID_COMMAND: { + throw new QueryFormatException(); + } + case FILE_SEND: { + receiveFile(filename); + break; + } + } + } + + /** + * Reads FolderDescription from InputStream. + * @return read FolderDescription + */ + private FolderDescription read() throws IOException { + int size = in.readInt(); + if (size == 0) { + return new FolderDescription(0, null); + } + FolderDescription.FileDescription[] files = new FolderDescription.FileDescription[size]; + + for (int i = 0; i < size; i++) { + String name = in.readUTF(); + boolean isDir = in.readBoolean(); + files[i] = new FolderDescription.FileDescription(name, isDir); + } + return new FolderDescription(size, files); + } + + /** + * Returns simple file name of the filepath. + * @param path path to file + * @return filename + */ + private static String simpleName(String path) { + return new File(path).getName(); + } + + /** + * Downloads a file from server. + * @param name name of the file + */ + private void receiveFile(String name) throws IOException{ + long length = in.readLong(); + if (length == 0) { + System.out.println("No such file"); + return; + } + try (FileOutputStream out = new FileOutputStream(simpleName(name))) { + byte[] buffer = new byte[4096]; + long remaining = length; + int read; + while ((read = in.read(buffer, 0, (int) Math.min(buffer.length, remaining))) > 0) { + remaining -= read; + out.write(buffer); + } + } + } + + /** + * Console interface for client. + */ + public static void main(String[] args) { + + try (Socket socket = new Socket("127.0.0.1", 8080); + Scanner stdIn = new Scanner(System.in)) { + String query; + Client client = new Client(socket); + while ((query = stdIn.nextLine()) != null) { + String[] queryParts = query.split(" "); + if (queryParts.length == 2) { + if (queryParts[0].equals("1")) { + client.describeFolderQuery(queryParts[1]).print(); + } else if (queryParts[0].equals("2")) { + client.getFileQuery(queryParts[1]); + System.out.println("Downloaded" + simpleName(queryParts[1])); + } else { + System.out.println("Incorrect command!"); + } + } else { + System.out.println("Incorrect input!"); + } + } + } catch (IOException | QueryFormatException e) { + e.printStackTrace(); + } + } +} diff --git a/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/FolderDescription.java b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/FolderDescription.java new file mode 100644 index 0000000..ce306c2 --- /dev/null +++ b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/FolderDescription.java @@ -0,0 +1,107 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.File; +import java.io.IOException; + +/** + * Class describing folder contents. + */ +public class FolderDescription { + + /** + * Size of the folder. + */ + private final int size; + + /** + * Description of folder's contents. + */ + private final FileDescription[] files; + + public FolderDescription(int size, FileDescription[] files) { + this.size = size; + this.files = files; + } + + public int getSize() { + return size; + } + + public FileDescription[] getFiles() { + return files; + } + + /** + * Prints FolderDescription to console. + */ + public void print() { + if (size == 0) { + System.out.println("Folder not found"); + return; + } + System.out.println(size + " files:"); + for (FileDescription description : files) { + System.out.print(description.name); + if (description.isDir) { + System.out.print(": folder"); + } + System.out.println(); + } + System.out.println(); + } + + /** + * Returns a FolderDescription from path to folder. + * If it is the path of non-folder file, returns a FolderDescription with size = 0. + * @param path path to file/folder + * @return FolderDescription on this path + */ + public static FolderDescription describeFolder(String path) { + File root = new File(path); + + File[] contents = root.listFiles(); + if (contents == null) { + return new FolderDescription(0, null); + } + + FileDescription[] files = new FileDescription[contents.length]; + int size = contents.length; + for (int i = 0; i < size; i++) { + String name = contents[i].getName(); + boolean isDir = contents[i].isDirectory(); + files[i] = new FileDescription(name, isDir); + } + return new FolderDescription(size, files); + } + + /** + * Class describing one file. + */ + public static class FileDescription { + + /** + * Filename. + */ + private final String name; + + /** + * Whether a file is a directory or not. + */ + private final boolean isDir; + + public String getName() { + return name; + } + + public boolean isDir() { + return isDir; + } + + public FileDescription(String name, boolean isDir) { + this.name = name; + this.isDir = isDir; + } + } +} diff --git a/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/QueryFormatException.java b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/QueryFormatException.java new file mode 100644 index 0000000..4dafcdc --- /dev/null +++ b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/QueryFormatException.java @@ -0,0 +1,4 @@ +package ru.spbau.dkaznacheev.simpleftp; + +public class QueryFormatException extends Throwable { +} diff --git a/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/ResponseCode.java b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/ResponseCode.java new file mode 100644 index 0000000..efa2088 --- /dev/null +++ b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/ResponseCode.java @@ -0,0 +1,31 @@ +package ru.spbau.dkaznacheev.simpleftp; + +/** + * Codes that client and server use to send util information. + */ +public enum ResponseCode { + /** + * If a connection is closed. + */ + CLOSE_CONNECTION, + + /** + * If a connection is opened. + */ + OPEN_CONNECTION, + + /** + * If a client sent an invalid command. + */ + INVALID_COMMAND, + + /** + * If a server is going to send a FolderDescription. + */ + FOLDER_DESCRIPTION, + + /** + * If a server is going to send a file. + */ + FILE_SEND +} \ No newline at end of file diff --git a/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/Server.java b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/Server.java new file mode 100644 index 0000000..0b85465 --- /dev/null +++ b/SimpleFTP/src/main/java/ru/spbau/dkaznacheev/simpleftp/Server.java @@ -0,0 +1,186 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.concurrent.*; + +import static ru.spbau.dkaznacheev.simpleftp.ResponseCode.*; +import static ru.spbau.dkaznacheev.simpleftp.ResponseCode.INVALID_COMMAND; + +/** + * Server class for SimpleFTP. It can send files and folder descriptions. + */ +public class Server { + + /** + * Number of threads to run thread pool on. + */ + private static final int THREADS = 4; + + /** + * A thread pool for describing folders. + */ + private final ExecutorService folderDescriber = Executors.newFixedThreadPool(THREADS); + + /** + * Server's ServerSocket. + */ + private ServerSocket serverSocket; + + public Server(ServerSocket serverSocket) throws IOException { + this.serverSocket = serverSocket; + } + + /** + * Runnable for multithreaded client handling. + */ + private class ClientProcessor implements Runnable { + /** + * Client's socket. + */ + private Socket socket; + + private ClientProcessor(Socket socket) { + this.socket = socket; + } + + @Override + public void run() { + try ( + DataInputStream in = new DataInputStream(socket.getInputStream()); + DataOutputStream out = new DataOutputStream(socket.getOutputStream()) + ) { + while (true) { + int command = in.readInt(); + String path = in.readUTF(); + + if (command == 0) { + out.writeInt(CLOSE_CONNECTION.ordinal()); + break; + } + + switch (command) { + case 1: { + Future result = folderDescriber.submit(new FolderDescriptionCallable(path)); + FolderDescription description; + try { + description = result.get(); + } catch (Exception e) { + description = null; + } + out.writeInt(FOLDER_DESCRIPTION.ordinal()); + writeFolderDescription(description, out); + break; + } + case 2: { + out.writeInt(FILE_SEND.ordinal()); + sendFile(path, out); + break; + } + default: { + out.writeInt(INVALID_COMMAND.ordinal()); + } + } + } + } + catch (IOException e) { } + finally { + try { + socket.close(); + } catch (IOException ee) { + ee.printStackTrace(); + } + } + } + } + + /** + * Callable for getting FolderDescription in a ThreadPool. + */ + private class FolderDescriptionCallable implements Callable { + + /** + * Path to folder. + */ + private String path; + + private FolderDescriptionCallable(String path) { + this.path = path; + } + + @Override + public FolderDescription call() throws Exception { + return FolderDescription.describeFolder(path); + } + } + + /** + * Starts the server. + */ + public void start() { + while(true) { + try { + Socket socket = serverSocket.accept(); + new Thread(new ClientProcessor(socket)).start(); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + /** + * Writes FolderDescription to DataOutputStream. + * @param description description to write + * @param out output stream to write to + */ + public void writeFolderDescription(FolderDescription description, DataOutputStream out) throws IOException { + int size; + if (description == null) { + size = 0; + } else { + size = description.getSize(); + } + out.writeInt(size); + if (size == 0) { + return; + } + for (FolderDescription.FileDescription fileDescription : description.getFiles()) { + out.writeUTF(fileDescription.getName()); + out.writeBoolean(fileDescription.isDir()); + } + } + + /** + * Sends file over ServerSocket's DataOutputStream. + * @param name filename + * @param out output stream to write to + */ + private void sendFile(String name, DataOutputStream out) throws IOException{ + File file = new File(name); + if (!file.exists()) { + out.writeLong(0); + return; + } + out.writeLong(file.length()); + byte[] buffer = new byte[4096]; + int read; + try (FileInputStream in = new FileInputStream(file)) { + while ((read = in.read(buffer)) > -1) { + out.write(buffer, 0, read); + } + } + } + + public static void main(String[] args) { + ServerSocket serverSocket; + try { + serverSocket = new ServerSocket(8080); + new Server(serverSocket).start(); + } catch (IOException e) { + System.err.println("Error creating server"); + return; + } + } + +} diff --git a/SimpleFTP/src/test/java/ru/spbau/dkaznacheev/simpleftp/FolderDescriptionTest.java b/SimpleFTP/src/test/java/ru/spbau/dkaznacheev/simpleftp/FolderDescriptionTest.java new file mode 100644 index 0000000..85d4b8b --- /dev/null +++ b/SimpleFTP/src/test/java/ru/spbau/dkaznacheev/simpleftp/FolderDescriptionTest.java @@ -0,0 +1,11 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import org.junit.Test; + +public class FolderDescriptionTest { + @Test + public void folderDescSimpleTest() { + FolderDescription desc = FolderDescription.describeFolder("./"); + desc.print(); + } +} diff --git a/SimpleFTP/src/test/java/ru/spbau/dkaznacheev/simpleftp/SimpleFTPTest.java b/SimpleFTP/src/test/java/ru/spbau/dkaznacheev/simpleftp/SimpleFTPTest.java new file mode 100644 index 0000000..fb6f358 --- /dev/null +++ b/SimpleFTP/src/test/java/ru/spbau/dkaznacheev/simpleftp/SimpleFTPTest.java @@ -0,0 +1,27 @@ +package ru.spbau.dkaznacheev.simpleftp; + +import org.junit.Test; + +import java.io.*; +import java.net.ServerSocket; +import java.net.Socket; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.function.BiConsumer; +import java.util.function.Function; +import java.util.regex.PatternSyntaxException; + +import static org.junit.Assert.*; +import static ru.spbau.dkaznacheev.simpleftp.ResponseCode.FILE_SEND; +import static ru.spbau.dkaznacheev.simpleftp.ResponseCode.FOLDER_DESCRIPTION; + +public class SimpleFTPTest { + @Test + public void correctFolderDescription() throws Throwable { + FolderDescription description = FolderDescription.describeFolder("src/test/resources"); + assertEquals(1, description.getSize()); + assertEquals(1, description.getFiles().length); + assertEquals("testFile", description.getFiles()[0].getName()); + assertEquals(false, description.getFiles()[0].isDir()); + } +} \ No newline at end of file diff --git a/SimpleFTP/src/test/resources/testFile b/SimpleFTP/src/test/resources/testFile new file mode 100644 index 0000000..30d74d2 --- /dev/null +++ b/SimpleFTP/src/test/resources/testFile @@ -0,0 +1 @@ +test \ No newline at end of file diff --git a/SimpleFTP/testFile b/SimpleFTP/testFile new file mode 100644 index 0000000..5057510 Binary files /dev/null and b/SimpleFTP/testFile differ