diff --git a/.travis.yml b/.travis.yml
index 7943e5c..e2c60ee 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -2,5 +2,5 @@ language: java
jdk: oraclejdk8
os: linux
env:
- - PROJECT_DIR=term2/cw2
+ - PROJECT_DIR=term2/hw3
script: cd $PROJECT_DIR && ./gradlew check
diff --git a/term2/hw3/.idea/gradle.xml b/term2/hw3/.idea/gradle.xml
new file mode 100644
index 0000000..3da2943
--- /dev/null
+++ b/term2/hw3/.idea/gradle.xml
@@ -0,0 +1,19 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/term2/hw3/.idea/misc.xml b/term2/hw3/.idea/misc.xml
new file mode 100644
index 0000000..bc8d0a3
--- /dev/null
+++ b/term2/hw3/.idea/misc.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/term2/hw3/build.gradle b/term2/hw3/build.gradle
new file mode 100644
index 0000000..d951f05
--- /dev/null
+++ b/term2/hw3/build.gradle
@@ -0,0 +1,13 @@
+version '1.0-SNAPSHOT'
+
+apply plugin: 'java'
+
+sourceCompatibility = 1.8
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ testCompile group: 'junit', name: 'junit', version: '4.12'
+}
diff --git a/term2/hw3/gradle/wrapper/gradle-wrapper.jar b/term2/hw3/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..01b8bf6
Binary files /dev/null and b/term2/hw3/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/term2/hw3/gradle/wrapper/gradle-wrapper.properties b/term2/hw3/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..933b647
--- /dev/null
+++ b/term2/hw3/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
diff --git a/term2/hw3/gradlew b/term2/hw3/gradlew
new file mode 100755
index 0000000..cccdd3d
--- /dev/null
+++ b/term2/hw3/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/term2/hw3/gradlew.bat b/term2/hw3/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/term2/hw3/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/term2/hw3/settings.gradle b/term2/hw3/settings.gradle
new file mode 100644
index 0000000..10a2291
--- /dev/null
+++ b/term2/hw3/settings.gradle
@@ -0,0 +1,2 @@
+rootProject.name = 'hw3'
+
diff --git a/term2/hw3/src/main/java/spbau/eliseeva/ftp/Command.java b/term2/hw3/src/main/java/spbau/eliseeva/ftp/Command.java
new file mode 100644
index 0000000..9df8c21
--- /dev/null
+++ b/term2/hw3/src/main/java/spbau/eliseeva/ftp/Command.java
@@ -0,0 +1,4 @@
+package spbau.eliseeva.ftp;
+
+/** Commands which exists. */
+public enum Command {LIST, GET, CONNECT}
\ No newline at end of file
diff --git a/term2/hw3/src/main/java/spbau/eliseeva/ftp/FTPClient.java b/term2/hw3/src/main/java/spbau/eliseeva/ftp/FTPClient.java
new file mode 100644
index 0000000..c60d15c
--- /dev/null
+++ b/term2/hw3/src/main/java/spbau/eliseeva/ftp/FTPClient.java
@@ -0,0 +1,124 @@
+package spbau.eliseeva.ftp;
+
+import java.io.*;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.util.Scanner;
+
+/** Client for getting file or list of them from server.*/
+public class FTPClient {
+ /**
+ * Scans host name and port number and connects. Starts communication with the server.
+ * @param args ignored
+ */
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Write host name.\n");
+ String hostName = scanner.nextLine();
+ System.out.print("Write port number.\n");
+ int portNumber = Integer.parseInt(scanner.nextLine());
+ try {
+ checkConnection(hostName, portNumber);
+ communicateWithServer(scanner, hostName, portNumber);
+ } catch (IOException e) {
+ System.err.println("Problems with connection or reading and writing.");
+ }
+ }
+
+ /**
+ * While user has not printed "exit" waits for new command and sends requests to server.
+ * @param scanner System.in^ to read from
+ * @param hostName name of host
+ * @param portNumber port to connect
+ * @throws IOException thrown if problems with reading or writing, for example when connection is lost.
+ */
+ private static void communicateWithServer(Scanner scanner, String hostName, int portNumber) throws IOException {
+ String[] fromUser = scanner.nextLine().split(" ");
+ while (!fromUser[0].equals("exit")) {
+ if (!fromUser[0].equals("list") && !fromUser[0].equals("get") || fromUser.length != 2) {
+ System.out.println("Wrong command.");
+ fromUser = scanner.nextLine().split(" ");
+ continue;
+ }
+ Socket socket = new Socket(InetAddress.getByName(hostName), portNumber);
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ DataOutputStream out = new DataOutputStream(socket.getOutputStream());
+ if (fromUser[0].equals("list")) {
+ out.writeInt(Command.LIST.ordinal());
+ out.writeUTF(fromUser[1]);
+ out.flush();
+ listAnswer(in);
+ } else {
+ out.writeInt(Command.GET.ordinal());
+ out.writeUTF(fromUser[1]);
+ out.flush();
+ getAnswer(in, fromUser[1]);
+ }
+ System.out.println();
+ fromUser = scanner.nextLine().split(" ");
+ }
+ }
+
+ /**
+ * Writes and answer for get request.
+ * @param in input stream to read data from
+ * @throws IOException thrown if problems with reading, for example when connection is lost.
+ */
+ private static void listAnswer(DataInputStream in) throws IOException {
+ int size = in.readInt();
+ if (size == -1) {
+ System.out.println("No such directory.");
+ return;
+ }
+ System.out.print(size);
+ System.out.print(' ');
+ for (int i = 0; i < size; i++) {
+ System.out.print('(' + in.readUTF() + ' ');
+ System.out.print(in.readBoolean());
+ System.out.print(')');
+ }
+ }
+
+ /**
+ * Writes and answer for list request.
+ * @param in input stream to read data from
+ * @throws IOException thrown if problems with reading, for example when connection is lost.
+ */
+ private static void getAnswer(DataInputStream in, String fileName) throws IOException {
+ long size = in.readLong();
+ if (size == -1) {
+ System.out.println("Wrong name, file does not exist.");
+ return;
+ }
+ if (size == -2) {
+ System.out.println("File is directory.");
+ return;
+ }
+ System.out.print(size);
+ File file = new File("results/" + fileName);
+ file.getParentFile().mkdirs();
+ OutputStream outputStream = new FileOutputStream(file);
+ int c;
+ byte[] buffer = new byte[1024];
+ while ((c = in.read(buffer)) == 1024) {
+ outputStream.write(buffer, 0, c);
+ }
+ outputStream.write(buffer, 0, c);
+ outputStream.close();
+ }
+
+ /**
+ * Checks that connection exists, should write "connected" on the screen.
+ * @param hostName name of host
+ * @param portNumber port to connect
+ * @throws IOException thrown if problems with reading, for example when connection is lost.
+ */
+ private static void checkConnection(String hostName, int portNumber) throws IOException {
+ Socket socket = new Socket(InetAddress.getByName(hostName), portNumber);
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ DataOutputStream out = new DataOutputStream(socket.getOutputStream());
+ out.writeInt(Command.CONNECT.ordinal());
+ out.flush();
+ System.out.println(in.readUTF());
+ }
+}
diff --git a/term2/hw3/src/main/java/spbau/eliseeva/ftp/FTPServer.java b/term2/hw3/src/main/java/spbau/eliseeva/ftp/FTPServer.java
new file mode 100644
index 0000000..1fc14da
--- /dev/null
+++ b/term2/hw3/src/main/java/spbau/eliseeva/ftp/FTPServer.java
@@ -0,0 +1,131 @@
+package spbau.eliseeva.ftp;
+
+import java.io.*;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Arrays;
+import java.util.Comparator;
+import java.util.Scanner;
+
+/** Server answering for get and list requests: getting file or list of files in the directory.*/
+public class FTPServer {
+ /**
+ * Scans port number and starts waiting for the connection. Ends the program when enter pressed.
+ * @param args ignored
+ */
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Write port number.\n");
+ int portNumber = Integer.parseInt(scanner.nextLine());
+ Thread serverThread = new Thread(() -> runServer(portNumber));
+ serverThread.setDaemon(true);
+ serverThread.start();
+ System.out.println("Press enter to end.\n");
+ scanner.nextLine();
+ }
+
+ /**
+ * Waits for connections and work with requests while not interrupted.
+ * @param portNumber port to listen
+ */
+ private static void runServer(int portNumber) {
+ try {
+ ServerSocket serverSocket = new ServerSocket(portNumber);
+ while (!Thread.interrupted()) {
+ Socket clientSocket = serverSocket.accept();
+ Thread thread = new Thread(() -> {
+ try {
+ DataInputStream in = new DataInputStream(clientSocket.getInputStream());
+ DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
+ processInput(in, out);
+ out.flush();
+ } catch (IOException e) {
+ System.err.println("Problems with connection or reading and writing.");
+ }
+ });
+ thread.setDaemon(true);
+ thread.start();
+ }
+ } catch (IOException ignored) {
+ }
+ }
+
+ /**
+ * Read a request from input and do the requested action.
+ * @param dataInputStream stream to read request
+ * @param dataOutputStream stream to answer
+ * @throws IOException thrown if problems with reading or writing, for example when connection is lost.
+ */
+ private static void processInput(DataInputStream dataInputStream, DataOutputStream dataOutputStream) throws IOException {
+ Command command = Command.values()[dataInputStream.readInt()];
+ switch (command) {
+ case LIST:
+ list(dataInputStream.readUTF(), dataOutputStream);
+ break;
+ case GET:
+ get(dataInputStream.readUTF(), dataOutputStream);
+ break;
+ case CONNECT:
+ dataOutputStream.writeUTF("connected");
+ break;
+ default:
+ dataOutputStream.writeUTF("wrong command.");
+ }
+ }
+
+ /**
+ * Writes in the output size of file and everything inside it.
+ * @param fileName file to write in the output
+ * @param dataOutputStream stream to answer
+ * @throws IOException thrown if problems with writing, for example when connection is lost.
+ */
+ private static void get(String fileName, DataOutputStream dataOutputStream) throws IOException {
+ if ((new File(fileName)).isDirectory()) {
+ dataOutputStream.writeLong(-2);
+ return;
+ }
+ FileInputStream fileInputStream;
+ try {
+ fileInputStream = new FileInputStream(fileName);
+ } catch (FileNotFoundException e) {
+ dataOutputStream.writeLong(-1);
+ return;
+ }
+ int size = 0;
+ int c;
+ byte[] buffer = new byte[1024];
+ while ((c = fileInputStream.read(buffer)) == 1024) {
+ size += c;
+ }
+ size += c;
+ dataOutputStream.writeLong(size);
+ fileInputStream.close();
+ fileInputStream = new FileInputStream(fileName);
+ while ((c = fileInputStream.read(buffer)) == 1024) {
+ dataOutputStream.write(buffer, 0, c);
+ }
+ dataOutputStream.write(buffer, 0, c);
+ fileInputStream.close();
+ }
+
+ /**
+ * Writes in the output number of elements in the directory and names of all of them with noting if directory or not.
+ * @param directoryName directory to find files from
+ * @param dataOutputStream stream to answer
+ * @throws IOException thrown if problems with writing, for example when connection is lost.
+ */
+ private static void list(String directoryName, DataOutputStream dataOutputStream) throws IOException {
+ File dir = new File(directoryName);
+ if (!dir.isDirectory()) {
+ dataOutputStream.writeInt(-1);
+ return;
+ }
+ dataOutputStream.writeInt(dir.listFiles().length);
+ File [] files = dir.listFiles();
+ Arrays.sort(files, Comparator.comparing(File::getName));
+ for (File file : files) {
+ dataOutputStream.writeUTF(file.getName());
+ dataOutputStream.writeBoolean(file.isDirectory());
+ }
+ }
+}
diff --git a/term2/hw3/src/test/java/spbau/eliseeva/ftp/FTPTest.java b/term2/hw3/src/test/java/spbau/eliseeva/ftp/FTPTest.java
new file mode 100644
index 0000000..5437b7a
--- /dev/null
+++ b/term2/hw3/src/test/java/spbau/eliseeva/ftp/FTPTest.java
@@ -0,0 +1,128 @@
+package spbau.eliseeva.ftp;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.*;
+
+import static org.junit.Assert.*;
+
+/** Tests for FTPClient and FTPServer.*/
+public class FTPTest {
+ private static final String END_OF_LINE = System.lineSeparator();
+ @Rule
+ public TemporaryFolder FOLDER = new TemporaryFolder();
+ /** Checks if the server works as expected. */
+ @Test
+ public void testServer() {
+ InputStream serverInputStream = new ByteArrayInputStream(("1234" + END_OF_LINE + END_OF_LINE).getBytes());
+ System.setIn(serverInputStream);
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(byteArrayOutputStream));
+ FTPServer.main(new String[0]);
+ assertArrayEquals(("Write port number." + END_OF_LINE + "Press enter to end." + END_OF_LINE + END_OF_LINE).getBytes(), byteArrayOutputStream.toByteArray());
+ }
+
+ /**
+ * Checks if the client can connect to the server
+ * @throws InterruptedException thrown if problems with threads.
+ */
+ @Test
+ public void testConnection() throws InterruptedException {
+ runServer();
+ InputStream clientInputStream = new ByteArrayInputStream(("localhost" + END_OF_LINE + "1234" + END_OF_LINE +"exit" + END_OF_LINE).getBytes());
+ assertArrayEquals(("Write host name." + END_OF_LINE + "Write port number." + END_OF_LINE + "connected" + END_OF_LINE).getBytes(),
+ runClient(clientInputStream).toByteArray());
+ }
+
+ /**
+ * Checks some list and get requests.
+ * @throws InterruptedException thrown if problems with threads.
+ * @throws IOException if problems with files
+ */
+ @Test
+ public void testListAndGet() throws InterruptedException, IOException {
+ runServer();
+ FOLDER.newFolder("results");
+ InputStream clientInputStream = new ByteArrayInputStream(("localhost" + END_OF_LINE + "1234" + END_OF_LINE
+ + "list src/test/resources/dir1" + END_OF_LINE + "list src/test/resources/dir1/dir2" + END_OF_LINE +
+ "get src/test/resources/dir1/dir4/file3" + END_OF_LINE + "list src/test/resources/dir1/dir2/dir3" + END_OF_LINE + "exit" + END_OF_LINE).getBytes());
+ assertArrayEquals(("Write host name." + END_OF_LINE + "Write port number." + END_OF_LINE + "connected" + END_OF_LINE +
+ "3 (dir2 true)(dir4 true)(dir5 true)" + END_OF_LINE + "2 (dir3 true)(file1 false)" + END_OF_LINE +
+ "5" + END_OF_LINE + "2 (file2 false)(file5 false)" + END_OF_LINE).getBytes(), runClient(clientInputStream).toByteArray());
+ byte[] bytes = new byte[5];
+ (new FileInputStream(new File("results/src/test/resources/dir1/dir4/file3"))).read(bytes);
+ System.out.write(bytes);
+ assertArrayEquals(("file3").getBytes(),bytes);
+ }
+
+ /**
+ * Checks if two clients can work with same server.
+ * @throws InterruptedException thrown if problems with threads.
+ * @throws IOException if problems with files
+ */
+ @Test
+ public void testTwoClients() throws InterruptedException, IOException {
+ runServer();
+ FOLDER.newFolder("results");
+ Thread thread1 = new Thread(() -> {
+ InputStream clientInputStream1 = new ByteArrayInputStream(("localhost" + END_OF_LINE + "1234" + END_OF_LINE +
+ "list src/test/resources/dir1/dir5" + END_OF_LINE + "exit" + END_OF_LINE).getBytes());
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ignored) {
+ }
+ assertArrayEquals(("Write host name." + END_OF_LINE + "Write port number." + END_OF_LINE + "connected" + END_OF_LINE + "list (file4 false)").getBytes(),
+ runClient(clientInputStream1).toByteArray());
+ });
+ Thread thread2 = new Thread(() -> {
+ InputStream clientInputStream2 = new ByteArrayInputStream(("localhost" + END_OF_LINE + "1234" + END_OF_LINE +
+ "get src/test/resources/dir1/dir2/file1" + END_OF_LINE + "exit" + END_OF_LINE).getBytes());
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException ignored) {
+ }
+ assertArrayEquals(("Write host name." + END_OF_LINE + "Write port number." + END_OF_LINE + "connected" + END_OF_LINE + "5" + END_OF_LINE).getBytes(),
+ runClient(clientInputStream2).toByteArray());
+
+ byte[] bytes = new byte[5];
+ try {
+ (new FileInputStream(new File("results/src/test/resources/dir1/dir2/file1"))).read(bytes);
+ } catch (IOException ignored) {
+ }
+ assertArrayEquals(("file1").getBytes(), bytes);
+ });
+ thread1.start();
+ thread2.start();
+ }
+
+ /**
+ * Starts working of server.
+ * @throws InterruptedException thrown if problems with threads.
+ */
+ private void runServer() throws InterruptedException {
+ InputStream serverInputStream = new ByteArrayInputStream(("1234" + END_OF_LINE + END_OF_LINE).getBytes());
+ Thread thread = new Thread(() -> {
+ System.setIn(serverInputStream);
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ FTPServer.main(new String[0]);
+ });
+ thread.setDaemon(true);
+ thread.start();
+ Thread.sleep(2000);
+ }
+
+ /**
+ * Runs the client with given input stream and returns printed answer.
+ * @param clientInputStream stream which replaces "System.in" for the client
+ * @return stream which replaces "System.out" for the client
+ */
+ private ByteArrayOutputStream runClient(InputStream clientInputStream) {
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ System.setIn(clientInputStream);
+ System.setOut(new PrintStream(byteArrayOutputStream));
+ FTPClient.main(new String[0]);
+ return byteArrayOutputStream;
+ }
+}
diff --git a/term2/hw3/src/test/resources/dir1/dir2/dir3/file2 b/term2/hw3/src/test/resources/dir1/dir2/dir3/file2
new file mode 100644
index 0000000..30d67d4
--- /dev/null
+++ b/term2/hw3/src/test/resources/dir1/dir2/dir3/file2
@@ -0,0 +1 @@
+file2
\ No newline at end of file
diff --git a/term2/hw3/src/test/resources/dir1/dir2/dir3/file5 b/term2/hw3/src/test/resources/dir1/dir2/dir3/file5
new file mode 100644
index 0000000..d92b9c3
--- /dev/null
+++ b/term2/hw3/src/test/resources/dir1/dir2/dir3/file5
@@ -0,0 +1 @@
+file5
\ No newline at end of file
diff --git a/term2/hw3/src/test/resources/dir1/dir2/file1 b/term2/hw3/src/test/resources/dir1/dir2/file1
new file mode 100644
index 0000000..08219db
--- /dev/null
+++ b/term2/hw3/src/test/resources/dir1/dir2/file1
@@ -0,0 +1 @@
+file1
\ No newline at end of file
diff --git a/term2/hw3/src/test/resources/dir1/dir4/file3 b/term2/hw3/src/test/resources/dir1/dir4/file3
new file mode 100644
index 0000000..873fb8d
--- /dev/null
+++ b/term2/hw3/src/test/resources/dir1/dir4/file3
@@ -0,0 +1 @@
+file3
\ No newline at end of file
diff --git a/term2/hw3/src/test/resources/dir1/dir5/file4 b/term2/hw3/src/test/resources/dir1/dir5/file4
new file mode 100644
index 0000000..eed6780
--- /dev/null
+++ b/term2/hw3/src/test/resources/dir1/dir5/file4
@@ -0,0 +1 @@
+file4
\ No newline at end of file
diff --git a/term2/hw4/.idea/gradle.xml b/term2/hw4/.idea/gradle.xml
new file mode 100644
index 0000000..b2d9b0d
--- /dev/null
+++ b/term2/hw4/.idea/gradle.xml
@@ -0,0 +1,17 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/term2/hw4/.idea/misc.xml b/term2/hw4/.idea/misc.xml
new file mode 100644
index 0000000..bc8d0a3
--- /dev/null
+++ b/term2/hw4/.idea/misc.xml
@@ -0,0 +1,7 @@
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/term2/hw4/.idea/uiDesigner.xml b/term2/hw4/.idea/uiDesigner.xml
new file mode 100644
index 0000000..e96534f
--- /dev/null
+++ b/term2/hw4/.idea/uiDesigner.xml
@@ -0,0 +1,124 @@
+
+
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+
+
+
+ -
+
+
+
+
+
+ -
+
+
+
+
+
+ -
+
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+ -
+
+
+
+
+ -
+
+
+ -
+
+
+
+
+
\ No newline at end of file
diff --git a/term2/hw4/build.gradle b/term2/hw4/build.gradle
new file mode 100644
index 0000000..d951f05
--- /dev/null
+++ b/term2/hw4/build.gradle
@@ -0,0 +1,13 @@
+version '1.0-SNAPSHOT'
+
+apply plugin: 'java'
+
+sourceCompatibility = 1.8
+
+repositories {
+ mavenCentral()
+}
+
+dependencies {
+ testCompile group: 'junit', name: 'junit', version: '4.12'
+}
diff --git a/term2/hw4/gradle/wrapper/gradle-wrapper.jar b/term2/hw4/gradle/wrapper/gradle-wrapper.jar
new file mode 100644
index 0000000..01b8bf6
Binary files /dev/null and b/term2/hw4/gradle/wrapper/gradle-wrapper.jar differ
diff --git a/term2/hw4/gradle/wrapper/gradle-wrapper.properties b/term2/hw4/gradle/wrapper/gradle-wrapper.properties
new file mode 100644
index 0000000..933b647
--- /dev/null
+++ b/term2/hw4/gradle/wrapper/gradle-wrapper.properties
@@ -0,0 +1,5 @@
+distributionBase=GRADLE_USER_HOME
+distributionPath=wrapper/dists
+zipStoreBase=GRADLE_USER_HOME
+zipStorePath=wrapper/dists
+distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-bin.zip
diff --git a/term2/hw4/gradlew b/term2/hw4/gradlew
new file mode 100755
index 0000000..cccdd3d
--- /dev/null
+++ b/term2/hw4/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/term2/hw4/gradlew.bat b/term2/hw4/gradlew.bat
new file mode 100644
index 0000000..e95643d
--- /dev/null
+++ b/term2/hw4/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/term2/hw4/settings.gradle b/term2/hw4/settings.gradle
new file mode 100644
index 0000000..1a960dd
--- /dev/null
+++ b/term2/hw4/settings.gradle
@@ -0,0 +1,2 @@
+rootProject.name = 'hw4'
+
diff --git a/term2/hw4/src/main/java/spbau/eliseeva/ftp/FTPClient.java b/term2/hw4/src/main/java/spbau/eliseeva/ftp/FTPClient.java
new file mode 100644
index 0000000..c1b3293
--- /dev/null
+++ b/term2/hw4/src/main/java/spbau/eliseeva/ftp/FTPClient.java
@@ -0,0 +1,76 @@
+package spbau.eliseeva.ftp;
+
+import java.io.*;
+import java.net.InetAddress;
+import java.net.Socket;
+import java.util.HashMap;
+import java.util.Map;
+
+/** Client for getting file or list of them from server.*/
+public class FTPClient {
+ private int portNumber;
+ private String hostName;
+
+ /**
+ * Creates new client
+ * @param portNumber number of port
+ * @param hostName name of host
+ */
+ public FTPClient(int portNumber, String hostName) {
+ this.portNumber = portNumber;
+ this.hostName = hostName;
+ }
+
+ /**
+ * Returns answer to a list request
+ * @param fromUser name of directory
+ * @return result of list request
+ * @throws IOException if problems with reading or writing data
+ */
+ public Map listAnswer(String fromUser) throws IOException {
+ Socket socket = new Socket(InetAddress.getByName(hostName), portNumber);
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ DataOutputStream out = new DataOutputStream(socket.getOutputStream());
+ out.writeInt(1);
+ out.writeUTF(fromUser);
+ out.flush();
+ int size = in.readInt();
+ Map map = new HashMap<>();
+ for (int i = 0; i < size; i++) {
+ map.put(in.readUTF(), in.readBoolean());
+ }
+ return map;
+ }
+
+ /**
+ * Does get request.
+ * @param fromUser name of file on server
+ * @param fileName name of file to save
+ * @throws IOException if problems with files
+ */
+ public void getAnswer(String fromUser, String fileName) throws IOException {
+ Socket socket = new Socket(InetAddress.getByName(hostName), portNumber);
+ DataInputStream in = new DataInputStream(socket.getInputStream());
+ DataOutputStream out = new DataOutputStream(socket.getOutputStream());
+ out.writeInt(2);
+ out.writeUTF(fromUser);
+ out.flush();
+ long size = in.readLong();
+ File folder = new File("results");
+ if (!folder.exists()) {
+ folder.mkdir();
+ }
+ File file = new File("results/" + fileName);
+ OutputStream outputStream = new FileOutputStream(file);
+ if (size != 0) {
+ int c;
+ byte[] buffer = new byte[1024];
+ while ((c = in.read(buffer)) == 1024) {
+ outputStream.write(buffer, 0, c);
+ }
+ outputStream.write(buffer, 0, c);
+ }
+ outputStream.flush();
+ outputStream.close();
+ }
+}
diff --git a/term2/hw4/src/main/java/spbau/eliseeva/ftp/FTPServer.java b/term2/hw4/src/main/java/spbau/eliseeva/ftp/FTPServer.java
new file mode 100644
index 0000000..c9bdb1a
--- /dev/null
+++ b/term2/hw4/src/main/java/spbau/eliseeva/ftp/FTPServer.java
@@ -0,0 +1,127 @@
+package spbau.eliseeva.ftp;
+
+import java.io.*;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.util.Scanner;
+
+/** Server answering for get and list requests: getting file or list of files in the directory.*/
+public class FTPServer {
+ /**
+ * Scans port number and starts waiting for the connection. Ends the program when enter pressed.
+ * @param args ignored
+ */
+ public static void main(String[] args) {
+ Scanner scanner = new Scanner(System.in);
+ System.out.print("Write port number.\n");
+ int portNumber = Integer.parseInt(scanner.nextLine());
+ Thread serverThread = new Thread(() -> runServer(portNumber));
+ serverThread.setDaemon(true);
+ serverThread.start();
+ System.out.println("Press enter to end.\n");
+ scanner.nextLine();
+ }
+
+ /**
+ * Waits for connections and work with requests while not interrupted.
+ * @param portNumber port to listen
+ */
+ private static void runServer(int portNumber) {
+ try {
+ ServerSocket serverSocket = new ServerSocket(portNumber);
+ while (!Thread.interrupted()) {
+ Socket clientSocket = serverSocket.accept();
+ Thread thread = new Thread(() -> {
+ try {
+ DataInputStream in = new DataInputStream(clientSocket.getInputStream());
+ DataOutputStream out = new DataOutputStream(clientSocket.getOutputStream());
+ processInput(in, out);
+ out.flush();
+ } catch (IOException e) {
+ System.err.println("Problems with connection or reading and writing.");
+ }
+ });
+ thread.setDaemon(true);
+ thread.start();
+ }
+ } catch (IOException ignored) {
+ }
+ }
+
+ /**
+ * Read a request from input and do the requested action.
+ * @param dataInputStream stream to read request
+ * @param dataOutputStream stream to answer
+ * @throws IOException thrown if problems with reading or writing, for example when connection is lost.
+ */
+ private static void processInput(DataInputStream dataInputStream, DataOutputStream dataOutputStream) throws IOException {
+ int command = dataInputStream.readInt();
+ switch (command) {
+ case 1:
+ list(dataInputStream.readUTF(), dataOutputStream);
+ break;
+ case 2:
+ get(dataInputStream.readUTF(), dataOutputStream);
+ break;
+ case 17:
+ dataOutputStream.writeUTF("connected");
+ break;
+ default:
+ dataOutputStream.writeUTF("wrong command.");
+ }
+ }
+
+ /**
+ * Writes in the output size of file and everything inside it.
+ * @param fileName file to write in the output
+ * @param dataOutputStream stream to answer
+ * @throws IOException thrown if problems with writing, for example when connection is lost.
+ */
+ private static void get(String fileName, DataOutputStream dataOutputStream) throws IOException {
+ FileInputStream fileInputStream;
+ try {
+ fileInputStream = new FileInputStream(fileName);
+ } catch (FileNotFoundException e) {
+ dataOutputStream.writeLong(0);
+ return;
+ }
+ if ((new File(fileName)).isDirectory()) {
+ dataOutputStream.writeLong(0);
+ return;
+ }
+ int size = 0;
+ int c;
+ byte[] buffer = new byte[1024];
+ while ((c = fileInputStream.read(buffer)) == 1024) {
+ size += c;
+ }
+ size += c;
+ dataOutputStream.writeLong(size);
+ fileInputStream.close();
+ fileInputStream = new FileInputStream(fileName);
+ while ((c = fileInputStream.read(buffer)) == 1024) {
+ dataOutputStream.write(buffer, 0, c);
+ }
+ dataOutputStream.write(buffer, 0, c);
+ fileInputStream.close();
+ }
+
+ /**
+ * Writes in the output number of elements in the directory and names of all of them with noting if directory or not.
+ * @param directoryName directory to find files from
+ * @param dataOutputStream stream to answer
+ * @throws IOException thrown if problems with writing, for example when connection is lost.
+ */
+ private static void list(String directoryName, DataOutputStream dataOutputStream) throws IOException {
+ File dir = new File(directoryName);
+ if (!dir.isDirectory()) {
+ dataOutputStream.writeInt(0);
+ return;
+ }
+ dataOutputStream.writeInt(dir.listFiles().length);
+ for (File file : dir.listFiles()) {
+ dataOutputStream.writeUTF(file.getName());
+ dataOutputStream.writeBoolean(file.isDirectory());
+ }
+ }
+}
diff --git a/term2/hw4/src/main/java/spbau/eliseeva/gui/FoldersController.java b/term2/hw4/src/main/java/spbau/eliseeva/gui/FoldersController.java
new file mode 100644
index 0000000..aa8be89
--- /dev/null
+++ b/term2/hw4/src/main/java/spbau/eliseeva/gui/FoldersController.java
@@ -0,0 +1,157 @@
+package spbau.eliseeva.gui;
+
+import javafx.application.Platform;
+import javafx.fxml.FXMLLoader;
+import javafx.scene.Scene;
+import javafx.scene.control.Button;
+import javafx.scene.control.ScrollPane;
+import javafx.scene.layout.HBox;
+import javafx.scene.layout.Priority;
+import javafx.scene.layout.VBox;
+import javafx.stage.Stage;
+import spbau.eliseeva.ftp.FTPClient;
+
+import java.io.*;
+import java.net.MalformedURLException;
+import java.util.Map;
+
+/** Controller for a list with directories.*/
+class FoldersController {
+ private Scene scene;
+ private FTPClient client;
+ private Map names;
+ private int portNumber;
+ private String hostName;
+
+ /**
+ * Creates new controller and all the buttons.
+ * @param root name of directory to show
+ * @param portNumber number of port to connect
+ * @param hostName name of host
+ */
+ FoldersController(String root, int portNumber, String hostName) {
+ this.client = new FTPClient(portNumber, hostName);
+ this.portNumber = portNumber;
+ this.hostName = hostName;
+ try {
+ names = client.listAnswer(root);
+ } catch (IOException ignored) {
+ }
+ Button[] buttons = new Button[names.size()];
+ int index = 0;
+ for (Map.Entry entry : names.entrySet()) {
+ buttons[index] = makeButton(root, entry.getKey(), entry.getValue());
+ index++;
+ }
+ HBox[] rows;
+ int j = 0;
+ if (!root.equals("/")) {
+ rows = new HBox[names.size() + 1];
+ rows[0] = new HBox();
+ Button backButton = new Button();
+ backButton.setFocusTraversable(false);
+ backButton.setMaxWidth(400);
+ backButton.setMaxHeight(400);
+ backButton.setText("<-");
+ backButton.setStyle(" -fx-text-fill: #590ec7; -fx-opacity: 1.0;");
+ backButton.setOnMouseClicked(event -> {
+ Stage stage = (Stage) backButton.getScene().getWindow();
+ int ind = root.length() - 1;
+ while (root.charAt(ind) != '/') {
+ ind--;
+ }
+ if (ind == 0) {
+ ind++;
+ }
+ String newRoot = root.substring(0, ind);
+ stage.setScene(new FoldersController(newRoot, portNumber, hostName).getScene());
+ stage.show();
+ });
+
+ HBox.setHgrow(backButton, Priority.ALWAYS);
+ backButton.prefWidthProperty().bind(rows[0].widthProperty().divide(2));
+ rows[0].getChildren().add(backButton);
+ j++;
+ } else {
+ rows = new HBox[names.size()];
+ }
+ for (int i = 0; i < names.size(); i++, j++) {
+ rows[j] = new HBox();
+ HBox.setHgrow(buttons[i], Priority.ALWAYS);
+ buttons[i].prefWidthProperty().bind(rows[j].widthProperty().divide(2));
+ rows[j].getChildren().add(buttons[i]);
+ }
+ VBox field = new VBox();
+ for (HBox row : rows) {
+ VBox.setVgrow(row, Priority.ALWAYS);
+ field.getChildren().add(row);
+ }
+ ScrollPane scrollPane = new ScrollPane();
+ scrollPane.setContent(field);
+ scrollPane.setVbarPolicy(ScrollPane.ScrollBarPolicy.ALWAYS);
+ field.setPrefSize(380, 600);
+
+ this.scene = new Scene(scrollPane, 400, 600);
+ }
+
+ /**
+ * Creates a button for a file or directory
+ * @param root name of current dir
+ * @param text name of file or dir to open
+ * @param isDirectory true if directory
+ * @return the button
+ */
+ private Button makeButton(String root, String text, Boolean isDirectory) {
+ Button button = new Button();
+ button.setFocusTraversable(false);
+ button.setMaxWidth(400);
+ button.setMaxHeight(400);
+ button.setText(text);
+ if (isDirectory) {
+ button.setStyle(" -fx-text-fill: #c90d65; -fx-opacity: 1.0;");
+ button.setOnMouseClicked(event -> {
+ Stage stage = (Stage) button.getScene().getWindow();
+ String newRoot = root;
+ if (!root.equals("/")) {
+ newRoot += '/';
+ }
+ stage.setScene(new FoldersController(newRoot + text, portNumber, hostName).getScene());
+ stage.show();
+ });
+ } else {
+ button.setStyle(" -fx-text-fill: #590ec7; -fx-opacity: 1.0;");
+ button.setOnMouseClicked(event -> {
+ FXMLLoader fxmlLoader = new FXMLLoader();
+ try {
+ fxmlLoader.setLocation(new File("src/main/resources/save.fxml").toURI().toURL());
+ } catch (MalformedURLException e) {
+ Platform.exit();
+ }
+ Scene scene = null;
+ try {
+ scene = new Scene(fxmlLoader.load(), 400, 200);
+ } catch (IOException e) {
+ Platform.exit();
+ }
+ String newRoot = root;
+ if (!root.equals("/")) {
+ newRoot += '/';
+ }
+ ((SaveController)fxmlLoader.getController()).initialize(client, newRoot + text);
+ Stage stage = new Stage();
+ stage.setTitle("Save");
+ stage.setScene(scene);
+ stage.show();
+ });
+ }
+ return button;
+ }
+
+ /**
+ * Returns scene
+ * @return scene
+ */
+ Scene getScene() {
+ return scene;
+ }
+}
diff --git a/term2/hw4/src/main/java/spbau/eliseeva/gui/MainApplication.java b/term2/hw4/src/main/java/spbau/eliseeva/gui/MainApplication.java
new file mode 100644
index 0000000..aad9bfd
--- /dev/null
+++ b/term2/hw4/src/main/java/spbau/eliseeva/gui/MainApplication.java
@@ -0,0 +1,37 @@
+package spbau.eliseeva.gui;
+
+import javafx.application.Application;
+import javafx.application.Platform;
+import javafx.fxml.FXMLLoader;
+import javafx.scene.Parent;
+import javafx.scene.Scene;
+import javafx.stage.Stage;
+
+import java.io.File;
+import java.io.IOException;
+
+/** This class runs the application.*/
+public class MainApplication extends Application {
+ /**Starts the application using given in parameters size of game board.*/
+ @Override
+ public void start(Stage primaryStage) {
+ Parent root = null;
+ try {
+ root = FXMLLoader.load(new File("src/main/resources/menu.fxml").toURI().toURL());
+ } catch (IOException e) {
+ Platform.exit();
+ }
+ primaryStage.setTitle("Menu");
+ assert root != null;
+ primaryStage.setScene(new Scene(root, 400, 600));
+ primaryStage.show();
+ }
+
+ /**
+ * Runs the program.
+ * @param args first argument is game board size.
+ */
+ public static void main(String[] args) {
+ Application.launch(args);
+ }
+}
diff --git a/term2/hw4/src/main/java/spbau/eliseeva/gui/MenuController.java b/term2/hw4/src/main/java/spbau/eliseeva/gui/MenuController.java
new file mode 100644
index 0000000..977bb81
--- /dev/null
+++ b/term2/hw4/src/main/java/spbau/eliseeva/gui/MenuController.java
@@ -0,0 +1,32 @@
+package spbau.eliseeva.gui;
+
+import javafx.fxml.FXML;
+import javafx.scene.control.Button;
+import javafx.scene.control.TextField;
+import javafx.stage.Stage;
+
+/** Controller for the menu.*/
+public class MenuController {
+ /** Button to push to connect to server.*/
+ @FXML
+ Button connectButton;
+
+ /** Name of host*/
+ @FXML
+ TextField hostName;
+
+ /** Number of port */
+ @FXML
+ TextField portNumber;
+
+ /** Gives the needed tasks to all the buttons: to open the needed window.*/
+ @FXML
+ public void initialize() {
+ connectButton.setFocusTraversable(false);
+ connectButton.setOnMouseClicked((event) -> {
+ Stage stage = (Stage) connectButton.getScene().getWindow();
+ stage.setScene(new FoldersController("/", Integer.parseInt(portNumber.getText()), hostName.getText()).getScene());
+ stage.show();
+ });
+ }
+}
\ No newline at end of file
diff --git a/term2/hw4/src/main/java/spbau/eliseeva/gui/SaveController.java b/term2/hw4/src/main/java/spbau/eliseeva/gui/SaveController.java
new file mode 100644
index 0000000..13231c1
--- /dev/null
+++ b/term2/hw4/src/main/java/spbau/eliseeva/gui/SaveController.java
@@ -0,0 +1,36 @@
+package spbau.eliseeva.gui;
+
+import javafx.fxml.FXML;
+import javafx.scene.control.Button;
+import javafx.scene.control.TextField;
+import javafx.stage.Stage;
+import spbau.eliseeva.ftp.FTPClient;
+
+import java.io.IOException;
+
+/** Controller for saving file */
+public class SaveController {
+ /** button to save the file*/
+ @FXML
+ Button saveButton;
+
+ /** name of file to save*/
+ @FXML
+ TextField fileName;
+
+ /**
+ * Gives a task to the button
+ * @param client client giving the result
+ * @param oldFileName name of file on server
+ */
+ void initialize(FTPClient client, String oldFileName) {
+ saveButton.setFocusTraversable(false);
+ saveButton.setOnMouseClicked((event) -> {
+ try {
+ client.getAnswer(oldFileName, fileName.getText());
+ } catch (IOException ignored) {
+ }
+ ((Stage)saveButton.getScene().getWindow()).close();
+ });
+ }
+}
diff --git a/term2/hw4/src/main/resources/menu.fxml b/term2/hw4/src/main/resources/menu.fxml
new file mode 100644
index 0000000..5420a1e
--- /dev/null
+++ b/term2/hw4/src/main/resources/menu.fxml
@@ -0,0 +1,51 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/term2/hw4/src/main/resources/save.fxml b/term2/hw4/src/main/resources/save.fxml
new file mode 100644
index 0000000..781003c
--- /dev/null
+++ b/term2/hw4/src/main/resources/save.fxml
@@ -0,0 +1,38 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/term2/hw4/src/test/java/spbau/eliseeva/ftp/FTPTest.java b/term2/hw4/src/test/java/spbau/eliseeva/ftp/FTPTest.java
new file mode 100644
index 0000000..bf24179
--- /dev/null
+++ b/term2/hw4/src/test/java/spbau/eliseeva/ftp/FTPTest.java
@@ -0,0 +1,133 @@
+package spbau.eliseeva.ftp;
+
+import org.junit.Test;
+
+import java.io.*;
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.*;
+
+/** Tests for FTPClient and FTPServer.*/
+public class FTPTest {
+ /** Checks if the server works as expected. */
+ @Test
+ public void testServer() {
+ InputStream serverInputStream = new ByteArrayInputStream(("1234\n\n").getBytes());
+ System.setIn(serverInputStream);
+ ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(byteArrayOutputStream));
+ FTPServer.main(new String[0]);
+ assertArrayEquals(("Write port number.\nPress enter to end.\n\n").getBytes(), byteArrayOutputStream.toByteArray());
+ }
+
+ /**
+ * Checks some list requests.
+ * @throws InterruptedException thrown if problems with threads.
+ * @throws IOException if problems with files
+ */
+ @Test
+ public void testList() throws InterruptedException, IOException {
+ runServer();
+ Map result = new FTPClient(1234, "localhost").listAnswer("src/test/resources/dir1");
+ Map expected = new HashMap<>();
+ expected.put("dir2", true);
+ expected.put("dir4", true);
+ expected.put("dir5", true);
+ assertEquals(expected, result);
+ expected.clear();
+ result = new FTPClient(1234, "localhost").listAnswer("src/test/resources/dir1/dir2");
+ expected.put("dir3", true);
+ expected.put("file1", false);
+ assertEquals(expected, result);
+ expected.clear();
+ delete(new File("results"));
+ }
+
+ /**
+ * Checks some get requests.
+ * @throws InterruptedException thrown if problems with threads.
+ * @throws IOException if problems with files
+ */
+ @Test
+ public void testGet() throws InterruptedException, IOException {
+ runServer();
+ new FTPClient(1234, "localhost").getAnswer("src/test/resources/dir1/dir4/file3", "get0");
+ byte[] bytes = new byte[5];
+ (new FileInputStream(new File("results/get0"))).read(bytes);
+ assertArrayEquals(("file3").getBytes(),bytes);
+ delete(new File("results"));
+ }
+
+ /**
+ * Checks if two clients can work with same server.
+ * @throws InterruptedException thrown if problems with threads.
+ */
+ @Test
+ public void testTwoClients() throws InterruptedException {
+ runServer();
+ Thread thread1 = new Thread(() -> {
+ Map result = null;
+ try {
+ result = new FTPClient(1234, "localhost").listAnswer("src/test/resources/dir1/dir2/dir3");
+ } catch (IOException ignored) {
+ }
+ Map expected = new HashMap<>();
+ expected.put("file2", false);
+ expected.put("file5", false);
+ assertEquals(expected, result);
+ delete(new File("results"));
+ });
+ Thread thread2 = new Thread(() -> {
+ try {
+ new FTPClient(1234, "localhost").getAnswer("src/test/resources/dir1/dir2/dir3/file5", "get0");
+ } catch (IOException ignored) {
+ }
+ byte[] bytes = new byte[5];
+ try {
+ (new FileInputStream(new File("results/get0"))).read(bytes);
+ } catch (IOException ignored) {
+ }
+ assertArrayEquals(("file5").getBytes(),bytes);
+
+ delete(new File("results"));
+ });
+ thread1.start();
+ thread2.start();
+ }
+
+ /**
+ * Starts working of server.
+ * @throws InterruptedException thrown if problems with threads.
+ */
+ private void runServer() throws InterruptedException {
+ InputStream serverInputStream = new ByteArrayInputStream(("1234\n\n").getBytes());
+ Thread thread = new Thread(() -> {
+ System.setIn(serverInputStream);
+ System.setOut(new PrintStream(new ByteArrayOutputStream()));
+ FTPServer.main(new String[0]);
+ });
+ thread.setDaemon(true);
+ thread.start();
+ Thread.sleep(1000);
+ }
+
+ /**
+ * Delete file or directory.
+ * @param file file to delete
+ */
+ private void delete(File file) {
+ if (!file.exists()) {
+ return;
+ }
+ if (file.isDirectory()) {
+ for(File f : file.listFiles()) {
+ delete(f);
+ }
+ file.delete();
+ } else {
+ file.delete();
+ }
+ }
+
+}
\ No newline at end of file
diff --git a/term2/hw4/src/test/resources/dir1/dir2/dir3/file2 b/term2/hw4/src/test/resources/dir1/dir2/dir3/file2
new file mode 100644
index 0000000..30d67d4
--- /dev/null
+++ b/term2/hw4/src/test/resources/dir1/dir2/dir3/file2
@@ -0,0 +1 @@
+file2
\ No newline at end of file
diff --git a/term2/hw4/src/test/resources/dir1/dir2/dir3/file5 b/term2/hw4/src/test/resources/dir1/dir2/dir3/file5
new file mode 100644
index 0000000..d92b9c3
--- /dev/null
+++ b/term2/hw4/src/test/resources/dir1/dir2/dir3/file5
@@ -0,0 +1 @@
+file5
\ No newline at end of file
diff --git a/term2/hw4/src/test/resources/dir1/dir2/file1 b/term2/hw4/src/test/resources/dir1/dir2/file1
new file mode 100644
index 0000000..08219db
--- /dev/null
+++ b/term2/hw4/src/test/resources/dir1/dir2/file1
@@ -0,0 +1 @@
+file1
\ No newline at end of file
diff --git a/term2/hw4/src/test/resources/dir1/dir4/file3 b/term2/hw4/src/test/resources/dir1/dir4/file3
new file mode 100644
index 0000000..873fb8d
--- /dev/null
+++ b/term2/hw4/src/test/resources/dir1/dir4/file3
@@ -0,0 +1 @@
+file3
\ No newline at end of file
diff --git a/term2/hw4/src/test/resources/dir1/dir5/file4 b/term2/hw4/src/test/resources/dir1/dir5/file4
new file mode 100644
index 0000000..eed6780
--- /dev/null
+++ b/term2/hw4/src/test/resources/dir1/dir5/file4
@@ -0,0 +1 @@
+file4
\ No newline at end of file